]> Git Repo - qemu.git/blob - block/qcow2.c
qcow2: use byte-based read in qcow2_decompress_cluster
[qemu.git] / 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
25 #include "qemu/osdep.h"
26
27 #define ZLIB_CONST
28 #include <zlib.h>
29
30 #include "block/block_int.h"
31 #include "block/qdict.h"
32 #include "sysemu/block-backend.h"
33 #include "qemu/module.h"
34 #include "qcow2.h"
35 #include "qemu/error-report.h"
36 #include "qapi/error.h"
37 #include "qapi/qapi-events-block-core.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qstring.h"
40 #include "trace.h"
41 #include "qemu/option_int.h"
42 #include "qemu/cutils.h"
43 #include "qemu/bswap.h"
44 #include "qapi/qobject-input-visitor.h"
45 #include "qapi/qapi-visit-block-core.h"
46 #include "crypto.h"
47 #include "block/thread-pool.h"
48
49 /*
50   Differences with QCOW:
51
52   - Support for multiple incremental snapshots.
53   - Memory management by reference counts.
54   - Clusters which have a reference count of one have the bit
55     QCOW_OFLAG_COPIED to optimize write performance.
56   - Size of compressed clusters is stored in sectors to reduce bit usage
57     in the cluster offsets.
58   - Support for storing additional data (such as the VM state) in the
59     snapshots.
60   - If a backing store is used, the cluster size is not constrained
61     (could be backported to QCOW).
62   - L2 tables have always a size of one cluster.
63 */
64
65
66 typedef struct {
67     uint32_t magic;
68     uint32_t len;
69 } QEMU_PACKED QCowExtension;
70
71 #define  QCOW2_EXT_MAGIC_END 0
72 #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
73 #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
74 #define  QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
75 #define  QCOW2_EXT_MAGIC_BITMAPS 0x23852875
76
77 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
78 {
79     const QCowHeader *cow_header = (const void *)buf;
80
81     if (buf_size >= sizeof(QCowHeader) &&
82         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
83         be32_to_cpu(cow_header->version) >= 2)
84         return 100;
85     else
86         return 0;
87 }
88
89
90 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
91                                           uint8_t *buf, size_t buflen,
92                                           void *opaque, Error **errp)
93 {
94     BlockDriverState *bs = opaque;
95     BDRVQcow2State *s = bs->opaque;
96     ssize_t ret;
97
98     if ((offset + buflen) > s->crypto_header.length) {
99         error_setg(errp, "Request for data outside of extension header");
100         return -1;
101     }
102
103     ret = bdrv_pread(bs->file,
104                      s->crypto_header.offset + offset, buf, buflen);
105     if (ret < 0) {
106         error_setg_errno(errp, -ret, "Could not read encryption header");
107         return -1;
108     }
109     return ret;
110 }
111
112
113 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
114                                           void *opaque, Error **errp)
115 {
116     BlockDriverState *bs = opaque;
117     BDRVQcow2State *s = bs->opaque;
118     int64_t ret;
119     int64_t clusterlen;
120
121     ret = qcow2_alloc_clusters(bs, headerlen);
122     if (ret < 0) {
123         error_setg_errno(errp, -ret,
124                          "Cannot allocate cluster for LUKS header size %zu",
125                          headerlen);
126         return -1;
127     }
128
129     s->crypto_header.length = headerlen;
130     s->crypto_header.offset = ret;
131
132     /* Zero fill remaining space in cluster so it has predictable
133      * content in case of future spec changes */
134     clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
135     assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
136     ret = bdrv_pwrite_zeroes(bs->file,
137                              ret + headerlen,
138                              clusterlen - headerlen, 0);
139     if (ret < 0) {
140         error_setg_errno(errp, -ret, "Could not zero fill encryption header");
141         return -1;
142     }
143
144     return ret;
145 }
146
147
148 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
149                                            const uint8_t *buf, size_t buflen,
150                                            void *opaque, Error **errp)
151 {
152     BlockDriverState *bs = opaque;
153     BDRVQcow2State *s = bs->opaque;
154     ssize_t ret;
155
156     if ((offset + buflen) > s->crypto_header.length) {
157         error_setg(errp, "Request for data outside of extension header");
158         return -1;
159     }
160
161     ret = bdrv_pwrite(bs->file,
162                       s->crypto_header.offset + offset, buf, buflen);
163     if (ret < 0) {
164         error_setg_errno(errp, -ret, "Could not read encryption header");
165         return -1;
166     }
167     return ret;
168 }
169
170
171 /* 
172  * read qcow2 extension and fill bs
173  * start reading from start_offset
174  * finish reading upon magic of value 0 or when end_offset reached
175  * unknown magic is skipped (future extension this version knows nothing about)
176  * return 0 upon success, non-0 otherwise
177  */
178 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
179                                  uint64_t end_offset, void **p_feature_table,
180                                  int flags, bool *need_update_header,
181                                  Error **errp)
182 {
183     BDRVQcow2State *s = bs->opaque;
184     QCowExtension ext;
185     uint64_t offset;
186     int ret;
187     Qcow2BitmapHeaderExt bitmaps_ext;
188
189     if (need_update_header != NULL) {
190         *need_update_header = false;
191     }
192
193 #ifdef DEBUG_EXT
194     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
195 #endif
196     offset = start_offset;
197     while (offset < end_offset) {
198
199 #ifdef DEBUG_EXT
200         /* Sanity check */
201         if (offset > s->cluster_size)
202             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
203
204         printf("attempting to read extended header in offset %lu\n", offset);
205 #endif
206
207         ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
208         if (ret < 0) {
209             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
210                              "pread fail from offset %" PRIu64, offset);
211             return 1;
212         }
213         ext.magic = be32_to_cpu(ext.magic);
214         ext.len = be32_to_cpu(ext.len);
215         offset += sizeof(ext);
216 #ifdef DEBUG_EXT
217         printf("ext.magic = 0x%x\n", ext.magic);
218 #endif
219         if (offset > end_offset || ext.len > end_offset - offset) {
220             error_setg(errp, "Header extension too large");
221             return -EINVAL;
222         }
223
224         switch (ext.magic) {
225         case QCOW2_EXT_MAGIC_END:
226             return 0;
227
228         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
229             if (ext.len >= sizeof(bs->backing_format)) {
230                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
231                            " too large (>=%zu)", ext.len,
232                            sizeof(bs->backing_format));
233                 return 2;
234             }
235             ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
236             if (ret < 0) {
237                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
238                                  "Could not read format name");
239                 return 3;
240             }
241             bs->backing_format[ext.len] = '\0';
242             s->image_backing_format = g_strdup(bs->backing_format);
243 #ifdef DEBUG_EXT
244             printf("Qcow2: Got format extension %s\n", bs->backing_format);
245 #endif
246             break;
247
248         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
249             if (p_feature_table != NULL) {
250                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
251                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
252                 if (ret < 0) {
253                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
254                                      "Could not read table");
255                     return ret;
256                 }
257
258                 *p_feature_table = feature_table;
259             }
260             break;
261
262         case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
263             unsigned int cflags = 0;
264             if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
265                 error_setg(errp, "CRYPTO header extension only "
266                            "expected with LUKS encryption method");
267                 return -EINVAL;
268             }
269             if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
270                 error_setg(errp, "CRYPTO header extension size %u, "
271                            "but expected size %zu", ext.len,
272                            sizeof(Qcow2CryptoHeaderExtension));
273                 return -EINVAL;
274             }
275
276             ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
277             if (ret < 0) {
278                 error_setg_errno(errp, -ret,
279                                  "Unable to read CRYPTO header extension");
280                 return ret;
281             }
282             s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
283             s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
284
285             if ((s->crypto_header.offset % s->cluster_size) != 0) {
286                 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
287                            "not a multiple of cluster size '%u'",
288                            s->crypto_header.offset, s->cluster_size);
289                 return -EINVAL;
290             }
291
292             if (flags & BDRV_O_NO_IO) {
293                 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
294             }
295             s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
296                                            qcow2_crypto_hdr_read_func,
297                                            bs, cflags, 1, errp);
298             if (!s->crypto) {
299                 return -EINVAL;
300             }
301         }   break;
302
303         case QCOW2_EXT_MAGIC_BITMAPS:
304             if (ext.len != sizeof(bitmaps_ext)) {
305                 error_setg_errno(errp, -ret, "bitmaps_ext: "
306                                  "Invalid extension length");
307                 return -EINVAL;
308             }
309
310             if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
311                 if (s->qcow_version < 3) {
312                     /* Let's be a bit more specific */
313                     warn_report("This qcow2 v2 image contains bitmaps, but "
314                                 "they may have been modified by a program "
315                                 "without persistent bitmap support; so now "
316                                 "they must all be considered inconsistent");
317                 } else {
318                     warn_report("a program lacking bitmap support "
319                                 "modified this file, so all bitmaps are now "
320                                 "considered inconsistent");
321                 }
322                 error_printf("Some clusters may be leaked, "
323                              "run 'qemu-img check -r' on the image "
324                              "file to fix.");
325                 if (need_update_header != NULL) {
326                     /* Updating is needed to drop invalid bitmap extension. */
327                     *need_update_header = true;
328                 }
329                 break;
330             }
331
332             ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
333             if (ret < 0) {
334                 error_setg_errno(errp, -ret, "bitmaps_ext: "
335                                  "Could not read ext header");
336                 return ret;
337             }
338
339             if (bitmaps_ext.reserved32 != 0) {
340                 error_setg_errno(errp, -ret, "bitmaps_ext: "
341                                  "Reserved field is not zero");
342                 return -EINVAL;
343             }
344
345             bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
346             bitmaps_ext.bitmap_directory_size =
347                 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
348             bitmaps_ext.bitmap_directory_offset =
349                 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
350
351             if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
352                 error_setg(errp,
353                            "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
354                            "exceeding the QEMU supported maximum of %d",
355                            bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
356                 return -EINVAL;
357             }
358
359             if (bitmaps_ext.nb_bitmaps == 0) {
360                 error_setg(errp, "found bitmaps extension with zero bitmaps");
361                 return -EINVAL;
362             }
363
364             if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
365                 error_setg(errp, "bitmaps_ext: "
366                                  "invalid bitmap directory offset");
367                 return -EINVAL;
368             }
369
370             if (bitmaps_ext.bitmap_directory_size >
371                 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
372                 error_setg(errp, "bitmaps_ext: "
373                                  "bitmap directory size (%" PRIu64 ") exceeds "
374                                  "the maximum supported size (%d)",
375                                  bitmaps_ext.bitmap_directory_size,
376                                  QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
377                 return -EINVAL;
378             }
379
380             s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
381             s->bitmap_directory_offset =
382                     bitmaps_ext.bitmap_directory_offset;
383             s->bitmap_directory_size =
384                     bitmaps_ext.bitmap_directory_size;
385
386 #ifdef DEBUG_EXT
387             printf("Qcow2: Got bitmaps extension: "
388                    "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
389                    s->bitmap_directory_offset, s->nb_bitmaps);
390 #endif
391             break;
392
393         default:
394             /* unknown magic - save it in case we need to rewrite the header */
395             /* If you add a new feature, make sure to also update the fast
396              * path of qcow2_make_empty() to deal with it. */
397             {
398                 Qcow2UnknownHeaderExtension *uext;
399
400                 uext = g_malloc0(sizeof(*uext)  + ext.len);
401                 uext->magic = ext.magic;
402                 uext->len = ext.len;
403                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
404
405                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
406                 if (ret < 0) {
407                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
408                                      "Could not read data");
409                     return ret;
410                 }
411             }
412             break;
413         }
414
415         offset += ((ext.len + 7) & ~7);
416     }
417
418     return 0;
419 }
420
421 static void cleanup_unknown_header_ext(BlockDriverState *bs)
422 {
423     BDRVQcow2State *s = bs->opaque;
424     Qcow2UnknownHeaderExtension *uext, *next;
425
426     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
427         QLIST_REMOVE(uext, next);
428         g_free(uext);
429     }
430 }
431
432 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
433                                        uint64_t mask)
434 {
435     char *features = g_strdup("");
436     char *old;
437
438     while (table && table->name[0] != '\0') {
439         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
440             if (mask & (1ULL << table->bit)) {
441                 old = features;
442                 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
443                                            table->name);
444                 g_free(old);
445                 mask &= ~(1ULL << table->bit);
446             }
447         }
448         table++;
449     }
450
451     if (mask) {
452         old = features;
453         features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
454                                    old, *old ? ", " : "", mask);
455         g_free(old);
456     }
457
458     error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
459     g_free(features);
460 }
461
462 /*
463  * Sets the dirty bit and flushes afterwards if necessary.
464  *
465  * The incompatible_features bit is only set if the image file header was
466  * updated successfully.  Therefore it is not required to check the return
467  * value of this function.
468  */
469 int qcow2_mark_dirty(BlockDriverState *bs)
470 {
471     BDRVQcow2State *s = bs->opaque;
472     uint64_t val;
473     int ret;
474
475     assert(s->qcow_version >= 3);
476
477     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
478         return 0; /* already dirty */
479     }
480
481     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
482     ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
483                       &val, sizeof(val));
484     if (ret < 0) {
485         return ret;
486     }
487     ret = bdrv_flush(bs->file->bs);
488     if (ret < 0) {
489         return ret;
490     }
491
492     /* Only treat image as dirty if the header was updated successfully */
493     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
494     return 0;
495 }
496
497 /*
498  * Clears the dirty bit and flushes before if necessary.  Only call this
499  * function when there are no pending requests, it does not guard against
500  * concurrent requests dirtying the image.
501  */
502 static int qcow2_mark_clean(BlockDriverState *bs)
503 {
504     BDRVQcow2State *s = bs->opaque;
505
506     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
507         int ret;
508
509         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
510
511         ret = qcow2_flush_caches(bs);
512         if (ret < 0) {
513             return ret;
514         }
515
516         return qcow2_update_header(bs);
517     }
518     return 0;
519 }
520
521 /*
522  * Marks the image as corrupt.
523  */
524 int qcow2_mark_corrupt(BlockDriverState *bs)
525 {
526     BDRVQcow2State *s = bs->opaque;
527
528     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
529     return qcow2_update_header(bs);
530 }
531
532 /*
533  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
534  * before if necessary.
535  */
536 int qcow2_mark_consistent(BlockDriverState *bs)
537 {
538     BDRVQcow2State *s = bs->opaque;
539
540     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
541         int ret = qcow2_flush_caches(bs);
542         if (ret < 0) {
543             return ret;
544         }
545
546         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
547         return qcow2_update_header(bs);
548     }
549     return 0;
550 }
551
552 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
553                                               BdrvCheckResult *result,
554                                               BdrvCheckMode fix)
555 {
556     int ret = qcow2_check_refcounts(bs, result, fix);
557     if (ret < 0) {
558         return ret;
559     }
560
561     if (fix && result->check_errors == 0 && result->corruptions == 0) {
562         ret = qcow2_mark_clean(bs);
563         if (ret < 0) {
564             return ret;
565         }
566         return qcow2_mark_consistent(bs);
567     }
568     return ret;
569 }
570
571 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
572                                        BdrvCheckResult *result,
573                                        BdrvCheckMode fix)
574 {
575     BDRVQcow2State *s = bs->opaque;
576     int ret;
577
578     qemu_co_mutex_lock(&s->lock);
579     ret = qcow2_co_check_locked(bs, result, fix);
580     qemu_co_mutex_unlock(&s->lock);
581     return ret;
582 }
583
584 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
585                          uint64_t entries, size_t entry_len,
586                          int64_t max_size_bytes, const char *table_name,
587                          Error **errp)
588 {
589     BDRVQcow2State *s = bs->opaque;
590
591     if (entries > max_size_bytes / entry_len) {
592         error_setg(errp, "%s too large", table_name);
593         return -EFBIG;
594     }
595
596     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
597      * because values will be passed to qemu functions taking int64_t. */
598     if ((INT64_MAX - entries * entry_len < offset) ||
599         (offset_into_cluster(s, offset) != 0)) {
600         error_setg(errp, "%s offset invalid", table_name);
601         return -EINVAL;
602     }
603
604     return 0;
605 }
606
607 static QemuOptsList qcow2_runtime_opts = {
608     .name = "qcow2",
609     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
610     .desc = {
611         {
612             .name = QCOW2_OPT_LAZY_REFCOUNTS,
613             .type = QEMU_OPT_BOOL,
614             .help = "Postpone refcount updates",
615         },
616         {
617             .name = QCOW2_OPT_DISCARD_REQUEST,
618             .type = QEMU_OPT_BOOL,
619             .help = "Pass guest discard requests to the layer below",
620         },
621         {
622             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
623             .type = QEMU_OPT_BOOL,
624             .help = "Generate discard requests when snapshot related space "
625                     "is freed",
626         },
627         {
628             .name = QCOW2_OPT_DISCARD_OTHER,
629             .type = QEMU_OPT_BOOL,
630             .help = "Generate discard requests when other clusters are freed",
631         },
632         {
633             .name = QCOW2_OPT_OVERLAP,
634             .type = QEMU_OPT_STRING,
635             .help = "Selects which overlap checks to perform from a range of "
636                     "templates (none, constant, cached, all)",
637         },
638         {
639             .name = QCOW2_OPT_OVERLAP_TEMPLATE,
640             .type = QEMU_OPT_STRING,
641             .help = "Selects which overlap checks to perform from a range of "
642                     "templates (none, constant, cached, all)",
643         },
644         {
645             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
646             .type = QEMU_OPT_BOOL,
647             .help = "Check for unintended writes into the main qcow2 header",
648         },
649         {
650             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
651             .type = QEMU_OPT_BOOL,
652             .help = "Check for unintended writes into the active L1 table",
653         },
654         {
655             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
656             .type = QEMU_OPT_BOOL,
657             .help = "Check for unintended writes into an active L2 table",
658         },
659         {
660             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
661             .type = QEMU_OPT_BOOL,
662             .help = "Check for unintended writes into the refcount table",
663         },
664         {
665             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
666             .type = QEMU_OPT_BOOL,
667             .help = "Check for unintended writes into a refcount block",
668         },
669         {
670             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
671             .type = QEMU_OPT_BOOL,
672             .help = "Check for unintended writes into the snapshot table",
673         },
674         {
675             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
676             .type = QEMU_OPT_BOOL,
677             .help = "Check for unintended writes into an inactive L1 table",
678         },
679         {
680             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
681             .type = QEMU_OPT_BOOL,
682             .help = "Check for unintended writes into an inactive L2 table",
683         },
684         {
685             .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
686             .type = QEMU_OPT_BOOL,
687             .help = "Check for unintended writes into the bitmap directory",
688         },
689         {
690             .name = QCOW2_OPT_CACHE_SIZE,
691             .type = QEMU_OPT_SIZE,
692             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
693                     "cache size",
694         },
695         {
696             .name = QCOW2_OPT_L2_CACHE_SIZE,
697             .type = QEMU_OPT_SIZE,
698             .help = "Maximum L2 table cache size",
699         },
700         {
701             .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
702             .type = QEMU_OPT_SIZE,
703             .help = "Size of each entry in the L2 cache",
704         },
705         {
706             .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
707             .type = QEMU_OPT_SIZE,
708             .help = "Maximum refcount block cache size",
709         },
710         {
711             .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
712             .type = QEMU_OPT_NUMBER,
713             .help = "Clean unused cache entries after this time (in seconds)",
714         },
715         BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
716             "ID of secret providing qcow2 AES key or LUKS passphrase"),
717         { /* end of list */ }
718     },
719 };
720
721 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
722     [QCOW2_OL_MAIN_HEADER_BITNR]      = QCOW2_OPT_OVERLAP_MAIN_HEADER,
723     [QCOW2_OL_ACTIVE_L1_BITNR]        = QCOW2_OPT_OVERLAP_ACTIVE_L1,
724     [QCOW2_OL_ACTIVE_L2_BITNR]        = QCOW2_OPT_OVERLAP_ACTIVE_L2,
725     [QCOW2_OL_REFCOUNT_TABLE_BITNR]   = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
726     [QCOW2_OL_REFCOUNT_BLOCK_BITNR]   = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
727     [QCOW2_OL_SNAPSHOT_TABLE_BITNR]   = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
728     [QCOW2_OL_INACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_INACTIVE_L1,
729     [QCOW2_OL_INACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_INACTIVE_L2,
730     [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
731 };
732
733 static void cache_clean_timer_cb(void *opaque)
734 {
735     BlockDriverState *bs = opaque;
736     BDRVQcow2State *s = bs->opaque;
737     qcow2_cache_clean_unused(s->l2_table_cache);
738     qcow2_cache_clean_unused(s->refcount_block_cache);
739     timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
740               (int64_t) s->cache_clean_interval * 1000);
741 }
742
743 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
744 {
745     BDRVQcow2State *s = bs->opaque;
746     if (s->cache_clean_interval > 0) {
747         s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
748                                              SCALE_MS, cache_clean_timer_cb,
749                                              bs);
750         timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
751                   (int64_t) s->cache_clean_interval * 1000);
752     }
753 }
754
755 static void cache_clean_timer_del(BlockDriverState *bs)
756 {
757     BDRVQcow2State *s = bs->opaque;
758     if (s->cache_clean_timer) {
759         timer_del(s->cache_clean_timer);
760         timer_free(s->cache_clean_timer);
761         s->cache_clean_timer = NULL;
762     }
763 }
764
765 static void qcow2_detach_aio_context(BlockDriverState *bs)
766 {
767     cache_clean_timer_del(bs);
768 }
769
770 static void qcow2_attach_aio_context(BlockDriverState *bs,
771                                      AioContext *new_context)
772 {
773     cache_clean_timer_init(bs, new_context);
774 }
775
776 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
777                              uint64_t *l2_cache_size,
778                              uint64_t *l2_cache_entry_size,
779                              uint64_t *refcount_cache_size, Error **errp)
780 {
781     BDRVQcow2State *s = bs->opaque;
782     uint64_t combined_cache_size, l2_cache_max_setting;
783     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
784     int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
785     uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
786     uint64_t max_l2_cache = virtual_disk_size / (s->cluster_size / 8);
787
788     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
789     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
790     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
791
792     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
793     l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
794                                              DEFAULT_L2_CACHE_MAX_SIZE);
795     *refcount_cache_size = qemu_opt_get_size(opts,
796                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
797
798     *l2_cache_entry_size = qemu_opt_get_size(
799         opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
800
801     *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
802
803     if (combined_cache_size_set) {
804         if (l2_cache_size_set && refcount_cache_size_set) {
805             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
806                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
807                        "at the same time");
808             return;
809         } else if (l2_cache_size_set &&
810                    (l2_cache_max_setting > combined_cache_size)) {
811             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
812                        QCOW2_OPT_CACHE_SIZE);
813             return;
814         } else if (*refcount_cache_size > combined_cache_size) {
815             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
816                        QCOW2_OPT_CACHE_SIZE);
817             return;
818         }
819
820         if (l2_cache_size_set) {
821             *refcount_cache_size = combined_cache_size - *l2_cache_size;
822         } else if (refcount_cache_size_set) {
823             *l2_cache_size = combined_cache_size - *refcount_cache_size;
824         } else {
825             /* Assign as much memory as possible to the L2 cache, and
826              * use the remainder for the refcount cache */
827             if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
828                 *l2_cache_size = max_l2_cache;
829                 *refcount_cache_size = combined_cache_size - *l2_cache_size;
830             } else {
831                 *refcount_cache_size =
832                     MIN(combined_cache_size, min_refcount_cache);
833                 *l2_cache_size = combined_cache_size - *refcount_cache_size;
834             }
835         }
836     }
837     /* l2_cache_size and refcount_cache_size are ensured to have at least
838      * their minimum values in qcow2_update_options_prepare() */
839
840     if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
841         *l2_cache_entry_size > s->cluster_size ||
842         !is_power_of_2(*l2_cache_entry_size)) {
843         error_setg(errp, "L2 cache entry size must be a power of two "
844                    "between %d and the cluster size (%d)",
845                    1 << MIN_CLUSTER_BITS, s->cluster_size);
846         return;
847     }
848 }
849
850 typedef struct Qcow2ReopenState {
851     Qcow2Cache *l2_table_cache;
852     Qcow2Cache *refcount_block_cache;
853     int l2_slice_size; /* Number of entries in a slice of the L2 table */
854     bool use_lazy_refcounts;
855     int overlap_check;
856     bool discard_passthrough[QCOW2_DISCARD_MAX];
857     uint64_t cache_clean_interval;
858     QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
859 } Qcow2ReopenState;
860
861 static int qcow2_update_options_prepare(BlockDriverState *bs,
862                                         Qcow2ReopenState *r,
863                                         QDict *options, int flags,
864                                         Error **errp)
865 {
866     BDRVQcow2State *s = bs->opaque;
867     QemuOpts *opts = NULL;
868     const char *opt_overlap_check, *opt_overlap_check_template;
869     int overlap_check_template = 0;
870     uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
871     int i;
872     const char *encryptfmt;
873     QDict *encryptopts = NULL;
874     Error *local_err = NULL;
875     int ret;
876
877     qdict_extract_subqdict(options, &encryptopts, "encrypt.");
878     encryptfmt = qdict_get_try_str(encryptopts, "format");
879
880     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
881     qemu_opts_absorb_qdict(opts, options, &local_err);
882     if (local_err) {
883         error_propagate(errp, local_err);
884         ret = -EINVAL;
885         goto fail;
886     }
887
888     /* get L2 table/refcount block cache size from command line options */
889     read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
890                      &refcount_cache_size, &local_err);
891     if (local_err) {
892         error_propagate(errp, local_err);
893         ret = -EINVAL;
894         goto fail;
895     }
896
897     l2_cache_size /= l2_cache_entry_size;
898     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
899         l2_cache_size = MIN_L2_CACHE_SIZE;
900     }
901     if (l2_cache_size > INT_MAX) {
902         error_setg(errp, "L2 cache size too big");
903         ret = -EINVAL;
904         goto fail;
905     }
906
907     refcount_cache_size /= s->cluster_size;
908     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
909         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
910     }
911     if (refcount_cache_size > INT_MAX) {
912         error_setg(errp, "Refcount cache size too big");
913         ret = -EINVAL;
914         goto fail;
915     }
916
917     /* alloc new L2 table/refcount block cache, flush old one */
918     if (s->l2_table_cache) {
919         ret = qcow2_cache_flush(bs, s->l2_table_cache);
920         if (ret) {
921             error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
922             goto fail;
923         }
924     }
925
926     if (s->refcount_block_cache) {
927         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
928         if (ret) {
929             error_setg_errno(errp, -ret,
930                              "Failed to flush the refcount block cache");
931             goto fail;
932         }
933     }
934
935     r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
936     r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
937                                            l2_cache_entry_size);
938     r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
939                                                  s->cluster_size);
940     if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
941         error_setg(errp, "Could not allocate metadata caches");
942         ret = -ENOMEM;
943         goto fail;
944     }
945
946     /* New interval for cache cleanup timer */
947     r->cache_clean_interval =
948         qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
949                             DEFAULT_CACHE_CLEAN_INTERVAL);
950 #ifndef CONFIG_LINUX
951     if (r->cache_clean_interval != 0) {
952         error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
953                    " not supported on this host");
954         ret = -EINVAL;
955         goto fail;
956     }
957 #endif
958     if (r->cache_clean_interval > UINT_MAX) {
959         error_setg(errp, "Cache clean interval too big");
960         ret = -EINVAL;
961         goto fail;
962     }
963
964     /* lazy-refcounts; flush if going from enabled to disabled */
965     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
966         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
967     if (r->use_lazy_refcounts && s->qcow_version < 3) {
968         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
969                    "qemu 1.1 compatibility level");
970         ret = -EINVAL;
971         goto fail;
972     }
973
974     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
975         ret = qcow2_mark_clean(bs);
976         if (ret < 0) {
977             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
978             goto fail;
979         }
980     }
981
982     /* Overlap check options */
983     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
984     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
985     if (opt_overlap_check_template && opt_overlap_check &&
986         strcmp(opt_overlap_check_template, opt_overlap_check))
987     {
988         error_setg(errp, "Conflicting values for qcow2 options '"
989                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
990                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
991         ret = -EINVAL;
992         goto fail;
993     }
994     if (!opt_overlap_check) {
995         opt_overlap_check = opt_overlap_check_template ?: "cached";
996     }
997
998     if (!strcmp(opt_overlap_check, "none")) {
999         overlap_check_template = 0;
1000     } else if (!strcmp(opt_overlap_check, "constant")) {
1001         overlap_check_template = QCOW2_OL_CONSTANT;
1002     } else if (!strcmp(opt_overlap_check, "cached")) {
1003         overlap_check_template = QCOW2_OL_CACHED;
1004     } else if (!strcmp(opt_overlap_check, "all")) {
1005         overlap_check_template = QCOW2_OL_ALL;
1006     } else {
1007         error_setg(errp, "Unsupported value '%s' for qcow2 option "
1008                    "'overlap-check'. Allowed are any of the following: "
1009                    "none, constant, cached, all", opt_overlap_check);
1010         ret = -EINVAL;
1011         goto fail;
1012     }
1013
1014     r->overlap_check = 0;
1015     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1016         /* overlap-check defines a template bitmask, but every flag may be
1017          * overwritten through the associated boolean option */
1018         r->overlap_check |=
1019             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1020                               overlap_check_template & (1 << i)) << i;
1021     }
1022
1023     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1024     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1025     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1026         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1027                           flags & BDRV_O_UNMAP);
1028     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1029         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1030     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1031         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1032
1033     switch (s->crypt_method_header) {
1034     case QCOW_CRYPT_NONE:
1035         if (encryptfmt) {
1036             error_setg(errp, "No encryption in image header, but options "
1037                        "specified format '%s'", encryptfmt);
1038             ret = -EINVAL;
1039             goto fail;
1040         }
1041         break;
1042
1043     case QCOW_CRYPT_AES:
1044         if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1045             error_setg(errp,
1046                        "Header reported 'aes' encryption format but "
1047                        "options specify '%s'", encryptfmt);
1048             ret = -EINVAL;
1049             goto fail;
1050         }
1051         qdict_put_str(encryptopts, "format", "qcow");
1052         r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1053         break;
1054
1055     case QCOW_CRYPT_LUKS:
1056         if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1057             error_setg(errp,
1058                        "Header reported 'luks' encryption format but "
1059                        "options specify '%s'", encryptfmt);
1060             ret = -EINVAL;
1061             goto fail;
1062         }
1063         qdict_put_str(encryptopts, "format", "luks");
1064         r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1065         break;
1066
1067     default:
1068         error_setg(errp, "Unsupported encryption method %d",
1069                    s->crypt_method_header);
1070         break;
1071     }
1072     if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1073         ret = -EINVAL;
1074         goto fail;
1075     }
1076
1077     ret = 0;
1078 fail:
1079     qobject_unref(encryptopts);
1080     qemu_opts_del(opts);
1081     opts = NULL;
1082     return ret;
1083 }
1084
1085 static void qcow2_update_options_commit(BlockDriverState *bs,
1086                                         Qcow2ReopenState *r)
1087 {
1088     BDRVQcow2State *s = bs->opaque;
1089     int i;
1090
1091     if (s->l2_table_cache) {
1092         qcow2_cache_destroy(s->l2_table_cache);
1093     }
1094     if (s->refcount_block_cache) {
1095         qcow2_cache_destroy(s->refcount_block_cache);
1096     }
1097     s->l2_table_cache = r->l2_table_cache;
1098     s->refcount_block_cache = r->refcount_block_cache;
1099     s->l2_slice_size = r->l2_slice_size;
1100
1101     s->overlap_check = r->overlap_check;
1102     s->use_lazy_refcounts = r->use_lazy_refcounts;
1103
1104     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1105         s->discard_passthrough[i] = r->discard_passthrough[i];
1106     }
1107
1108     if (s->cache_clean_interval != r->cache_clean_interval) {
1109         cache_clean_timer_del(bs);
1110         s->cache_clean_interval = r->cache_clean_interval;
1111         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1112     }
1113
1114     qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1115     s->crypto_opts = r->crypto_opts;
1116 }
1117
1118 static void qcow2_update_options_abort(BlockDriverState *bs,
1119                                        Qcow2ReopenState *r)
1120 {
1121     if (r->l2_table_cache) {
1122         qcow2_cache_destroy(r->l2_table_cache);
1123     }
1124     if (r->refcount_block_cache) {
1125         qcow2_cache_destroy(r->refcount_block_cache);
1126     }
1127     qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1128 }
1129
1130 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1131                                 int flags, Error **errp)
1132 {
1133     Qcow2ReopenState r = {};
1134     int ret;
1135
1136     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1137     if (ret >= 0) {
1138         qcow2_update_options_commit(bs, &r);
1139     } else {
1140         qcow2_update_options_abort(bs, &r);
1141     }
1142
1143     return ret;
1144 }
1145
1146 /* Called with s->lock held.  */
1147 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1148                                       int flags, Error **errp)
1149 {
1150     BDRVQcow2State *s = bs->opaque;
1151     unsigned int len, i;
1152     int ret = 0;
1153     QCowHeader header;
1154     Error *local_err = NULL;
1155     uint64_t ext_end;
1156     uint64_t l1_vm_state_index;
1157     bool update_header = false;
1158
1159     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1160     if (ret < 0) {
1161         error_setg_errno(errp, -ret, "Could not read qcow2 header");
1162         goto fail;
1163     }
1164     header.magic = be32_to_cpu(header.magic);
1165     header.version = be32_to_cpu(header.version);
1166     header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1167     header.backing_file_size = be32_to_cpu(header.backing_file_size);
1168     header.size = be64_to_cpu(header.size);
1169     header.cluster_bits = be32_to_cpu(header.cluster_bits);
1170     header.crypt_method = be32_to_cpu(header.crypt_method);
1171     header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1172     header.l1_size = be32_to_cpu(header.l1_size);
1173     header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1174     header.refcount_table_clusters =
1175         be32_to_cpu(header.refcount_table_clusters);
1176     header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1177     header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1178
1179     if (header.magic != QCOW_MAGIC) {
1180         error_setg(errp, "Image is not in qcow2 format");
1181         ret = -EINVAL;
1182         goto fail;
1183     }
1184     if (header.version < 2 || header.version > 3) {
1185         error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1186         ret = -ENOTSUP;
1187         goto fail;
1188     }
1189
1190     s->qcow_version = header.version;
1191
1192     /* Initialise cluster size */
1193     if (header.cluster_bits < MIN_CLUSTER_BITS ||
1194         header.cluster_bits > MAX_CLUSTER_BITS) {
1195         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1196                    header.cluster_bits);
1197         ret = -EINVAL;
1198         goto fail;
1199     }
1200
1201     s->cluster_bits = header.cluster_bits;
1202     s->cluster_size = 1 << s->cluster_bits;
1203     s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1204
1205     /* Initialise version 3 header fields */
1206     if (header.version == 2) {
1207         header.incompatible_features    = 0;
1208         header.compatible_features      = 0;
1209         header.autoclear_features       = 0;
1210         header.refcount_order           = 4;
1211         header.header_length            = 72;
1212     } else {
1213         header.incompatible_features =
1214             be64_to_cpu(header.incompatible_features);
1215         header.compatible_features = be64_to_cpu(header.compatible_features);
1216         header.autoclear_features = be64_to_cpu(header.autoclear_features);
1217         header.refcount_order = be32_to_cpu(header.refcount_order);
1218         header.header_length = be32_to_cpu(header.header_length);
1219
1220         if (header.header_length < 104) {
1221             error_setg(errp, "qcow2 header too short");
1222             ret = -EINVAL;
1223             goto fail;
1224         }
1225     }
1226
1227     if (header.header_length > s->cluster_size) {
1228         error_setg(errp, "qcow2 header exceeds cluster size");
1229         ret = -EINVAL;
1230         goto fail;
1231     }
1232
1233     if (header.header_length > sizeof(header)) {
1234         s->unknown_header_fields_size = header.header_length - sizeof(header);
1235         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1236         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1237                          s->unknown_header_fields_size);
1238         if (ret < 0) {
1239             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1240                              "fields");
1241             goto fail;
1242         }
1243     }
1244
1245     if (header.backing_file_offset > s->cluster_size) {
1246         error_setg(errp, "Invalid backing file offset");
1247         ret = -EINVAL;
1248         goto fail;
1249     }
1250
1251     if (header.backing_file_offset) {
1252         ext_end = header.backing_file_offset;
1253     } else {
1254         ext_end = 1 << header.cluster_bits;
1255     }
1256
1257     /* Handle feature bits */
1258     s->incompatible_features    = header.incompatible_features;
1259     s->compatible_features      = header.compatible_features;
1260     s->autoclear_features       = header.autoclear_features;
1261
1262     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1263         void *feature_table = NULL;
1264         qcow2_read_extensions(bs, header.header_length, ext_end,
1265                               &feature_table, flags, NULL, NULL);
1266         report_unsupported_feature(errp, feature_table,
1267                                    s->incompatible_features &
1268                                    ~QCOW2_INCOMPAT_MASK);
1269         ret = -ENOTSUP;
1270         g_free(feature_table);
1271         goto fail;
1272     }
1273
1274     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1275         /* Corrupt images may not be written to unless they are being repaired
1276          */
1277         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1278             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1279                        "read/write");
1280             ret = -EACCES;
1281             goto fail;
1282         }
1283     }
1284
1285     /* Check support for various header values */
1286     if (header.refcount_order > 6) {
1287         error_setg(errp, "Reference count entry width too large; may not "
1288                    "exceed 64 bits");
1289         ret = -EINVAL;
1290         goto fail;
1291     }
1292     s->refcount_order = header.refcount_order;
1293     s->refcount_bits = 1 << s->refcount_order;
1294     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1295     s->refcount_max += s->refcount_max - 1;
1296
1297     s->crypt_method_header = header.crypt_method;
1298     if (s->crypt_method_header) {
1299         if (bdrv_uses_whitelist() &&
1300             s->crypt_method_header == QCOW_CRYPT_AES) {
1301             error_setg(errp,
1302                        "Use of AES-CBC encrypted qcow2 images is no longer "
1303                        "supported in system emulators");
1304             error_append_hint(errp,
1305                               "You can use 'qemu-img convert' to convert your "
1306                               "image to an alternative supported format, such "
1307                               "as unencrypted qcow2, or raw with the LUKS "
1308                               "format instead.\n");
1309             ret = -ENOSYS;
1310             goto fail;
1311         }
1312
1313         if (s->crypt_method_header == QCOW_CRYPT_AES) {
1314             s->crypt_physical_offset = false;
1315         } else {
1316             /* Assuming LUKS and any future crypt methods we
1317              * add will all use physical offsets, due to the
1318              * fact that the alternative is insecure...  */
1319             s->crypt_physical_offset = true;
1320         }
1321
1322         bs->encrypted = true;
1323     }
1324
1325     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1326     s->l2_size = 1 << s->l2_bits;
1327     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1328     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1329     s->refcount_block_size = 1 << s->refcount_block_bits;
1330     bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1331     s->csize_shift = (62 - (s->cluster_bits - 8));
1332     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1333     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1334
1335     s->refcount_table_offset = header.refcount_table_offset;
1336     s->refcount_table_size =
1337         header.refcount_table_clusters << (s->cluster_bits - 3);
1338
1339     if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1340         error_setg(errp, "Image does not contain a reference count table");
1341         ret = -EINVAL;
1342         goto fail;
1343     }
1344
1345     ret = qcow2_validate_table(bs, s->refcount_table_offset,
1346                                header.refcount_table_clusters,
1347                                s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1348                                "Reference count table", errp);
1349     if (ret < 0) {
1350         goto fail;
1351     }
1352
1353     /* The total size in bytes of the snapshot table is checked in
1354      * qcow2_read_snapshots() because the size of each snapshot is
1355      * variable and we don't know it yet.
1356      * Here we only check the offset and number of snapshots. */
1357     ret = qcow2_validate_table(bs, header.snapshots_offset,
1358                                header.nb_snapshots,
1359                                sizeof(QCowSnapshotHeader),
1360                                sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
1361                                "Snapshot table", errp);
1362     if (ret < 0) {
1363         goto fail;
1364     }
1365
1366     /* read the level 1 table */
1367     ret = qcow2_validate_table(bs, header.l1_table_offset,
1368                                header.l1_size, sizeof(uint64_t),
1369                                QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1370     if (ret < 0) {
1371         goto fail;
1372     }
1373     s->l1_size = header.l1_size;
1374     s->l1_table_offset = header.l1_table_offset;
1375
1376     l1_vm_state_index = size_to_l1(s, header.size);
1377     if (l1_vm_state_index > INT_MAX) {
1378         error_setg(errp, "Image is too big");
1379         ret = -EFBIG;
1380         goto fail;
1381     }
1382     s->l1_vm_state_index = l1_vm_state_index;
1383
1384     /* the L1 table must contain at least enough entries to put
1385        header.size bytes */
1386     if (s->l1_size < s->l1_vm_state_index) {
1387         error_setg(errp, "L1 table is too small");
1388         ret = -EINVAL;
1389         goto fail;
1390     }
1391
1392     if (s->l1_size > 0) {
1393         s->l1_table = qemu_try_blockalign(bs->file->bs,
1394             ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1395         if (s->l1_table == NULL) {
1396             error_setg(errp, "Could not allocate L1 table");
1397             ret = -ENOMEM;
1398             goto fail;
1399         }
1400         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1401                          s->l1_size * sizeof(uint64_t));
1402         if (ret < 0) {
1403             error_setg_errno(errp, -ret, "Could not read L1 table");
1404             goto fail;
1405         }
1406         for(i = 0;i < s->l1_size; i++) {
1407             s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1408         }
1409     }
1410
1411     /* Parse driver-specific options */
1412     ret = qcow2_update_options(bs, options, flags, errp);
1413     if (ret < 0) {
1414         goto fail;
1415     }
1416
1417     s->cluster_cache_offset = -1;
1418     s->flags = flags;
1419
1420     ret = qcow2_refcount_init(bs);
1421     if (ret != 0) {
1422         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1423         goto fail;
1424     }
1425
1426     QLIST_INIT(&s->cluster_allocs);
1427     QTAILQ_INIT(&s->discards);
1428
1429     /* read qcow2 extensions */
1430     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1431                               flags, &update_header, &local_err)) {
1432         error_propagate(errp, local_err);
1433         ret = -EINVAL;
1434         goto fail;
1435     }
1436
1437     /* qcow2_read_extension may have set up the crypto context
1438      * if the crypt method needs a header region, some methods
1439      * don't need header extensions, so must check here
1440      */
1441     if (s->crypt_method_header && !s->crypto) {
1442         if (s->crypt_method_header == QCOW_CRYPT_AES) {
1443             unsigned int cflags = 0;
1444             if (flags & BDRV_O_NO_IO) {
1445                 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1446             }
1447             s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1448                                            NULL, NULL, cflags, 1, errp);
1449             if (!s->crypto) {
1450                 ret = -EINVAL;
1451                 goto fail;
1452             }
1453         } else if (!(flags & BDRV_O_NO_IO)) {
1454             error_setg(errp, "Missing CRYPTO header for crypt method %d",
1455                        s->crypt_method_header);
1456             ret = -EINVAL;
1457             goto fail;
1458         }
1459     }
1460
1461     /* read the backing file name */
1462     if (header.backing_file_offset != 0) {
1463         len = header.backing_file_size;
1464         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1465             len >= sizeof(bs->backing_file)) {
1466             error_setg(errp, "Backing file name too long");
1467             ret = -EINVAL;
1468             goto fail;
1469         }
1470         ret = bdrv_pread(bs->file, header.backing_file_offset,
1471                          bs->backing_file, len);
1472         if (ret < 0) {
1473             error_setg_errno(errp, -ret, "Could not read backing file name");
1474             goto fail;
1475         }
1476         bs->backing_file[len] = '\0';
1477         s->image_backing_file = g_strdup(bs->backing_file);
1478     }
1479
1480     /* Internal snapshots */
1481     s->snapshots_offset = header.snapshots_offset;
1482     s->nb_snapshots = header.nb_snapshots;
1483
1484     ret = qcow2_read_snapshots(bs);
1485     if (ret < 0) {
1486         error_setg_errno(errp, -ret, "Could not read snapshots");
1487         goto fail;
1488     }
1489
1490     /* Clear unknown autoclear feature bits */
1491     update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1492     update_header =
1493         update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1494     if (update_header) {
1495         s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1496     }
1497
1498     /* == Handle persistent dirty bitmaps ==
1499      *
1500      * We want load dirty bitmaps in three cases:
1501      *
1502      * 1. Normal open of the disk in active mode, not related to invalidation
1503      *    after migration.
1504      *
1505      * 2. Invalidation of the target vm after pre-copy phase of migration, if
1506      *    bitmaps are _not_ migrating through migration channel, i.e.
1507      *    'dirty-bitmaps' capability is disabled.
1508      *
1509      * 3. Invalidation of source vm after failed or canceled migration.
1510      *    This is a very interesting case. There are two possible types of
1511      *    bitmaps:
1512      *
1513      *    A. Stored on inactivation and removed. They should be loaded from the
1514      *       image.
1515      *
1516      *    B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1517      *       the migration channel (with dirty-bitmaps capability).
1518      *
1519      *    On the other hand, there are two possible sub-cases:
1520      *
1521      *    3.1 disk was changed by somebody else while were inactive. In this
1522      *        case all in-RAM dirty bitmaps (both persistent and not) are
1523      *        definitely invalid. And we don't have any method to determine
1524      *        this.
1525      *
1526      *        Simple and safe thing is to just drop all the bitmaps of type B on
1527      *        inactivation. But in this case we lose bitmaps in valid 4.2 case.
1528      *
1529      *        On the other hand, resuming source vm, if disk was already changed
1530      *        is a bad thing anyway: not only bitmaps, the whole vm state is
1531      *        out of sync with disk.
1532      *
1533      *        This means, that user or management tool, who for some reason
1534      *        decided to resume source vm, after disk was already changed by
1535      *        target vm, should at least drop all dirty bitmaps by hand.
1536      *
1537      *        So, we can ignore this case for now, but TODO: "generation"
1538      *        extension for qcow2, to determine, that image was changed after
1539      *        last inactivation. And if it is changed, we will drop (or at least
1540      *        mark as 'invalid' all the bitmaps of type B, both persistent
1541      *        and not).
1542      *
1543      *    3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1544      *        to disk ('dirty-bitmaps' capability disabled), or not saved
1545      *        ('dirty-bitmaps' capability enabled), but we don't need to care
1546      *        of: let's load bitmaps as always: stored bitmaps will be loaded,
1547      *        and not stored has flag IN_USE=1 in the image and will be skipped
1548      *        on loading.
1549      *
1550      * One remaining possible case when we don't want load bitmaps:
1551      *
1552      * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1553      *    will be loaded on invalidation, no needs try loading them before)
1554      */
1555
1556     if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1557         /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1558         bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1559
1560         update_header = update_header && !header_updated;
1561     }
1562     if (local_err != NULL) {
1563         error_propagate(errp, local_err);
1564         ret = -EINVAL;
1565         goto fail;
1566     }
1567
1568     if (update_header) {
1569         ret = qcow2_update_header(bs);
1570         if (ret < 0) {
1571             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1572             goto fail;
1573         }
1574     }
1575
1576     bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1577
1578     /* Repair image if dirty */
1579     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1580         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1581         BdrvCheckResult result = {0};
1582
1583         ret = qcow2_co_check_locked(bs, &result,
1584                                     BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1585         if (ret < 0 || result.check_errors) {
1586             if (ret >= 0) {
1587                 ret = -EIO;
1588             }
1589             error_setg_errno(errp, -ret, "Could not repair dirty image");
1590             goto fail;
1591         }
1592     }
1593
1594 #ifdef DEBUG_ALLOC
1595     {
1596         BdrvCheckResult result = {0};
1597         qcow2_check_refcounts(bs, &result, 0);
1598     }
1599 #endif
1600
1601     qemu_co_queue_init(&s->compress_wait_queue);
1602
1603     return ret;
1604
1605  fail:
1606     g_free(s->unknown_header_fields);
1607     cleanup_unknown_header_ext(bs);
1608     qcow2_free_snapshots(bs);
1609     qcow2_refcount_close(bs);
1610     qemu_vfree(s->l1_table);
1611     /* else pre-write overlap checks in cache_destroy may crash */
1612     s->l1_table = NULL;
1613     cache_clean_timer_del(bs);
1614     if (s->l2_table_cache) {
1615         qcow2_cache_destroy(s->l2_table_cache);
1616     }
1617     if (s->refcount_block_cache) {
1618         qcow2_cache_destroy(s->refcount_block_cache);
1619     }
1620     qcrypto_block_free(s->crypto);
1621     qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1622     return ret;
1623 }
1624
1625 typedef struct QCow2OpenCo {
1626     BlockDriverState *bs;
1627     QDict *options;
1628     int flags;
1629     Error **errp;
1630     int ret;
1631 } QCow2OpenCo;
1632
1633 static void coroutine_fn qcow2_open_entry(void *opaque)
1634 {
1635     QCow2OpenCo *qoc = opaque;
1636     BDRVQcow2State *s = qoc->bs->opaque;
1637
1638     qemu_co_mutex_lock(&s->lock);
1639     qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1640     qemu_co_mutex_unlock(&s->lock);
1641 }
1642
1643 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1644                       Error **errp)
1645 {
1646     BDRVQcow2State *s = bs->opaque;
1647     QCow2OpenCo qoc = {
1648         .bs = bs,
1649         .options = options,
1650         .flags = flags,
1651         .errp = errp,
1652         .ret = -EINPROGRESS
1653     };
1654
1655     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1656                                false, errp);
1657     if (!bs->file) {
1658         return -EINVAL;
1659     }
1660
1661     /* Initialise locks */
1662     qemu_co_mutex_init(&s->lock);
1663
1664     if (qemu_in_coroutine()) {
1665         /* From bdrv_co_create.  */
1666         qcow2_open_entry(&qoc);
1667     } else {
1668         qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1669         BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1670     }
1671     return qoc.ret;
1672 }
1673
1674 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1675 {
1676     BDRVQcow2State *s = bs->opaque;
1677
1678     if (bs->encrypted) {
1679         /* Encryption works on a sector granularity */
1680         bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1681     }
1682     bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1683     bs->bl.pdiscard_alignment = s->cluster_size;
1684 }
1685
1686 static int qcow2_reopen_prepare(BDRVReopenState *state,
1687                                 BlockReopenQueue *queue, Error **errp)
1688 {
1689     Qcow2ReopenState *r;
1690     int ret;
1691
1692     r = g_new0(Qcow2ReopenState, 1);
1693     state->opaque = r;
1694
1695     ret = qcow2_update_options_prepare(state->bs, r, state->options,
1696                                        state->flags, errp);
1697     if (ret < 0) {
1698         goto fail;
1699     }
1700
1701     /* We need to write out any unwritten data if we reopen read-only. */
1702     if ((state->flags & BDRV_O_RDWR) == 0) {
1703         ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1704         if (ret < 0) {
1705             goto fail;
1706         }
1707
1708         ret = bdrv_flush(state->bs);
1709         if (ret < 0) {
1710             goto fail;
1711         }
1712
1713         ret = qcow2_mark_clean(state->bs);
1714         if (ret < 0) {
1715             goto fail;
1716         }
1717     }
1718
1719     return 0;
1720
1721 fail:
1722     qcow2_update_options_abort(state->bs, r);
1723     g_free(r);
1724     return ret;
1725 }
1726
1727 static void qcow2_reopen_commit(BDRVReopenState *state)
1728 {
1729     qcow2_update_options_commit(state->bs, state->opaque);
1730     g_free(state->opaque);
1731 }
1732
1733 static void qcow2_reopen_abort(BDRVReopenState *state)
1734 {
1735     qcow2_update_options_abort(state->bs, state->opaque);
1736     g_free(state->opaque);
1737 }
1738
1739 static void qcow2_join_options(QDict *options, QDict *old_options)
1740 {
1741     bool has_new_overlap_template =
1742         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1743         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1744     bool has_new_total_cache_size =
1745         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1746     bool has_all_cache_options;
1747
1748     /* New overlap template overrides all old overlap options */
1749     if (has_new_overlap_template) {
1750         qdict_del(old_options, QCOW2_OPT_OVERLAP);
1751         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1752         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1753         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1754         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1755         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1756         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1757         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1758         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1759         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1760     }
1761
1762     /* New total cache size overrides all old options */
1763     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1764         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1765         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1766     }
1767
1768     qdict_join(options, old_options, false);
1769
1770     /*
1771      * If after merging all cache size options are set, an old total size is
1772      * overwritten. Do keep all options, however, if all three are new. The
1773      * resulting error message is what we want to happen.
1774      */
1775     has_all_cache_options =
1776         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1777         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1778         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1779
1780     if (has_all_cache_options && !has_new_total_cache_size) {
1781         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1782     }
1783 }
1784
1785 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1786                                               bool want_zero,
1787                                               int64_t offset, int64_t count,
1788                                               int64_t *pnum, int64_t *map,
1789                                               BlockDriverState **file)
1790 {
1791     BDRVQcow2State *s = bs->opaque;
1792     uint64_t cluster_offset;
1793     int index_in_cluster, ret;
1794     unsigned int bytes;
1795     int status = 0;
1796
1797     bytes = MIN(INT_MAX, count);
1798     qemu_co_mutex_lock(&s->lock);
1799     ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1800     qemu_co_mutex_unlock(&s->lock);
1801     if (ret < 0) {
1802         return ret;
1803     }
1804
1805     *pnum = bytes;
1806
1807     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1808         !s->crypto) {
1809         index_in_cluster = offset & (s->cluster_size - 1);
1810         *map = cluster_offset | index_in_cluster;
1811         *file = bs->file->bs;
1812         status |= BDRV_BLOCK_OFFSET_VALID;
1813     }
1814     if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1815         status |= BDRV_BLOCK_ZERO;
1816     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1817         status |= BDRV_BLOCK_DATA;
1818     }
1819     return status;
1820 }
1821
1822 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
1823                                             QCowL2Meta **pl2meta,
1824                                             bool link_l2)
1825 {
1826     int ret = 0;
1827     QCowL2Meta *l2meta = *pl2meta;
1828
1829     while (l2meta != NULL) {
1830         QCowL2Meta *next;
1831
1832         if (link_l2) {
1833             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1834             if (ret) {
1835                 goto out;
1836             }
1837         } else {
1838             qcow2_alloc_cluster_abort(bs, l2meta);
1839         }
1840
1841         /* Take the request off the list of running requests */
1842         if (l2meta->nb_clusters != 0) {
1843             QLIST_REMOVE(l2meta, next_in_flight);
1844         }
1845
1846         qemu_co_queue_restart_all(&l2meta->dependent_requests);
1847
1848         next = l2meta->next;
1849         g_free(l2meta);
1850         l2meta = next;
1851     }
1852 out:
1853     *pl2meta = l2meta;
1854     return ret;
1855 }
1856
1857 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1858                                         uint64_t bytes, QEMUIOVector *qiov,
1859                                         int flags)
1860 {
1861     BDRVQcow2State *s = bs->opaque;
1862     int offset_in_cluster;
1863     int ret;
1864     unsigned int cur_bytes; /* number of bytes in current iteration */
1865     uint64_t cluster_offset = 0;
1866     uint64_t bytes_done = 0;
1867     QEMUIOVector hd_qiov;
1868     uint8_t *cluster_data = NULL;
1869
1870     qemu_iovec_init(&hd_qiov, qiov->niov);
1871
1872     qemu_co_mutex_lock(&s->lock);
1873
1874     while (bytes != 0) {
1875
1876         /* prepare next request */
1877         cur_bytes = MIN(bytes, INT_MAX);
1878         if (s->crypto) {
1879             cur_bytes = MIN(cur_bytes,
1880                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1881         }
1882
1883         ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1884         if (ret < 0) {
1885             goto fail;
1886         }
1887
1888         offset_in_cluster = offset_into_cluster(s, offset);
1889
1890         qemu_iovec_reset(&hd_qiov);
1891         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1892
1893         switch (ret) {
1894         case QCOW2_CLUSTER_UNALLOCATED:
1895
1896             if (bs->backing) {
1897                 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1898                 qemu_co_mutex_unlock(&s->lock);
1899                 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1900                                      &hd_qiov, 0);
1901                 qemu_co_mutex_lock(&s->lock);
1902                 if (ret < 0) {
1903                     goto fail;
1904                 }
1905             } else {
1906                 /* Note: in this case, no need to wait */
1907                 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1908             }
1909             break;
1910
1911         case QCOW2_CLUSTER_ZERO_PLAIN:
1912         case QCOW2_CLUSTER_ZERO_ALLOC:
1913             qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1914             break;
1915
1916         case QCOW2_CLUSTER_COMPRESSED:
1917             /* add AIO support for compressed blocks ? */
1918             ret = qcow2_decompress_cluster(bs, cluster_offset);
1919             if (ret < 0) {
1920                 goto fail;
1921             }
1922
1923             qemu_iovec_from_buf(&hd_qiov, 0,
1924                                 s->cluster_cache + offset_in_cluster,
1925                                 cur_bytes);
1926             break;
1927
1928         case QCOW2_CLUSTER_NORMAL:
1929             if ((cluster_offset & 511) != 0) {
1930                 ret = -EIO;
1931                 goto fail;
1932             }
1933
1934             if (bs->encrypted) {
1935                 assert(s->crypto);
1936
1937                 /*
1938                  * For encrypted images, read everything into a temporary
1939                  * contiguous buffer on which the AES functions can work.
1940                  */
1941                 if (!cluster_data) {
1942                     cluster_data =
1943                         qemu_try_blockalign(bs->file->bs,
1944                                             QCOW_MAX_CRYPT_CLUSTERS
1945                                             * s->cluster_size);
1946                     if (cluster_data == NULL) {
1947                         ret = -ENOMEM;
1948                         goto fail;
1949                     }
1950                 }
1951
1952                 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1953                 qemu_iovec_reset(&hd_qiov);
1954                 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1955             }
1956
1957             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1958             qemu_co_mutex_unlock(&s->lock);
1959             ret = bdrv_co_preadv(bs->file,
1960                                  cluster_offset + offset_in_cluster,
1961                                  cur_bytes, &hd_qiov, 0);
1962             qemu_co_mutex_lock(&s->lock);
1963             if (ret < 0) {
1964                 goto fail;
1965             }
1966             if (bs->encrypted) {
1967                 assert(s->crypto);
1968                 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1969                 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1970                 if (qcrypto_block_decrypt(s->crypto,
1971                                           (s->crypt_physical_offset ?
1972                                            cluster_offset + offset_in_cluster :
1973                                            offset),
1974                                           cluster_data,
1975                                           cur_bytes,
1976                                           NULL) < 0) {
1977                     ret = -EIO;
1978                     goto fail;
1979                 }
1980                 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1981             }
1982             break;
1983
1984         default:
1985             g_assert_not_reached();
1986             ret = -EIO;
1987             goto fail;
1988         }
1989
1990         bytes -= cur_bytes;
1991         offset += cur_bytes;
1992         bytes_done += cur_bytes;
1993     }
1994     ret = 0;
1995
1996 fail:
1997     qemu_co_mutex_unlock(&s->lock);
1998
1999     qemu_iovec_destroy(&hd_qiov);
2000     qemu_vfree(cluster_data);
2001
2002     return ret;
2003 }
2004
2005 /* Check if it's possible to merge a write request with the writing of
2006  * the data from the COW regions */
2007 static bool merge_cow(uint64_t offset, unsigned bytes,
2008                       QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
2009 {
2010     QCowL2Meta *m;
2011
2012     for (m = l2meta; m != NULL; m = m->next) {
2013         /* If both COW regions are empty then there's nothing to merge */
2014         if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2015             continue;
2016         }
2017
2018         /* The data (middle) region must be immediately after the
2019          * start region */
2020         if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2021             continue;
2022         }
2023
2024         /* The end region must be immediately after the data (middle)
2025          * region */
2026         if (m->offset + m->cow_end.offset != offset + bytes) {
2027             continue;
2028         }
2029
2030         /* Make sure that adding both COW regions to the QEMUIOVector
2031          * does not exceed IOV_MAX */
2032         if (hd_qiov->niov > IOV_MAX - 2) {
2033             continue;
2034         }
2035
2036         m->data_qiov = hd_qiov;
2037         return true;
2038     }
2039
2040     return false;
2041 }
2042
2043 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
2044                                          uint64_t bytes, QEMUIOVector *qiov,
2045                                          int flags)
2046 {
2047     BDRVQcow2State *s = bs->opaque;
2048     int offset_in_cluster;
2049     int ret;
2050     unsigned int cur_bytes; /* number of sectors in current iteration */
2051     uint64_t cluster_offset;
2052     QEMUIOVector hd_qiov;
2053     uint64_t bytes_done = 0;
2054     uint8_t *cluster_data = NULL;
2055     QCowL2Meta *l2meta = NULL;
2056
2057     trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2058
2059     qemu_iovec_init(&hd_qiov, qiov->niov);
2060
2061     s->cluster_cache_offset = -1; /* disable compressed cache */
2062
2063     qemu_co_mutex_lock(&s->lock);
2064
2065     while (bytes != 0) {
2066
2067         l2meta = NULL;
2068
2069         trace_qcow2_writev_start_part(qemu_coroutine_self());
2070         offset_in_cluster = offset_into_cluster(s, offset);
2071         cur_bytes = MIN(bytes, INT_MAX);
2072         if (bs->encrypted) {
2073             cur_bytes = MIN(cur_bytes,
2074                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2075                             - offset_in_cluster);
2076         }
2077
2078         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2079                                          &cluster_offset, &l2meta);
2080         if (ret < 0) {
2081             goto fail;
2082         }
2083
2084         assert((cluster_offset & 511) == 0);
2085
2086         qemu_iovec_reset(&hd_qiov);
2087         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
2088
2089         if (bs->encrypted) {
2090             assert(s->crypto);
2091             if (!cluster_data) {
2092                 cluster_data = qemu_try_blockalign(bs->file->bs,
2093                                                    QCOW_MAX_CRYPT_CLUSTERS
2094                                                    * s->cluster_size);
2095                 if (cluster_data == NULL) {
2096                     ret = -ENOMEM;
2097                     goto fail;
2098                 }
2099             }
2100
2101             assert(hd_qiov.size <=
2102                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2103             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
2104
2105             if (qcrypto_block_encrypt(s->crypto,
2106                                       (s->crypt_physical_offset ?
2107                                        cluster_offset + offset_in_cluster :
2108                                        offset),
2109                                       cluster_data,
2110                                       cur_bytes, NULL) < 0) {
2111                 ret = -EIO;
2112                 goto fail;
2113             }
2114
2115             qemu_iovec_reset(&hd_qiov);
2116             qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2117         }
2118
2119         ret = qcow2_pre_write_overlap_check(bs, 0,
2120                 cluster_offset + offset_in_cluster, cur_bytes);
2121         if (ret < 0) {
2122             goto fail;
2123         }
2124
2125         /* If we need to do COW, check if it's possible to merge the
2126          * writing of the guest data together with that of the COW regions.
2127          * If it's not possible (or not necessary) then write the
2128          * guest data now. */
2129         if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2130             qemu_co_mutex_unlock(&s->lock);
2131             BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2132             trace_qcow2_writev_data(qemu_coroutine_self(),
2133                                     cluster_offset + offset_in_cluster);
2134             ret = bdrv_co_pwritev(bs->file,
2135                                   cluster_offset + offset_in_cluster,
2136                                   cur_bytes, &hd_qiov, 0);
2137             qemu_co_mutex_lock(&s->lock);
2138             if (ret < 0) {
2139                 goto fail;
2140             }
2141         }
2142
2143         ret = qcow2_handle_l2meta(bs, &l2meta, true);
2144         if (ret) {
2145             goto fail;
2146         }
2147
2148         bytes -= cur_bytes;
2149         offset += cur_bytes;
2150         bytes_done += cur_bytes;
2151         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2152     }
2153     ret = 0;
2154
2155 fail:
2156     qcow2_handle_l2meta(bs, &l2meta, false);
2157
2158     qemu_co_mutex_unlock(&s->lock);
2159
2160     qemu_iovec_destroy(&hd_qiov);
2161     qemu_vfree(cluster_data);
2162     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2163
2164     return ret;
2165 }
2166
2167 static int qcow2_inactivate(BlockDriverState *bs)
2168 {
2169     BDRVQcow2State *s = bs->opaque;
2170     int ret, result = 0;
2171     Error *local_err = NULL;
2172
2173     qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2174     if (local_err != NULL) {
2175         result = -EINVAL;
2176         error_reportf_err(local_err, "Lost persistent bitmaps during "
2177                           "inactivation of node '%s': ",
2178                           bdrv_get_device_or_node_name(bs));
2179     }
2180
2181     ret = qcow2_cache_flush(bs, s->l2_table_cache);
2182     if (ret) {
2183         result = ret;
2184         error_report("Failed to flush the L2 table cache: %s",
2185                      strerror(-ret));
2186     }
2187
2188     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2189     if (ret) {
2190         result = ret;
2191         error_report("Failed to flush the refcount block cache: %s",
2192                      strerror(-ret));
2193     }
2194
2195     if (result == 0) {
2196         qcow2_mark_clean(bs);
2197     }
2198
2199     return result;
2200 }
2201
2202 static void qcow2_close(BlockDriverState *bs)
2203 {
2204     BDRVQcow2State *s = bs->opaque;
2205     qemu_vfree(s->l1_table);
2206     /* else pre-write overlap checks in cache_destroy may crash */
2207     s->l1_table = NULL;
2208
2209     if (!(s->flags & BDRV_O_INACTIVE)) {
2210         qcow2_inactivate(bs);
2211     }
2212
2213     cache_clean_timer_del(bs);
2214     qcow2_cache_destroy(s->l2_table_cache);
2215     qcow2_cache_destroy(s->refcount_block_cache);
2216
2217     qcrypto_block_free(s->crypto);
2218     s->crypto = NULL;
2219
2220     g_free(s->unknown_header_fields);
2221     cleanup_unknown_header_ext(bs);
2222
2223     g_free(s->image_backing_file);
2224     g_free(s->image_backing_format);
2225
2226     g_free(s->cluster_cache);
2227     qemu_vfree(s->cluster_data);
2228     qcow2_refcount_close(bs);
2229     qcow2_free_snapshots(bs);
2230 }
2231
2232 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2233                                                    Error **errp)
2234 {
2235     BDRVQcow2State *s = bs->opaque;
2236     int flags = s->flags;
2237     QCryptoBlock *crypto = NULL;
2238     QDict *options;
2239     Error *local_err = NULL;
2240     int ret;
2241
2242     /*
2243      * Backing files are read-only which makes all of their metadata immutable,
2244      * that means we don't have to worry about reopening them here.
2245      */
2246
2247     crypto = s->crypto;
2248     s->crypto = NULL;
2249
2250     qcow2_close(bs);
2251
2252     memset(s, 0, sizeof(BDRVQcow2State));
2253     options = qdict_clone_shallow(bs->options);
2254
2255     flags &= ~BDRV_O_INACTIVE;
2256     qemu_co_mutex_lock(&s->lock);
2257     ret = qcow2_do_open(bs, options, flags, &local_err);
2258     qemu_co_mutex_unlock(&s->lock);
2259     qobject_unref(options);
2260     if (local_err) {
2261         error_propagate_prepend(errp, local_err,
2262                                 "Could not reopen qcow2 layer: ");
2263         bs->drv = NULL;
2264         return;
2265     } else if (ret < 0) {
2266         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2267         bs->drv = NULL;
2268         return;
2269     }
2270
2271     s->crypto = crypto;
2272 }
2273
2274 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2275     size_t len, size_t buflen)
2276 {
2277     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2278     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2279
2280     if (buflen < ext_len) {
2281         return -ENOSPC;
2282     }
2283
2284     *ext_backing_fmt = (QCowExtension) {
2285         .magic  = cpu_to_be32(magic),
2286         .len    = cpu_to_be32(len),
2287     };
2288
2289     if (len) {
2290         memcpy(buf + sizeof(QCowExtension), s, len);
2291     }
2292
2293     return ext_len;
2294 }
2295
2296 /*
2297  * Updates the qcow2 header, including the variable length parts of it, i.e.
2298  * the backing file name and all extensions. qcow2 was not designed to allow
2299  * such changes, so if we run out of space (we can only use the first cluster)
2300  * this function may fail.
2301  *
2302  * Returns 0 on success, -errno in error cases.
2303  */
2304 int qcow2_update_header(BlockDriverState *bs)
2305 {
2306     BDRVQcow2State *s = bs->opaque;
2307     QCowHeader *header;
2308     char *buf;
2309     size_t buflen = s->cluster_size;
2310     int ret;
2311     uint64_t total_size;
2312     uint32_t refcount_table_clusters;
2313     size_t header_length;
2314     Qcow2UnknownHeaderExtension *uext;
2315
2316     buf = qemu_blockalign(bs, buflen);
2317
2318     /* Header structure */
2319     header = (QCowHeader*) buf;
2320
2321     if (buflen < sizeof(*header)) {
2322         ret = -ENOSPC;
2323         goto fail;
2324     }
2325
2326     header_length = sizeof(*header) + s->unknown_header_fields_size;
2327     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2328     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2329
2330     *header = (QCowHeader) {
2331         /* Version 2 fields */
2332         .magic                  = cpu_to_be32(QCOW_MAGIC),
2333         .version                = cpu_to_be32(s->qcow_version),
2334         .backing_file_offset    = 0,
2335         .backing_file_size      = 0,
2336         .cluster_bits           = cpu_to_be32(s->cluster_bits),
2337         .size                   = cpu_to_be64(total_size),
2338         .crypt_method           = cpu_to_be32(s->crypt_method_header),
2339         .l1_size                = cpu_to_be32(s->l1_size),
2340         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
2341         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
2342         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2343         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
2344         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
2345
2346         /* Version 3 fields */
2347         .incompatible_features  = cpu_to_be64(s->incompatible_features),
2348         .compatible_features    = cpu_to_be64(s->compatible_features),
2349         .autoclear_features     = cpu_to_be64(s->autoclear_features),
2350         .refcount_order         = cpu_to_be32(s->refcount_order),
2351         .header_length          = cpu_to_be32(header_length),
2352     };
2353
2354     /* For older versions, write a shorter header */
2355     switch (s->qcow_version) {
2356     case 2:
2357         ret = offsetof(QCowHeader, incompatible_features);
2358         break;
2359     case 3:
2360         ret = sizeof(*header);
2361         break;
2362     default:
2363         ret = -EINVAL;
2364         goto fail;
2365     }
2366
2367     buf += ret;
2368     buflen -= ret;
2369     memset(buf, 0, buflen);
2370
2371     /* Preserve any unknown field in the header */
2372     if (s->unknown_header_fields_size) {
2373         if (buflen < s->unknown_header_fields_size) {
2374             ret = -ENOSPC;
2375             goto fail;
2376         }
2377
2378         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2379         buf += s->unknown_header_fields_size;
2380         buflen -= s->unknown_header_fields_size;
2381     }
2382
2383     /* Backing file format header extension */
2384     if (s->image_backing_format) {
2385         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2386                              s->image_backing_format,
2387                              strlen(s->image_backing_format),
2388                              buflen);
2389         if (ret < 0) {
2390             goto fail;
2391         }
2392
2393         buf += ret;
2394         buflen -= ret;
2395     }
2396
2397     /* Full disk encryption header pointer extension */
2398     if (s->crypto_header.offset != 0) {
2399         s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2400         s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
2401         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2402                              &s->crypto_header, sizeof(s->crypto_header),
2403                              buflen);
2404         s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2405         s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2406         if (ret < 0) {
2407             goto fail;
2408         }
2409         buf += ret;
2410         buflen -= ret;
2411     }
2412
2413     /* Feature table */
2414     if (s->qcow_version >= 3) {
2415         Qcow2Feature features[] = {
2416             {
2417                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2418                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
2419                 .name = "dirty bit",
2420             },
2421             {
2422                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2423                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
2424                 .name = "corrupt bit",
2425             },
2426             {
2427                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2428                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2429                 .name = "lazy refcounts",
2430             },
2431         };
2432
2433         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2434                              features, sizeof(features), buflen);
2435         if (ret < 0) {
2436             goto fail;
2437         }
2438         buf += ret;
2439         buflen -= ret;
2440     }
2441
2442     /* Bitmap extension */
2443     if (s->nb_bitmaps > 0) {
2444         Qcow2BitmapHeaderExt bitmaps_header = {
2445             .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2446             .bitmap_directory_size =
2447                     cpu_to_be64(s->bitmap_directory_size),
2448             .bitmap_directory_offset =
2449                     cpu_to_be64(s->bitmap_directory_offset)
2450         };
2451         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2452                              &bitmaps_header, sizeof(bitmaps_header),
2453                              buflen);
2454         if (ret < 0) {
2455             goto fail;
2456         }
2457         buf += ret;
2458         buflen -= ret;
2459     }
2460
2461     /* Keep unknown header extensions */
2462     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2463         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2464         if (ret < 0) {
2465             goto fail;
2466         }
2467
2468         buf += ret;
2469         buflen -= ret;
2470     }
2471
2472     /* End of header extensions */
2473     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2474     if (ret < 0) {
2475         goto fail;
2476     }
2477
2478     buf += ret;
2479     buflen -= ret;
2480
2481     /* Backing file name */
2482     if (s->image_backing_file) {
2483         size_t backing_file_len = strlen(s->image_backing_file);
2484
2485         if (buflen < backing_file_len) {
2486             ret = -ENOSPC;
2487             goto fail;
2488         }
2489
2490         /* Using strncpy is ok here, since buf is not NUL-terminated. */
2491         strncpy(buf, s->image_backing_file, buflen);
2492
2493         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2494         header->backing_file_size   = cpu_to_be32(backing_file_len);
2495     }
2496
2497     /* Write the new header */
2498     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2499     if (ret < 0) {
2500         goto fail;
2501     }
2502
2503     ret = 0;
2504 fail:
2505     qemu_vfree(header);
2506     return ret;
2507 }
2508
2509 static int qcow2_change_backing_file(BlockDriverState *bs,
2510     const char *backing_file, const char *backing_fmt)
2511 {
2512     BDRVQcow2State *s = bs->opaque;
2513
2514     if (backing_file && strlen(backing_file) > 1023) {
2515         return -EINVAL;
2516     }
2517
2518     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2519     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2520
2521     g_free(s->image_backing_file);
2522     g_free(s->image_backing_format);
2523
2524     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2525     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2526
2527     return qcow2_update_header(bs);
2528 }
2529
2530 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2531 {
2532     if (g_str_equal(encryptfmt, "luks")) {
2533         return QCOW_CRYPT_LUKS;
2534     } else if (g_str_equal(encryptfmt, "aes")) {
2535         return QCOW_CRYPT_AES;
2536     } else {
2537         return -EINVAL;
2538     }
2539 }
2540
2541 static int qcow2_set_up_encryption(BlockDriverState *bs,
2542                                    QCryptoBlockCreateOptions *cryptoopts,
2543                                    Error **errp)
2544 {
2545     BDRVQcow2State *s = bs->opaque;
2546     QCryptoBlock *crypto = NULL;
2547     int fmt, ret;
2548
2549     switch (cryptoopts->format) {
2550     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2551         fmt = QCOW_CRYPT_LUKS;
2552         break;
2553     case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2554         fmt = QCOW_CRYPT_AES;
2555         break;
2556     default:
2557         error_setg(errp, "Crypto format not supported in qcow2");
2558         return -EINVAL;
2559     }
2560
2561     s->crypt_method_header = fmt;
2562
2563     crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2564                                   qcow2_crypto_hdr_init_func,
2565                                   qcow2_crypto_hdr_write_func,
2566                                   bs, errp);
2567     if (!crypto) {
2568         return -EINVAL;
2569     }
2570
2571     ret = qcow2_update_header(bs);
2572     if (ret < 0) {
2573         error_setg_errno(errp, -ret, "Could not write encryption header");
2574         goto out;
2575     }
2576
2577     ret = 0;
2578  out:
2579     qcrypto_block_free(crypto);
2580     return ret;
2581 }
2582
2583 /**
2584  * Preallocates metadata structures for data clusters between @offset (in the
2585  * guest disk) and @new_length (which is thus generally the new guest disk
2586  * size).
2587  *
2588  * Returns: 0 on success, -errno on failure.
2589  */
2590 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
2591                                        uint64_t new_length)
2592 {
2593     uint64_t bytes;
2594     uint64_t host_offset = 0;
2595     unsigned int cur_bytes;
2596     int ret;
2597     QCowL2Meta *meta;
2598
2599     assert(offset <= new_length);
2600     bytes = new_length - offset;
2601
2602     while (bytes) {
2603         cur_bytes = MIN(bytes, INT_MAX);
2604         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2605                                          &host_offset, &meta);
2606         if (ret < 0) {
2607             return ret;
2608         }
2609
2610         while (meta) {
2611             QCowL2Meta *next = meta->next;
2612
2613             ret = qcow2_alloc_cluster_link_l2(bs, meta);
2614             if (ret < 0) {
2615                 qcow2_free_any_clusters(bs, meta->alloc_offset,
2616                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
2617                 return ret;
2618             }
2619
2620             /* There are no dependent requests, but we need to remove our
2621              * request from the list of in-flight requests */
2622             QLIST_REMOVE(meta, next_in_flight);
2623
2624             g_free(meta);
2625             meta = next;
2626         }
2627
2628         /* TODO Preallocate data if requested */
2629
2630         bytes -= cur_bytes;
2631         offset += cur_bytes;
2632     }
2633
2634     /*
2635      * It is expected that the image file is large enough to actually contain
2636      * all of the allocated clusters (otherwise we get failing reads after
2637      * EOF). Extend the image to the last allocated sector.
2638      */
2639     if (host_offset != 0) {
2640         uint8_t data = 0;
2641         ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2642                           &data, 1);
2643         if (ret < 0) {
2644             return ret;
2645         }
2646     }
2647
2648     return 0;
2649 }
2650
2651 /* qcow2_refcount_metadata_size:
2652  * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2653  * @cluster_size: size of a cluster, in bytes
2654  * @refcount_order: refcount bits power-of-2 exponent
2655  * @generous_increase: allow for the refcount table to be 1.5x as large as it
2656  *                     needs to be
2657  *
2658  * Returns: Number of bytes required for refcount blocks and table metadata.
2659  */
2660 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2661                                      int refcount_order, bool generous_increase,
2662                                      uint64_t *refblock_count)
2663 {
2664     /*
2665      * Every host cluster is reference-counted, including metadata (even
2666      * refcount metadata is recursively included).
2667      *
2668      * An accurate formula for the size of refcount metadata size is difficult
2669      * to derive.  An easier method of calculation is finding the fixed point
2670      * where no further refcount blocks or table clusters are required to
2671      * reference count every cluster.
2672      */
2673     int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2674     int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2675     int64_t table = 0;  /* number of refcount table clusters */
2676     int64_t blocks = 0; /* number of refcount block clusters */
2677     int64_t last;
2678     int64_t n = 0;
2679
2680     do {
2681         last = n;
2682         blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2683         table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2684         n = clusters + blocks + table;
2685
2686         if (n == last && generous_increase) {
2687             clusters += DIV_ROUND_UP(table, 2);
2688             n = 0; /* force another loop */
2689             generous_increase = false;
2690         }
2691     } while (n != last);
2692
2693     if (refblock_count) {
2694         *refblock_count = blocks;
2695     }
2696
2697     return (blocks + table) * cluster_size;
2698 }
2699
2700 /**
2701  * qcow2_calc_prealloc_size:
2702  * @total_size: virtual disk size in bytes
2703  * @cluster_size: cluster size in bytes
2704  * @refcount_order: refcount bits power-of-2 exponent
2705  *
2706  * Returns: Total number of bytes required for the fully allocated image
2707  * (including metadata).
2708  */
2709 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2710                                         size_t cluster_size,
2711                                         int refcount_order)
2712 {
2713     int64_t meta_size = 0;
2714     uint64_t nl1e, nl2e;
2715     int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2716
2717     /* header: 1 cluster */
2718     meta_size += cluster_size;
2719
2720     /* total size of L2 tables */
2721     nl2e = aligned_total_size / cluster_size;
2722     nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2723     meta_size += nl2e * sizeof(uint64_t);
2724
2725     /* total size of L1 tables */
2726     nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2727     nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2728     meta_size += nl1e * sizeof(uint64_t);
2729
2730     /* total size of refcount table and blocks */
2731     meta_size += qcow2_refcount_metadata_size(
2732             (meta_size + aligned_total_size) / cluster_size,
2733             cluster_size, refcount_order, false, NULL);
2734
2735     return meta_size + aligned_total_size;
2736 }
2737
2738 static bool validate_cluster_size(size_t cluster_size, Error **errp)
2739 {
2740     int cluster_bits = ctz32(cluster_size);
2741     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2742         (1 << cluster_bits) != cluster_size)
2743     {
2744         error_setg(errp, "Cluster size must be a power of two between %d and "
2745                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2746         return false;
2747     }
2748     return true;
2749 }
2750
2751 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2752 {
2753     size_t cluster_size;
2754
2755     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2756                                          DEFAULT_CLUSTER_SIZE);
2757     if (!validate_cluster_size(cluster_size, errp)) {
2758         return 0;
2759     }
2760     return cluster_size;
2761 }
2762
2763 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2764 {
2765     char *buf;
2766     int ret;
2767
2768     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2769     if (!buf) {
2770         ret = 3; /* default */
2771     } else if (!strcmp(buf, "0.10")) {
2772         ret = 2;
2773     } else if (!strcmp(buf, "1.1")) {
2774         ret = 3;
2775     } else {
2776         error_setg(errp, "Invalid compatibility level: '%s'", buf);
2777         ret = -EINVAL;
2778     }
2779     g_free(buf);
2780     return ret;
2781 }
2782
2783 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2784                                                 Error **errp)
2785 {
2786     uint64_t refcount_bits;
2787
2788     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2789     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2790         error_setg(errp, "Refcount width must be a power of two and may not "
2791                    "exceed 64 bits");
2792         return 0;
2793     }
2794
2795     if (version < 3 && refcount_bits != 16) {
2796         error_setg(errp, "Different refcount widths than 16 bits require "
2797                    "compatibility level 1.1 or above (use compat=1.1 or "
2798                    "greater)");
2799         return 0;
2800     }
2801
2802     return refcount_bits;
2803 }
2804
2805 static int coroutine_fn
2806 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
2807 {
2808     BlockdevCreateOptionsQcow2 *qcow2_opts;
2809     QDict *options;
2810
2811     /*
2812      * Open the image file and write a minimal qcow2 header.
2813      *
2814      * We keep things simple and start with a zero-sized image. We also
2815      * do without refcount blocks or a L1 table for now. We'll fix the
2816      * inconsistency later.
2817      *
2818      * We do need a refcount table because growing the refcount table means
2819      * allocating two new refcount blocks - the seconds of which would be at
2820      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2821      * size for any qcow2 image.
2822      */
2823     BlockBackend *blk = NULL;
2824     BlockDriverState *bs = NULL;
2825     QCowHeader *header;
2826     size_t cluster_size;
2827     int version;
2828     int refcount_order;
2829     uint64_t* refcount_table;
2830     Error *local_err = NULL;
2831     int ret;
2832
2833     assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
2834     qcow2_opts = &create_options->u.qcow2;
2835
2836     bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
2837     if (bs == NULL) {
2838         return -EIO;
2839     }
2840
2841     /* Validate options and set default values */
2842     if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
2843         error_setg(errp, "Image size must be a multiple of 512 bytes");
2844         ret = -EINVAL;
2845         goto out;
2846     }
2847
2848     if (qcow2_opts->has_version) {
2849         switch (qcow2_opts->version) {
2850         case BLOCKDEV_QCOW2_VERSION_V2:
2851             version = 2;
2852             break;
2853         case BLOCKDEV_QCOW2_VERSION_V3:
2854             version = 3;
2855             break;
2856         default:
2857             g_assert_not_reached();
2858         }
2859     } else {
2860         version = 3;
2861     }
2862
2863     if (qcow2_opts->has_cluster_size) {
2864         cluster_size = qcow2_opts->cluster_size;
2865     } else {
2866         cluster_size = DEFAULT_CLUSTER_SIZE;
2867     }
2868
2869     if (!validate_cluster_size(cluster_size, errp)) {
2870         ret = -EINVAL;
2871         goto out;
2872     }
2873
2874     if (!qcow2_opts->has_preallocation) {
2875         qcow2_opts->preallocation = PREALLOC_MODE_OFF;
2876     }
2877     if (qcow2_opts->has_backing_file &&
2878         qcow2_opts->preallocation != PREALLOC_MODE_OFF)
2879     {
2880         error_setg(errp, "Backing file and preallocation cannot be used at "
2881                    "the same time");
2882         ret = -EINVAL;
2883         goto out;
2884     }
2885     if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
2886         error_setg(errp, "Backing format cannot be used without backing file");
2887         ret = -EINVAL;
2888         goto out;
2889     }
2890
2891     if (!qcow2_opts->has_lazy_refcounts) {
2892         qcow2_opts->lazy_refcounts = false;
2893     }
2894     if (version < 3 && qcow2_opts->lazy_refcounts) {
2895         error_setg(errp, "Lazy refcounts only supported with compatibility "
2896                    "level 1.1 and above (use version=v3 or greater)");
2897         ret = -EINVAL;
2898         goto out;
2899     }
2900
2901     if (!qcow2_opts->has_refcount_bits) {
2902         qcow2_opts->refcount_bits = 16;
2903     }
2904     if (qcow2_opts->refcount_bits > 64 ||
2905         !is_power_of_2(qcow2_opts->refcount_bits))
2906     {
2907         error_setg(errp, "Refcount width must be a power of two and may not "
2908                    "exceed 64 bits");
2909         ret = -EINVAL;
2910         goto out;
2911     }
2912     if (version < 3 && qcow2_opts->refcount_bits != 16) {
2913         error_setg(errp, "Different refcount widths than 16 bits require "
2914                    "compatibility level 1.1 or above (use version=v3 or "
2915                    "greater)");
2916         ret = -EINVAL;
2917         goto out;
2918     }
2919     refcount_order = ctz32(qcow2_opts->refcount_bits);
2920
2921
2922     /* Create BlockBackend to write to the image */
2923     blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
2924     ret = blk_insert_bs(blk, bs, errp);
2925     if (ret < 0) {
2926         goto out;
2927     }
2928     blk_set_allow_write_beyond_eof(blk, true);
2929
2930     /* Clear the protocol layer and preallocate it if necessary */
2931     ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
2932     if (ret < 0) {
2933         goto out;
2934     }
2935
2936     if (qcow2_opts->preallocation == PREALLOC_MODE_FULL ||
2937         qcow2_opts->preallocation == PREALLOC_MODE_FALLOC)
2938     {
2939         int64_t prealloc_size =
2940             qcow2_calc_prealloc_size(qcow2_opts->size, cluster_size,
2941                                      refcount_order);
2942
2943         ret = blk_truncate(blk, prealloc_size, qcow2_opts->preallocation, errp);
2944         if (ret < 0) {
2945             goto out;
2946         }
2947     }
2948
2949     /* Write the header */
2950     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2951     header = g_malloc0(cluster_size);
2952     *header = (QCowHeader) {
2953         .magic                      = cpu_to_be32(QCOW_MAGIC),
2954         .version                    = cpu_to_be32(version),
2955         .cluster_bits               = cpu_to_be32(ctz32(cluster_size)),
2956         .size                       = cpu_to_be64(0),
2957         .l1_table_offset            = cpu_to_be64(0),
2958         .l1_size                    = cpu_to_be32(0),
2959         .refcount_table_offset      = cpu_to_be64(cluster_size),
2960         .refcount_table_clusters    = cpu_to_be32(1),
2961         .refcount_order             = cpu_to_be32(refcount_order),
2962         .header_length              = cpu_to_be32(sizeof(*header)),
2963     };
2964
2965     /* We'll update this to correct value later */
2966     header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2967
2968     if (qcow2_opts->lazy_refcounts) {
2969         header->compatible_features |=
2970             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2971     }
2972
2973     ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2974     g_free(header);
2975     if (ret < 0) {
2976         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2977         goto out;
2978     }
2979
2980     /* Write a refcount table with one refcount block */
2981     refcount_table = g_malloc0(2 * cluster_size);
2982     refcount_table[0] = cpu_to_be64(2 * cluster_size);
2983     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2984     g_free(refcount_table);
2985
2986     if (ret < 0) {
2987         error_setg_errno(errp, -ret, "Could not write refcount table");
2988         goto out;
2989     }
2990
2991     blk_unref(blk);
2992     blk = NULL;
2993
2994     /*
2995      * And now open the image and make it consistent first (i.e. increase the
2996      * refcount of the cluster that is occupied by the header and the refcount
2997      * table)
2998      */
2999     options = qdict_new();
3000     qdict_put_str(options, "driver", "qcow2");
3001     qdict_put_str(options, "file", bs->node_name);
3002     blk = blk_new_open(NULL, NULL, options,
3003                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3004                        &local_err);
3005     if (blk == NULL) {
3006         error_propagate(errp, local_err);
3007         ret = -EIO;
3008         goto out;
3009     }
3010
3011     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3012     if (ret < 0) {
3013         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3014                          "header and refcount table");
3015         goto out;
3016
3017     } else if (ret != 0) {
3018         error_report("Huh, first cluster in empty image is already in use?");
3019         abort();
3020     }
3021
3022     /* Create a full header (including things like feature table) */
3023     ret = qcow2_update_header(blk_bs(blk));
3024     if (ret < 0) {
3025         error_setg_errno(errp, -ret, "Could not update qcow2 header");
3026         goto out;
3027     }
3028
3029     /* Okay, now that we have a valid image, let's give it the right size */
3030     ret = blk_truncate(blk, qcow2_opts->size, PREALLOC_MODE_OFF, errp);
3031     if (ret < 0) {
3032         error_prepend(errp, "Could not resize image: ");
3033         goto out;
3034     }
3035
3036     /* Want a backing file? There you go.*/
3037     if (qcow2_opts->has_backing_file) {
3038         const char *backing_format = NULL;
3039
3040         if (qcow2_opts->has_backing_fmt) {
3041             backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3042         }
3043
3044         ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3045                                        backing_format);
3046         if (ret < 0) {
3047             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3048                              "with format '%s'", qcow2_opts->backing_file,
3049                              backing_format);
3050             goto out;
3051         }
3052     }
3053
3054     /* Want encryption? There you go. */
3055     if (qcow2_opts->has_encrypt) {
3056         ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3057         if (ret < 0) {
3058             goto out;
3059         }
3060     }
3061
3062     /* And if we're supposed to preallocate metadata, do that now */
3063     if (qcow2_opts->preallocation != PREALLOC_MODE_OFF) {
3064         BDRVQcow2State *s = blk_bs(blk)->opaque;
3065         qemu_co_mutex_lock(&s->lock);
3066         ret = preallocate_co(blk_bs(blk), 0, qcow2_opts->size);
3067         qemu_co_mutex_unlock(&s->lock);
3068
3069         if (ret < 0) {
3070             error_setg_errno(errp, -ret, "Could not preallocate metadata");
3071             goto out;
3072         }
3073     }
3074
3075     blk_unref(blk);
3076     blk = NULL;
3077
3078     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3079      * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3080      * have to setup decryption context. We're not doing any I/O on the top
3081      * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3082      * not have effect.
3083      */
3084     options = qdict_new();
3085     qdict_put_str(options, "driver", "qcow2");
3086     qdict_put_str(options, "file", bs->node_name);
3087     blk = blk_new_open(NULL, NULL, options,
3088                        BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3089                        &local_err);
3090     if (blk == NULL) {
3091         error_propagate(errp, local_err);
3092         ret = -EIO;
3093         goto out;
3094     }
3095
3096     ret = 0;
3097 out:
3098     blk_unref(blk);
3099     bdrv_unref(bs);
3100     return ret;
3101 }
3102
3103 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3104                                              Error **errp)
3105 {
3106     BlockdevCreateOptions *create_options = NULL;
3107     QDict *qdict;
3108     Visitor *v;
3109     BlockDriverState *bs = NULL;
3110     Error *local_err = NULL;
3111     const char *val;
3112     int ret;
3113
3114     /* Only the keyval visitor supports the dotted syntax needed for
3115      * encryption, so go through a QDict before getting a QAPI type. Ignore
3116      * options meant for the protocol layer so that the visitor doesn't
3117      * complain. */
3118     qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3119                                         true);
3120
3121     /* Handle encryption options */
3122     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3123     if (val && !strcmp(val, "on")) {
3124         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3125     } else if (val && !strcmp(val, "off")) {
3126         qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3127     }
3128
3129     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3130     if (val && !strcmp(val, "aes")) {
3131         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3132     }
3133
3134     /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3135      * version=v2/v3 below. */
3136     val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3137     if (val && !strcmp(val, "0.10")) {
3138         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3139     } else if (val && !strcmp(val, "1.1")) {
3140         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3141     }
3142
3143     /* Change legacy command line options into QMP ones */
3144     static const QDictRenames opt_renames[] = {
3145         { BLOCK_OPT_BACKING_FILE,       "backing-file" },
3146         { BLOCK_OPT_BACKING_FMT,        "backing-fmt" },
3147         { BLOCK_OPT_CLUSTER_SIZE,       "cluster-size" },
3148         { BLOCK_OPT_LAZY_REFCOUNTS,     "lazy-refcounts" },
3149         { BLOCK_OPT_REFCOUNT_BITS,      "refcount-bits" },
3150         { BLOCK_OPT_ENCRYPT,            BLOCK_OPT_ENCRYPT_FORMAT },
3151         { BLOCK_OPT_COMPAT_LEVEL,       "version" },
3152         { NULL, NULL },
3153     };
3154
3155     if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3156         ret = -EINVAL;
3157         goto finish;
3158     }
3159
3160     /* Create and open the file (protocol layer) */
3161     ret = bdrv_create_file(filename, opts, errp);
3162     if (ret < 0) {
3163         goto finish;
3164     }
3165
3166     bs = bdrv_open(filename, NULL, NULL,
3167                    BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3168     if (bs == NULL) {
3169         ret = -EIO;
3170         goto finish;
3171     }
3172
3173     /* Set 'driver' and 'node' options */
3174     qdict_put_str(qdict, "driver", "qcow2");
3175     qdict_put_str(qdict, "file", bs->node_name);
3176
3177     /* Now get the QAPI type BlockdevCreateOptions */
3178     v = qobject_input_visitor_new_flat_confused(qdict, errp);
3179     if (!v) {
3180         ret = -EINVAL;
3181         goto finish;
3182     }
3183
3184     visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3185     visit_free(v);
3186
3187     if (local_err) {
3188         error_propagate(errp, local_err);
3189         ret = -EINVAL;
3190         goto finish;
3191     }
3192
3193     /* Silently round up size */
3194     create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3195                                             BDRV_SECTOR_SIZE);
3196
3197     /* Create the qcow2 image (format layer) */
3198     ret = qcow2_co_create(create_options, errp);
3199     if (ret < 0) {
3200         goto finish;
3201     }
3202
3203     ret = 0;
3204 finish:
3205     qobject_unref(qdict);
3206     bdrv_unref(bs);
3207     qapi_free_BlockdevCreateOptions(create_options);
3208     return ret;
3209 }
3210
3211
3212 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3213 {
3214     int64_t nr;
3215     int res;
3216
3217     /* Clamp to image length, before checking status of underlying sectors */
3218     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3219         bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3220     }
3221
3222     if (!bytes) {
3223         return true;
3224     }
3225     res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3226     return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3227 }
3228
3229 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3230     int64_t offset, int bytes, BdrvRequestFlags flags)
3231 {
3232     int ret;
3233     BDRVQcow2State *s = bs->opaque;
3234
3235     uint32_t head = offset % s->cluster_size;
3236     uint32_t tail = (offset + bytes) % s->cluster_size;
3237
3238     trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3239     if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3240         tail = 0;
3241     }
3242
3243     if (head || tail) {
3244         uint64_t off;
3245         unsigned int nr;
3246
3247         assert(head + bytes <= s->cluster_size);
3248
3249         /* check whether remainder of cluster already reads as zero */
3250         if (!(is_zero(bs, offset - head, head) &&
3251               is_zero(bs, offset + bytes,
3252                       tail ? s->cluster_size - tail : 0))) {
3253             return -ENOTSUP;
3254         }
3255
3256         qemu_co_mutex_lock(&s->lock);
3257         /* We can have new write after previous check */
3258         offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3259         bytes = s->cluster_size;
3260         nr = s->cluster_size;
3261         ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3262         if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3263             ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3264             ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3265             qemu_co_mutex_unlock(&s->lock);
3266             return -ENOTSUP;
3267         }
3268     } else {
3269         qemu_co_mutex_lock(&s->lock);
3270     }
3271
3272     trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3273
3274     /* Whatever is left can use real zero clusters */
3275     ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3276     qemu_co_mutex_unlock(&s->lock);
3277
3278     return ret;
3279 }
3280
3281 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3282                                           int64_t offset, int bytes)
3283 {
3284     int ret;
3285     BDRVQcow2State *s = bs->opaque;
3286
3287     if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3288         assert(bytes < s->cluster_size);
3289         /* Ignore partial clusters, except for the special case of the
3290          * complete partial cluster at the end of an unaligned file */
3291         if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3292             offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3293             return -ENOTSUP;
3294         }
3295     }
3296
3297     qemu_co_mutex_lock(&s->lock);
3298     ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3299                                 false);
3300     qemu_co_mutex_unlock(&s->lock);
3301     return ret;
3302 }
3303
3304 static int coroutine_fn
3305 qcow2_co_copy_range_from(BlockDriverState *bs,
3306                          BdrvChild *src, uint64_t src_offset,
3307                          BdrvChild *dst, uint64_t dst_offset,
3308                          uint64_t bytes, BdrvRequestFlags read_flags,
3309                          BdrvRequestFlags write_flags)
3310 {
3311     BDRVQcow2State *s = bs->opaque;
3312     int ret;
3313     unsigned int cur_bytes; /* number of bytes in current iteration */
3314     BdrvChild *child = NULL;
3315     BdrvRequestFlags cur_write_flags;
3316
3317     assert(!bs->encrypted);
3318     qemu_co_mutex_lock(&s->lock);
3319
3320     while (bytes != 0) {
3321         uint64_t copy_offset = 0;
3322         /* prepare next request */
3323         cur_bytes = MIN(bytes, INT_MAX);
3324         cur_write_flags = write_flags;
3325
3326         ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3327         if (ret < 0) {
3328             goto out;
3329         }
3330
3331         switch (ret) {
3332         case QCOW2_CLUSTER_UNALLOCATED:
3333             if (bs->backing && bs->backing->bs) {
3334                 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3335                 if (src_offset >= backing_length) {
3336                     cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3337                 } else {
3338                     child = bs->backing;
3339                     cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3340                     copy_offset = src_offset;
3341                 }
3342             } else {
3343                 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3344             }
3345             break;
3346
3347         case QCOW2_CLUSTER_ZERO_PLAIN:
3348         case QCOW2_CLUSTER_ZERO_ALLOC:
3349             cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3350             break;
3351
3352         case QCOW2_CLUSTER_COMPRESSED:
3353             ret = -ENOTSUP;
3354             goto out;
3355
3356         case QCOW2_CLUSTER_NORMAL:
3357             child = bs->file;
3358             copy_offset += offset_into_cluster(s, src_offset);
3359             if ((copy_offset & 511) != 0) {
3360                 ret = -EIO;
3361                 goto out;
3362             }
3363             break;
3364
3365         default:
3366             abort();
3367         }
3368         qemu_co_mutex_unlock(&s->lock);
3369         ret = bdrv_co_copy_range_from(child,
3370                                       copy_offset,
3371                                       dst, dst_offset,
3372                                       cur_bytes, read_flags, cur_write_flags);
3373         qemu_co_mutex_lock(&s->lock);
3374         if (ret < 0) {
3375             goto out;
3376         }
3377
3378         bytes -= cur_bytes;
3379         src_offset += cur_bytes;
3380         dst_offset += cur_bytes;
3381     }
3382     ret = 0;
3383
3384 out:
3385     qemu_co_mutex_unlock(&s->lock);
3386     return ret;
3387 }
3388
3389 static int coroutine_fn
3390 qcow2_co_copy_range_to(BlockDriverState *bs,
3391                        BdrvChild *src, uint64_t src_offset,
3392                        BdrvChild *dst, uint64_t dst_offset,
3393                        uint64_t bytes, BdrvRequestFlags read_flags,
3394                        BdrvRequestFlags write_flags)
3395 {
3396     BDRVQcow2State *s = bs->opaque;
3397     int offset_in_cluster;
3398     int ret;
3399     unsigned int cur_bytes; /* number of sectors in current iteration */
3400     uint64_t cluster_offset;
3401     QCowL2Meta *l2meta = NULL;
3402
3403     assert(!bs->encrypted);
3404     s->cluster_cache_offset = -1; /* disable compressed cache */
3405
3406     qemu_co_mutex_lock(&s->lock);
3407
3408     while (bytes != 0) {
3409
3410         l2meta = NULL;
3411
3412         offset_in_cluster = offset_into_cluster(s, dst_offset);
3413         cur_bytes = MIN(bytes, INT_MAX);
3414
3415         /* TODO:
3416          * If src->bs == dst->bs, we could simply copy by incrementing
3417          * the refcnt, without copying user data.
3418          * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3419         ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3420                                          &cluster_offset, &l2meta);
3421         if (ret < 0) {
3422             goto fail;
3423         }
3424
3425         assert((cluster_offset & 511) == 0);
3426
3427         ret = qcow2_pre_write_overlap_check(bs, 0,
3428                 cluster_offset + offset_in_cluster, cur_bytes);
3429         if (ret < 0) {
3430             goto fail;
3431         }
3432
3433         qemu_co_mutex_unlock(&s->lock);
3434         ret = bdrv_co_copy_range_to(src, src_offset,
3435                                     bs->file,
3436                                     cluster_offset + offset_in_cluster,
3437                                     cur_bytes, read_flags, write_flags);
3438         qemu_co_mutex_lock(&s->lock);
3439         if (ret < 0) {
3440             goto fail;
3441         }
3442
3443         ret = qcow2_handle_l2meta(bs, &l2meta, true);
3444         if (ret) {
3445             goto fail;
3446         }
3447
3448         bytes -= cur_bytes;
3449         src_offset += cur_bytes;
3450         dst_offset += cur_bytes;
3451     }
3452     ret = 0;
3453
3454 fail:
3455     qcow2_handle_l2meta(bs, &l2meta, false);
3456
3457     qemu_co_mutex_unlock(&s->lock);
3458
3459     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3460
3461     return ret;
3462 }
3463
3464 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3465                                           PreallocMode prealloc, Error **errp)
3466 {
3467     BDRVQcow2State *s = bs->opaque;
3468     uint64_t old_length;
3469     int64_t new_l1_size;
3470     int ret;
3471     QDict *options;
3472
3473     if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3474         prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3475     {
3476         error_setg(errp, "Unsupported preallocation mode '%s'",
3477                    PreallocMode_str(prealloc));
3478         return -ENOTSUP;
3479     }
3480
3481     if (offset & 511) {
3482         error_setg(errp, "The new size must be a multiple of 512");
3483         return -EINVAL;
3484     }
3485
3486     qemu_co_mutex_lock(&s->lock);
3487
3488     /* cannot proceed if image has snapshots */
3489     if (s->nb_snapshots) {
3490         error_setg(errp, "Can't resize an image which has snapshots");
3491         ret = -ENOTSUP;
3492         goto fail;
3493     }
3494
3495     /* cannot proceed if image has bitmaps */
3496     if (s->nb_bitmaps) {
3497         /* TODO: resize bitmaps in the image */
3498         error_setg(errp, "Can't resize an image which has bitmaps");
3499         ret = -ENOTSUP;
3500         goto fail;
3501     }
3502
3503     old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
3504     new_l1_size = size_to_l1(s, offset);
3505
3506     if (offset < old_length) {
3507         int64_t last_cluster, old_file_size;
3508         if (prealloc != PREALLOC_MODE_OFF) {
3509             error_setg(errp,
3510                        "Preallocation can't be used for shrinking an image");
3511             ret = -EINVAL;
3512             goto fail;
3513         }
3514
3515         ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3516                                     old_length - ROUND_UP(offset,
3517                                                           s->cluster_size),
3518                                     QCOW2_DISCARD_ALWAYS, true);
3519         if (ret < 0) {
3520             error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3521             goto fail;
3522         }
3523
3524         ret = qcow2_shrink_l1_table(bs, new_l1_size);
3525         if (ret < 0) {
3526             error_setg_errno(errp, -ret,
3527                              "Failed to reduce the number of L2 tables");
3528             goto fail;
3529         }
3530
3531         ret = qcow2_shrink_reftable(bs);
3532         if (ret < 0) {
3533             error_setg_errno(errp, -ret,
3534                              "Failed to discard unused refblocks");
3535             goto fail;
3536         }
3537
3538         old_file_size = bdrv_getlength(bs->file->bs);
3539         if (old_file_size < 0) {
3540             error_setg_errno(errp, -old_file_size,
3541                              "Failed to inquire current file length");
3542             ret = old_file_size;
3543             goto fail;
3544         }
3545         last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3546         if (last_cluster < 0) {
3547             error_setg_errno(errp, -last_cluster,
3548                              "Failed to find the last cluster");
3549             ret = last_cluster;
3550             goto fail;
3551         }
3552         if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3553             Error *local_err = NULL;
3554
3555             bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3556                              PREALLOC_MODE_OFF, &local_err);
3557             if (local_err) {
3558                 warn_reportf_err(local_err,
3559                                  "Failed to truncate the tail of the image: ");
3560             }
3561         }
3562     } else {
3563         ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3564         if (ret < 0) {
3565             error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3566             goto fail;
3567         }
3568     }
3569
3570     switch (prealloc) {
3571     case PREALLOC_MODE_OFF:
3572         break;
3573
3574     case PREALLOC_MODE_METADATA:
3575         ret = preallocate_co(bs, old_length, offset);
3576         if (ret < 0) {
3577             error_setg_errno(errp, -ret, "Preallocation failed");
3578             goto fail;
3579         }
3580         break;
3581
3582     case PREALLOC_MODE_FALLOC:
3583     case PREALLOC_MODE_FULL:
3584     {
3585         int64_t allocation_start, host_offset, guest_offset;
3586         int64_t clusters_allocated;
3587         int64_t old_file_size, new_file_size;
3588         uint64_t nb_new_data_clusters, nb_new_l2_tables;
3589
3590         old_file_size = bdrv_getlength(bs->file->bs);
3591         if (old_file_size < 0) {
3592             error_setg_errno(errp, -old_file_size,
3593                              "Failed to inquire current file length");
3594             ret = old_file_size;
3595             goto fail;
3596         }
3597         old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3598
3599         nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3600                                             s->cluster_size);
3601
3602         /* This is an overestimation; we will not actually allocate space for
3603          * these in the file but just make sure the new refcount structures are
3604          * able to cover them so we will not have to allocate new refblocks
3605          * while entering the data blocks in the potentially new L2 tables.
3606          * (We do not actually care where the L2 tables are placed. Maybe they
3607          *  are already allocated or they can be placed somewhere before
3608          *  @old_file_size. It does not matter because they will be fully
3609          *  allocated automatically, so they do not need to be covered by the
3610          *  preallocation. All that matters is that we will not have to allocate
3611          *  new refcount structures for them.) */
3612         nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3613                                         s->cluster_size / sizeof(uint64_t));
3614         /* The cluster range may not be aligned to L2 boundaries, so add one L2
3615          * table for a potential head/tail */
3616         nb_new_l2_tables++;
3617
3618         allocation_start = qcow2_refcount_area(bs, old_file_size,
3619                                                nb_new_data_clusters +
3620                                                nb_new_l2_tables,
3621                                                true, 0, 0);
3622         if (allocation_start < 0) {
3623             error_setg_errno(errp, -allocation_start,
3624                              "Failed to resize refcount structures");
3625             ret = allocation_start;
3626             goto fail;
3627         }
3628
3629         clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3630                                                      nb_new_data_clusters);
3631         if (clusters_allocated < 0) {
3632             error_setg_errno(errp, -clusters_allocated,
3633                              "Failed to allocate data clusters");
3634             ret = clusters_allocated;
3635             goto fail;
3636         }
3637
3638         assert(clusters_allocated == nb_new_data_clusters);
3639
3640         /* Allocate the data area */
3641         new_file_size = allocation_start +
3642                         nb_new_data_clusters * s->cluster_size;
3643         ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
3644         if (ret < 0) {
3645             error_prepend(errp, "Failed to resize underlying file: ");
3646             qcow2_free_clusters(bs, allocation_start,
3647                                 nb_new_data_clusters * s->cluster_size,
3648                                 QCOW2_DISCARD_OTHER);
3649             goto fail;
3650         }
3651
3652         /* Create the necessary L2 entries */
3653         host_offset = allocation_start;
3654         guest_offset = old_length;
3655         while (nb_new_data_clusters) {
3656             int64_t nb_clusters = MIN(
3657                 nb_new_data_clusters,
3658                 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3659             QCowL2Meta allocation = {
3660                 .offset       = guest_offset,
3661                 .alloc_offset = host_offset,
3662                 .nb_clusters  = nb_clusters,
3663             };
3664             qemu_co_queue_init(&allocation.dependent_requests);
3665
3666             ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3667             if (ret < 0) {
3668                 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3669                 qcow2_free_clusters(bs, host_offset,
3670                                     nb_new_data_clusters * s->cluster_size,
3671                                     QCOW2_DISCARD_OTHER);
3672                 goto fail;
3673             }
3674
3675             guest_offset += nb_clusters * s->cluster_size;
3676             host_offset += nb_clusters * s->cluster_size;
3677             nb_new_data_clusters -= nb_clusters;
3678         }
3679         break;
3680     }
3681
3682     default:
3683         g_assert_not_reached();
3684     }
3685
3686     if (prealloc != PREALLOC_MODE_OFF) {
3687         /* Flush metadata before actually changing the image size */
3688         ret = qcow2_write_caches(bs);
3689         if (ret < 0) {
3690             error_setg_errno(errp, -ret,
3691                              "Failed to flush the preallocated area to disk");
3692             goto fail;
3693         }
3694     }
3695
3696     bs->total_sectors = offset / BDRV_SECTOR_SIZE;
3697
3698     /* write updated header.size */
3699     offset = cpu_to_be64(offset);
3700     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3701                            &offset, sizeof(uint64_t));
3702     if (ret < 0) {
3703         error_setg_errno(errp, -ret, "Failed to update the image size");
3704         goto fail;
3705     }
3706
3707     s->l1_vm_state_index = new_l1_size;
3708
3709     /* Update cache sizes */
3710     options = qdict_clone_shallow(bs->options);
3711     ret = qcow2_update_options(bs, options, s->flags, errp);
3712     qobject_unref(options);
3713     if (ret < 0) {
3714         goto fail;
3715     }
3716     ret = 0;
3717 fail:
3718     qemu_co_mutex_unlock(&s->lock);
3719     return ret;
3720 }
3721
3722 /*
3723  * qcow2_compress()
3724  *
3725  * @dest - destination buffer, @dest_size bytes
3726  * @src - source buffer, @src_size bytes
3727  *
3728  * Returns: compressed size on success
3729  *          -1 destination buffer is not enough to store compressed data
3730  *          -2 on any other error
3731  */
3732 static ssize_t qcow2_compress(void *dest, size_t dest_size,
3733                               const void *src, size_t src_size)
3734 {
3735     ssize_t ret;
3736     z_stream strm;
3737
3738     /* best compression, small window, no zlib header */
3739     memset(&strm, 0, sizeof(strm));
3740     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
3741                        -12, 9, Z_DEFAULT_STRATEGY);
3742     if (ret != Z_OK) {
3743         return -2;
3744     }
3745
3746     /* strm.next_in is not const in old zlib versions, such as those used on
3747      * OpenBSD/NetBSD, so cast the const away */
3748     strm.avail_in = src_size;
3749     strm.next_in = (void *) src;
3750     strm.avail_out = dest_size;
3751     strm.next_out = dest;
3752
3753     ret = deflate(&strm, Z_FINISH);
3754     if (ret == Z_STREAM_END) {
3755         ret = dest_size - strm.avail_out;
3756     } else {
3757         ret = (ret == Z_OK ? -1 : -2);
3758     }
3759
3760     deflateEnd(&strm);
3761
3762     return ret;
3763 }
3764
3765 /*
3766  * qcow2_decompress()
3767  *
3768  * Decompress some data (not more than @src_size bytes) to produce exactly
3769  * @dest_size bytes.
3770  *
3771  * @dest - destination buffer, @dest_size bytes
3772  * @src - source buffer, @src_size bytes
3773  *
3774  * Returns: 0 on success
3775  *          -1 on fail
3776  */
3777 static ssize_t qcow2_decompress(void *dest, size_t dest_size,
3778                                 const void *src, size_t src_size)
3779 {
3780     int ret = 0;
3781     z_stream strm;
3782
3783     memset(&strm, 0, sizeof(strm));
3784     strm.avail_in = src_size;
3785     strm.next_in = (void *) src;
3786     strm.avail_out = dest_size;
3787     strm.next_out = dest;
3788
3789     ret = inflateInit2(&strm, -12);
3790     if (ret != Z_OK) {
3791         return -1;
3792     }
3793
3794     ret = inflate(&strm, Z_FINISH);
3795     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) || strm.avail_out != 0) {
3796         /* We approve Z_BUF_ERROR because we need @dest buffer to be filled, but
3797          * @src buffer may be processed partly (because in qcow2 we know size of
3798          * compressed data with precision of one sector) */
3799         ret = -1;
3800     }
3801
3802     inflateEnd(&strm);
3803
3804     return ret;
3805 }
3806
3807 #define MAX_COMPRESS_THREADS 4
3808
3809 typedef struct Qcow2CompressData {
3810     void *dest;
3811     size_t dest_size;
3812     const void *src;
3813     size_t src_size;
3814     ssize_t ret;
3815 } Qcow2CompressData;
3816
3817 static int qcow2_compress_pool_func(void *opaque)
3818 {
3819     Qcow2CompressData *data = opaque;
3820
3821     data->ret = qcow2_compress(data->dest, data->dest_size,
3822                                data->src, data->src_size);
3823
3824     return 0;
3825 }
3826
3827 static void qcow2_compress_complete(void *opaque, int ret)
3828 {
3829     qemu_coroutine_enter(opaque);
3830 }
3831
3832 /* See qcow2_compress definition for parameters description */
3833 static ssize_t qcow2_co_compress(BlockDriverState *bs,
3834                                  void *dest, size_t dest_size,
3835                                  const void *src, size_t src_size)
3836 {
3837     BDRVQcow2State *s = bs->opaque;
3838     BlockAIOCB *acb;
3839     ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
3840     Qcow2CompressData arg = {
3841         .dest = dest,
3842         .dest_size = dest_size,
3843         .src = src,
3844         .src_size = src_size,
3845     };
3846
3847     while (s->nb_compress_threads >= MAX_COMPRESS_THREADS) {
3848         qemu_co_queue_wait(&s->compress_wait_queue, NULL);
3849     }
3850
3851     s->nb_compress_threads++;
3852     acb = thread_pool_submit_aio(pool, qcow2_compress_pool_func, &arg,
3853                                  qcow2_compress_complete,
3854                                  qemu_coroutine_self());
3855
3856     if (!acb) {
3857         s->nb_compress_threads--;
3858         return -EINVAL;
3859     }
3860     qemu_coroutine_yield();
3861     s->nb_compress_threads--;
3862     qemu_co_queue_next(&s->compress_wait_queue);
3863
3864     return arg.ret;
3865 }
3866
3867 /* XXX: put compressed sectors first, then all the cluster aligned
3868    tables to avoid losing bytes in alignment */
3869 static coroutine_fn int
3870 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3871                             uint64_t bytes, QEMUIOVector *qiov)
3872 {
3873     BDRVQcow2State *s = bs->opaque;
3874     QEMUIOVector hd_qiov;
3875     struct iovec iov;
3876     int ret;
3877     size_t out_len;
3878     uint8_t *buf, *out_buf;
3879     int64_t cluster_offset;
3880
3881     if (bytes == 0) {
3882         /* align end of file to a sector boundary to ease reading with
3883            sector based I/Os */
3884         cluster_offset = bdrv_getlength(bs->file->bs);
3885         if (cluster_offset < 0) {
3886             return cluster_offset;
3887         }
3888         return bdrv_co_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF,
3889                                 NULL);
3890     }
3891
3892     if (offset_into_cluster(s, offset)) {
3893         return -EINVAL;
3894     }
3895
3896     buf = qemu_blockalign(bs, s->cluster_size);
3897     if (bytes != s->cluster_size) {
3898         if (bytes > s->cluster_size ||
3899             offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3900         {
3901             qemu_vfree(buf);
3902             return -EINVAL;
3903         }
3904         /* Zero-pad last write if image size is not cluster aligned */
3905         memset(buf + bytes, 0, s->cluster_size - bytes);
3906     }
3907     qemu_iovec_to_buf(qiov, 0, buf, bytes);
3908
3909     out_buf = g_malloc(s->cluster_size);
3910
3911     out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
3912                                 buf, s->cluster_size);
3913     if (out_len == -2) {
3914         ret = -EINVAL;
3915         goto fail;
3916     } else if (out_len == -1) {
3917         /* could not compress: write normal cluster */
3918         ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3919         if (ret < 0) {
3920             goto fail;
3921         }
3922         goto success;
3923     }
3924
3925     qemu_co_mutex_lock(&s->lock);
3926     cluster_offset =
3927         qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3928     if (!cluster_offset) {
3929         qemu_co_mutex_unlock(&s->lock);
3930         ret = -EIO;
3931         goto fail;
3932     }
3933     cluster_offset &= s->cluster_offset_mask;
3934
3935     ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3936     qemu_co_mutex_unlock(&s->lock);
3937     if (ret < 0) {
3938         goto fail;
3939     }
3940
3941     iov = (struct iovec) {
3942         .iov_base   = out_buf,
3943         .iov_len    = out_len,
3944     };
3945     qemu_iovec_init_external(&hd_qiov, &iov, 1);
3946
3947     BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3948     ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3949     if (ret < 0) {
3950         goto fail;
3951     }
3952 success:
3953     ret = 0;
3954 fail:
3955     qemu_vfree(buf);
3956     g_free(out_buf);
3957     return ret;
3958 }
3959
3960 int coroutine_fn
3961 qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
3962 {
3963     BDRVQcow2State *s = bs->opaque;
3964     int ret, csize, nb_csectors;
3965     uint64_t coffset;
3966     struct iovec iov;
3967     QEMUIOVector local_qiov;
3968
3969     coffset = cluster_offset & s->cluster_offset_mask;
3970     if (s->cluster_cache_offset != coffset) {
3971         nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
3972         csize = nb_csectors * 512 - (coffset & 511);
3973
3974         /* Allocate buffers on first decompress operation, most images are
3975          * uncompressed and the memory overhead can be avoided.  The buffers
3976          * are freed in .bdrv_close().
3977          */
3978         if (!s->cluster_data) {
3979             /* one more sector for decompressed data alignment */
3980             s->cluster_data = qemu_try_blockalign(bs->file->bs,
3981                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size + 512);
3982             if (!s->cluster_data) {
3983                 return -ENOMEM;
3984             }
3985         }
3986         if (!s->cluster_cache) {
3987             s->cluster_cache = g_malloc(s->cluster_size);
3988         }
3989
3990         iov.iov_base = s->cluster_data;
3991         iov.iov_len = csize;
3992         qemu_iovec_init_external(&local_qiov, &iov, 1);
3993
3994         BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
3995         ret = bdrv_co_preadv(bs->file, coffset, csize, &local_qiov, 0);
3996         if (ret < 0) {
3997             return ret;
3998         }
3999         if (qcow2_decompress(s->cluster_cache, s->cluster_size,
4000                              s->cluster_data, csize) < 0) {
4001             return -EIO;
4002         }
4003         s->cluster_cache_offset = coffset;
4004     }
4005     return 0;
4006 }
4007
4008 static int make_completely_empty(BlockDriverState *bs)
4009 {
4010     BDRVQcow2State *s = bs->opaque;
4011     Error *local_err = NULL;
4012     int ret, l1_clusters;
4013     int64_t offset;
4014     uint64_t *new_reftable = NULL;
4015     uint64_t rt_entry, l1_size2;
4016     struct {
4017         uint64_t l1_offset;
4018         uint64_t reftable_offset;
4019         uint32_t reftable_clusters;
4020     } QEMU_PACKED l1_ofs_rt_ofs_cls;
4021
4022     ret = qcow2_cache_empty(bs, s->l2_table_cache);
4023     if (ret < 0) {
4024         goto fail;
4025     }
4026
4027     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4028     if (ret < 0) {
4029         goto fail;
4030     }
4031
4032     /* Refcounts will be broken utterly */
4033     ret = qcow2_mark_dirty(bs);
4034     if (ret < 0) {
4035         goto fail;
4036     }
4037
4038     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4039
4040     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4041     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4042
4043     /* After this call, neither the in-memory nor the on-disk refcount
4044      * information accurately describe the actual references */
4045
4046     ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
4047                              l1_clusters * s->cluster_size, 0);
4048     if (ret < 0) {
4049         goto fail_broken_refcounts;
4050     }
4051     memset(s->l1_table, 0, l1_size2);
4052
4053     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4054
4055     /* Overwrite enough clusters at the beginning of the sectors to place
4056      * the refcount table, a refcount block and the L1 table in; this may
4057      * overwrite parts of the existing refcount and L1 table, which is not
4058      * an issue because the dirty flag is set, complete data loss is in fact
4059      * desired and partial data loss is consequently fine as well */
4060     ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
4061                              (2 + l1_clusters) * s->cluster_size, 0);
4062     /* This call (even if it failed overall) may have overwritten on-disk
4063      * refcount structures; in that case, the in-memory refcount information
4064      * will probably differ from the on-disk information which makes the BDS
4065      * unusable */
4066     if (ret < 0) {
4067         goto fail_broken_refcounts;
4068     }
4069
4070     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4071     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4072
4073     /* "Create" an empty reftable (one cluster) directly after the image
4074      * header and an empty L1 table three clusters after the image header;
4075      * the cluster between those two will be used as the first refblock */
4076     l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4077     l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4078     l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4079     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
4080                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4081     if (ret < 0) {
4082         goto fail_broken_refcounts;
4083     }
4084
4085     s->l1_table_offset = 3 * s->cluster_size;
4086
4087     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4088     if (!new_reftable) {
4089         ret = -ENOMEM;
4090         goto fail_broken_refcounts;
4091     }
4092
4093     s->refcount_table_offset = s->cluster_size;
4094     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
4095     s->max_refcount_table_index = 0;
4096
4097     g_free(s->refcount_table);
4098     s->refcount_table = new_reftable;
4099     new_reftable = NULL;
4100
4101     /* Now the in-memory refcount information again corresponds to the on-disk
4102      * information (reftable is empty and no refblocks (the refblock cache is
4103      * empty)); however, this means some clusters (e.g. the image header) are
4104      * referenced, but not refcounted, but the normal qcow2 code assumes that
4105      * the in-memory information is always correct */
4106
4107     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4108
4109     /* Enter the first refblock into the reftable */
4110     rt_entry = cpu_to_be64(2 * s->cluster_size);
4111     ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
4112                            &rt_entry, sizeof(rt_entry));
4113     if (ret < 0) {
4114         goto fail_broken_refcounts;
4115     }
4116     s->refcount_table[0] = 2 * s->cluster_size;
4117
4118     s->free_cluster_index = 0;
4119     assert(3 + l1_clusters <= s->refcount_block_size);
4120     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4121     if (offset < 0) {
4122         ret = offset;
4123         goto fail_broken_refcounts;
4124     } else if (offset > 0) {
4125         error_report("First cluster in emptied image is in use");
4126         abort();
4127     }
4128
4129     /* Now finally the in-memory information corresponds to the on-disk
4130      * structures and is correct */
4131     ret = qcow2_mark_clean(bs);
4132     if (ret < 0) {
4133         goto fail;
4134     }
4135
4136     ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
4137                         PREALLOC_MODE_OFF, &local_err);
4138     if (ret < 0) {
4139         error_report_err(local_err);
4140         goto fail;
4141     }
4142
4143     return 0;
4144
4145 fail_broken_refcounts:
4146     /* The BDS is unusable at this point. If we wanted to make it usable, we
4147      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4148      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4149      * again. However, because the functions which could have caused this error
4150      * path to be taken are used by those functions as well, it's very likely
4151      * that that sequence will fail as well. Therefore, just eject the BDS. */
4152     bs->drv = NULL;
4153
4154 fail:
4155     g_free(new_reftable);
4156     return ret;
4157 }
4158
4159 static int qcow2_make_empty(BlockDriverState *bs)
4160 {
4161     BDRVQcow2State *s = bs->opaque;
4162     uint64_t offset, end_offset;
4163     int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4164     int l1_clusters, ret = 0;
4165
4166     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4167
4168     if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4169         3 + l1_clusters <= s->refcount_block_size &&
4170         s->crypt_method_header != QCOW_CRYPT_LUKS) {
4171         /* The following function only works for qcow2 v3 images (it
4172          * requires the dirty flag) and only as long as there are no
4173          * features that reserve extra clusters (such as snapshots,
4174          * LUKS header, or persistent bitmaps), because it completely
4175          * empties the image.  Furthermore, the L1 table and three
4176          * additional clusters (image header, refcount table, one
4177          * refcount block) have to fit inside one refcount block. */
4178         return make_completely_empty(bs);
4179     }
4180
4181     /* This fallback code simply discards every active cluster; this is slow,
4182      * but works in all cases */
4183     end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4184     for (offset = 0; offset < end_offset; offset += step) {
4185         /* As this function is generally used after committing an external
4186          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4187          * default action for this kind of discard is to pass the discard,
4188          * which will ideally result in an actually smaller image file, as
4189          * is probably desired. */
4190         ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4191                                     QCOW2_DISCARD_SNAPSHOT, true);
4192         if (ret < 0) {
4193             break;
4194         }
4195     }
4196
4197     return ret;
4198 }
4199
4200 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4201 {
4202     BDRVQcow2State *s = bs->opaque;
4203     int ret;
4204
4205     qemu_co_mutex_lock(&s->lock);
4206     ret = qcow2_write_caches(bs);
4207     qemu_co_mutex_unlock(&s->lock);
4208
4209     return ret;
4210 }
4211
4212 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4213                                        Error **errp)
4214 {
4215     Error *local_err = NULL;
4216     BlockMeasureInfo *info;
4217     uint64_t required = 0; /* bytes that contribute to required size */
4218     uint64_t virtual_size; /* disk size as seen by guest */
4219     uint64_t refcount_bits;
4220     uint64_t l2_tables;
4221     size_t cluster_size;
4222     int version;
4223     char *optstr;
4224     PreallocMode prealloc;
4225     bool has_backing_file;
4226
4227     /* Parse image creation options */
4228     cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4229     if (local_err) {
4230         goto err;
4231     }
4232
4233     version = qcow2_opt_get_version_del(opts, &local_err);
4234     if (local_err) {
4235         goto err;
4236     }
4237
4238     refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4239     if (local_err) {
4240         goto err;
4241     }
4242
4243     optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4244     prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4245                                PREALLOC_MODE_OFF, &local_err);
4246     g_free(optstr);
4247     if (local_err) {
4248         goto err;
4249     }
4250
4251     optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4252     has_backing_file = !!optstr;
4253     g_free(optstr);
4254
4255     virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4256     virtual_size = ROUND_UP(virtual_size, cluster_size);
4257
4258     /* Check that virtual disk size is valid */
4259     l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4260                              cluster_size / sizeof(uint64_t));
4261     if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4262         error_setg(&local_err, "The image size is too large "
4263                                "(try using a larger cluster size)");
4264         goto err;
4265     }
4266
4267     /* Account for input image */
4268     if (in_bs) {
4269         int64_t ssize = bdrv_getlength(in_bs);
4270         if (ssize < 0) {
4271             error_setg_errno(&local_err, -ssize,
4272                              "Unable to get image virtual_size");
4273             goto err;
4274         }
4275
4276         virtual_size = ROUND_UP(ssize, cluster_size);
4277
4278         if (has_backing_file) {
4279             /* We don't how much of the backing chain is shared by the input
4280              * image and the new image file.  In the worst case the new image's
4281              * backing file has nothing in common with the input image.  Be
4282              * conservative and assume all clusters need to be written.
4283              */
4284             required = virtual_size;
4285         } else {
4286             int64_t offset;
4287             int64_t pnum = 0;
4288
4289             for (offset = 0; offset < ssize; offset += pnum) {
4290                 int ret;
4291
4292                 ret = bdrv_block_status_above(in_bs, NULL, offset,
4293                                               ssize - offset, &pnum, NULL,
4294                                               NULL);
4295                 if (ret < 0) {
4296                     error_setg_errno(&local_err, -ret,
4297                                      "Unable to get block status");
4298                     goto err;
4299                 }
4300
4301                 if (ret & BDRV_BLOCK_ZERO) {
4302                     /* Skip zero regions (safe with no backing file) */
4303                 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4304                            (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4305                     /* Extend pnum to end of cluster for next iteration */
4306                     pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4307
4308                     /* Count clusters we've seen */
4309                     required += offset % cluster_size + pnum;
4310                 }
4311             }
4312         }
4313     }
4314
4315     /* Take into account preallocation.  Nothing special is needed for
4316      * PREALLOC_MODE_METADATA since metadata is always counted.
4317      */
4318     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4319         required = virtual_size;
4320     }
4321
4322     info = g_new(BlockMeasureInfo, 1);
4323     info->fully_allocated =
4324         qcow2_calc_prealloc_size(virtual_size, cluster_size,
4325                                  ctz32(refcount_bits));
4326
4327     /* Remove data clusters that are not required.  This overestimates the
4328      * required size because metadata needed for the fully allocated file is
4329      * still counted.
4330      */
4331     info->required = info->fully_allocated - virtual_size + required;
4332     return info;
4333
4334 err:
4335     error_propagate(errp, local_err);
4336     return NULL;
4337 }
4338
4339 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4340 {
4341     BDRVQcow2State *s = bs->opaque;
4342     bdi->unallocated_blocks_are_zero = true;
4343     bdi->cluster_size = s->cluster_size;
4344     bdi->vm_state_offset = qcow2_vm_state_offset(s);
4345     return 0;
4346 }
4347
4348 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
4349 {
4350     BDRVQcow2State *s = bs->opaque;
4351     ImageInfoSpecific *spec_info;
4352     QCryptoBlockInfo *encrypt_info = NULL;
4353
4354     if (s->crypto != NULL) {
4355         encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
4356     }
4357
4358     spec_info = g_new(ImageInfoSpecific, 1);
4359     *spec_info = (ImageInfoSpecific){
4360         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
4361         .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
4362     };
4363     if (s->qcow_version == 2) {
4364         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4365             .compat             = g_strdup("0.10"),
4366             .refcount_bits      = s->refcount_bits,
4367         };
4368     } else if (s->qcow_version == 3) {
4369         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4370             .compat             = g_strdup("1.1"),
4371             .lazy_refcounts     = s->compatible_features &
4372                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
4373             .has_lazy_refcounts = true,
4374             .corrupt            = s->incompatible_features &
4375                                   QCOW2_INCOMPAT_CORRUPT,
4376             .has_corrupt        = true,
4377             .refcount_bits      = s->refcount_bits,
4378         };
4379     } else {
4380         /* if this assertion fails, this probably means a new version was
4381          * added without having it covered here */
4382         assert(false);
4383     }
4384
4385     if (encrypt_info) {
4386         ImageInfoSpecificQCow2Encryption *qencrypt =
4387             g_new(ImageInfoSpecificQCow2Encryption, 1);
4388         switch (encrypt_info->format) {
4389         case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4390             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
4391             break;
4392         case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4393             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4394             qencrypt->u.luks = encrypt_info->u.luks;
4395             break;
4396         default:
4397             abort();
4398         }
4399         /* Since we did shallow copy above, erase any pointers
4400          * in the original info */
4401         memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4402         qapi_free_QCryptoBlockInfo(encrypt_info);
4403
4404         spec_info->u.qcow2.data->has_encrypt = true;
4405         spec_info->u.qcow2.data->encrypt = qencrypt;
4406     }
4407
4408     return spec_info;
4409 }
4410
4411 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4412                               int64_t pos)
4413 {
4414     BDRVQcow2State *s = bs->opaque;
4415
4416     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4417     return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4418                                     qiov->size, qiov, 0);
4419 }
4420
4421 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4422                               int64_t pos)
4423 {
4424     BDRVQcow2State *s = bs->opaque;
4425
4426     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4427     return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4428                                    qiov->size, qiov, 0);
4429 }
4430
4431 /*
4432  * Downgrades an image's version. To achieve this, any incompatible features
4433  * have to be removed.
4434  */
4435 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4436                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4437                            Error **errp)
4438 {
4439     BDRVQcow2State *s = bs->opaque;
4440     int current_version = s->qcow_version;
4441     int ret;
4442
4443     /* This is qcow2_downgrade(), not qcow2_upgrade() */
4444     assert(target_version < current_version);
4445
4446     /* There are no other versions (now) that you can downgrade to */
4447     assert(target_version == 2);
4448
4449     if (s->refcount_order != 4) {
4450         error_setg(errp, "compat=0.10 requires refcount_bits=16");
4451         return -ENOTSUP;
4452     }
4453
4454     /* clear incompatible features */
4455     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4456         ret = qcow2_mark_clean(bs);
4457         if (ret < 0) {
4458             error_setg_errno(errp, -ret, "Failed to make the image clean");
4459             return ret;
4460         }
4461     }
4462
4463     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4464      * the first place; if that happens nonetheless, returning -ENOTSUP is the
4465      * best thing to do anyway */
4466
4467     if (s->incompatible_features) {
4468         error_setg(errp, "Cannot downgrade an image with incompatible features "
4469                    "%#" PRIx64 " set", s->incompatible_features);
4470         return -ENOTSUP;
4471     }
4472
4473     /* since we can ignore compatible features, we can set them to 0 as well */
4474     s->compatible_features = 0;
4475     /* if lazy refcounts have been used, they have already been fixed through
4476      * clearing the dirty flag */
4477
4478     /* clearing autoclear features is trivial */
4479     s->autoclear_features = 0;
4480
4481     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
4482     if (ret < 0) {
4483         error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
4484         return ret;
4485     }
4486
4487     s->qcow_version = target_version;
4488     ret = qcow2_update_header(bs);
4489     if (ret < 0) {
4490         s->qcow_version = current_version;
4491         error_setg_errno(errp, -ret, "Failed to update the image header");
4492         return ret;
4493     }
4494     return 0;
4495 }
4496
4497 typedef enum Qcow2AmendOperation {
4498     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4499      * statically initialized to so that the helper CB can discern the first
4500      * invocation from an operation change */
4501     QCOW2_NO_OPERATION = 0,
4502
4503     QCOW2_CHANGING_REFCOUNT_ORDER,
4504     QCOW2_DOWNGRADING,
4505 } Qcow2AmendOperation;
4506
4507 typedef struct Qcow2AmendHelperCBInfo {
4508     /* The code coordinating the amend operations should only modify
4509      * these four fields; the rest will be managed by the CB */
4510     BlockDriverAmendStatusCB *original_status_cb;
4511     void *original_cb_opaque;
4512
4513     Qcow2AmendOperation current_operation;
4514
4515     /* Total number of operations to perform (only set once) */
4516     int total_operations;
4517
4518     /* The following fields are managed by the CB */
4519
4520     /* Number of operations completed */
4521     int operations_completed;
4522
4523     /* Cumulative offset of all completed operations */
4524     int64_t offset_completed;
4525
4526     Qcow2AmendOperation last_operation;
4527     int64_t last_work_size;
4528 } Qcow2AmendHelperCBInfo;
4529
4530 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4531                                   int64_t operation_offset,
4532                                   int64_t operation_work_size, void *opaque)
4533 {
4534     Qcow2AmendHelperCBInfo *info = opaque;
4535     int64_t current_work_size;
4536     int64_t projected_work_size;
4537
4538     if (info->current_operation != info->last_operation) {
4539         if (info->last_operation != QCOW2_NO_OPERATION) {
4540             info->offset_completed += info->last_work_size;
4541             info->operations_completed++;
4542         }
4543
4544         info->last_operation = info->current_operation;
4545     }
4546
4547     assert(info->total_operations > 0);
4548     assert(info->operations_completed < info->total_operations);
4549
4550     info->last_work_size = operation_work_size;
4551
4552     current_work_size = info->offset_completed + operation_work_size;
4553
4554     /* current_work_size is the total work size for (operations_completed + 1)
4555      * operations (which includes this one), so multiply it by the number of
4556      * operations not covered and divide it by the number of operations
4557      * covered to get a projection for the operations not covered */
4558     projected_work_size = current_work_size * (info->total_operations -
4559                                                info->operations_completed - 1)
4560                                             / (info->operations_completed + 1);
4561
4562     info->original_status_cb(bs, info->offset_completed + operation_offset,
4563                              current_work_size + projected_work_size,
4564                              info->original_cb_opaque);
4565 }
4566
4567 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4568                                BlockDriverAmendStatusCB *status_cb,
4569                                void *cb_opaque,
4570                                Error **errp)
4571 {
4572     BDRVQcow2State *s = bs->opaque;
4573     int old_version = s->qcow_version, new_version = old_version;
4574     uint64_t new_size = 0;
4575     const char *backing_file = NULL, *backing_format = NULL;
4576     bool lazy_refcounts = s->use_lazy_refcounts;
4577     const char *compat = NULL;
4578     uint64_t cluster_size = s->cluster_size;
4579     bool encrypt;
4580     int encformat;
4581     int refcount_bits = s->refcount_bits;
4582     int ret;
4583     QemuOptDesc *desc = opts->list->desc;
4584     Qcow2AmendHelperCBInfo helper_cb_info;
4585
4586     while (desc && desc->name) {
4587         if (!qemu_opt_find(opts, desc->name)) {
4588             /* only change explicitly defined options */
4589             desc++;
4590             continue;
4591         }
4592
4593         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4594             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4595             if (!compat) {
4596                 /* preserve default */
4597             } else if (!strcmp(compat, "0.10")) {
4598                 new_version = 2;
4599             } else if (!strcmp(compat, "1.1")) {
4600                 new_version = 3;
4601             } else {
4602                 error_setg(errp, "Unknown compatibility level %s", compat);
4603                 return -EINVAL;
4604             }
4605         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4606             error_setg(errp, "Cannot change preallocation mode");
4607             return -ENOTSUP;
4608         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4609             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4610         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4611             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4612         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4613             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4614         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4615             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4616                                         !!s->crypto);
4617
4618             if (encrypt != !!s->crypto) {
4619                 error_setg(errp,
4620                            "Changing the encryption flag is not supported");
4621                 return -ENOTSUP;
4622             }
4623         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4624             encformat = qcow2_crypt_method_from_format(
4625                 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4626
4627             if (encformat != s->crypt_method_header) {
4628                 error_setg(errp,
4629                            "Changing the encryption format is not supported");
4630                 return -ENOTSUP;
4631             }
4632         } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4633             error_setg(errp,
4634                        "Changing the encryption parameters is not supported");
4635             return -ENOTSUP;
4636         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4637             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4638                                              cluster_size);
4639             if (cluster_size != s->cluster_size) {
4640                 error_setg(errp, "Changing the cluster size is not supported");
4641                 return -ENOTSUP;
4642             }
4643         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4644             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4645                                                lazy_refcounts);
4646         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4647             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4648                                                 refcount_bits);
4649
4650             if (refcount_bits <= 0 || refcount_bits > 64 ||
4651                 !is_power_of_2(refcount_bits))
4652             {
4653                 error_setg(errp, "Refcount width must be a power of two and "
4654                            "may not exceed 64 bits");
4655                 return -EINVAL;
4656             }
4657         } else {
4658             /* if this point is reached, this probably means a new option was
4659              * added without having it covered here */
4660             abort();
4661         }
4662
4663         desc++;
4664     }
4665
4666     helper_cb_info = (Qcow2AmendHelperCBInfo){
4667         .original_status_cb = status_cb,
4668         .original_cb_opaque = cb_opaque,
4669         .total_operations = (new_version < old_version)
4670                           + (s->refcount_bits != refcount_bits)
4671     };
4672
4673     /* Upgrade first (some features may require compat=1.1) */
4674     if (new_version > old_version) {
4675         s->qcow_version = new_version;
4676         ret = qcow2_update_header(bs);
4677         if (ret < 0) {
4678             s->qcow_version = old_version;
4679             error_setg_errno(errp, -ret, "Failed to update the image header");
4680             return ret;
4681         }
4682     }
4683
4684     if (s->refcount_bits != refcount_bits) {
4685         int refcount_order = ctz32(refcount_bits);
4686
4687         if (new_version < 3 && refcount_bits != 16) {
4688             error_setg(errp, "Refcount widths other than 16 bits require "
4689                        "compatibility level 1.1 or above (use compat=1.1 or "
4690                        "greater)");
4691             return -EINVAL;
4692         }
4693
4694         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4695         ret = qcow2_change_refcount_order(bs, refcount_order,
4696                                           &qcow2_amend_helper_cb,
4697                                           &helper_cb_info, errp);
4698         if (ret < 0) {
4699             return ret;
4700         }
4701     }
4702
4703     if (backing_file || backing_format) {
4704         ret = qcow2_change_backing_file(bs,
4705                     backing_file ?: s->image_backing_file,
4706                     backing_format ?: s->image_backing_format);
4707         if (ret < 0) {
4708             error_setg_errno(errp, -ret, "Failed to change the backing file");
4709             return ret;
4710         }
4711     }
4712
4713     if (s->use_lazy_refcounts != lazy_refcounts) {
4714         if (lazy_refcounts) {
4715             if (new_version < 3) {
4716                 error_setg(errp, "Lazy refcounts only supported with "
4717                            "compatibility level 1.1 and above (use compat=1.1 "
4718                            "or greater)");
4719                 return -EINVAL;
4720             }
4721             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4722             ret = qcow2_update_header(bs);
4723             if (ret < 0) {
4724                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4725                 error_setg_errno(errp, -ret, "Failed to update the image header");
4726                 return ret;
4727             }
4728             s->use_lazy_refcounts = true;
4729         } else {
4730             /* make image clean first */
4731             ret = qcow2_mark_clean(bs);
4732             if (ret < 0) {
4733                 error_setg_errno(errp, -ret, "Failed to make the image clean");
4734                 return ret;
4735             }
4736             /* now disallow lazy refcounts */
4737             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4738             ret = qcow2_update_header(bs);
4739             if (ret < 0) {
4740                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4741                 error_setg_errno(errp, -ret, "Failed to update the image header");
4742                 return ret;
4743             }
4744             s->use_lazy_refcounts = false;
4745         }
4746     }
4747
4748     if (new_size) {
4749         BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4750         ret = blk_insert_bs(blk, bs, errp);
4751         if (ret < 0) {
4752             blk_unref(blk);
4753             return ret;
4754         }
4755
4756         ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
4757         blk_unref(blk);
4758         if (ret < 0) {
4759             return ret;
4760         }
4761     }
4762
4763     /* Downgrade last (so unsupported features can be removed before) */
4764     if (new_version < old_version) {
4765         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4766         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4767                               &helper_cb_info, errp);
4768         if (ret < 0) {
4769             return ret;
4770         }
4771     }
4772
4773     return 0;
4774 }
4775
4776 /*
4777  * If offset or size are negative, respectively, they will not be included in
4778  * the BLOCK_IMAGE_CORRUPTED event emitted.
4779  * fatal will be ignored for read-only BDS; corruptions found there will always
4780  * be considered non-fatal.
4781  */
4782 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4783                              int64_t size, const char *message_format, ...)
4784 {
4785     BDRVQcow2State *s = bs->opaque;
4786     const char *node_name;
4787     char *message;
4788     va_list ap;
4789
4790     fatal = fatal && bdrv_is_writable(bs);
4791
4792     if (s->signaled_corruption &&
4793         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4794     {
4795         return;
4796     }
4797
4798     va_start(ap, message_format);
4799     message = g_strdup_vprintf(message_format, ap);
4800     va_end(ap);
4801
4802     if (fatal) {
4803         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4804                 "corruption events will be suppressed\n", message);
4805     } else {
4806         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4807                 "corruption events will be suppressed\n", message);
4808     }
4809
4810     node_name = bdrv_get_node_name(bs);
4811     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4812                                           *node_name != '\0', node_name,
4813                                           message, offset >= 0, offset,
4814                                           size >= 0, size,
4815                                           fatal);
4816     g_free(message);
4817
4818     if (fatal) {
4819         qcow2_mark_corrupt(bs);
4820         bs->drv = NULL; /* make BDS unusable */
4821     }
4822
4823     s->signaled_corruption = true;
4824 }
4825
4826 static QemuOptsList qcow2_create_opts = {
4827     .name = "qcow2-create-opts",
4828     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4829     .desc = {
4830         {
4831             .name = BLOCK_OPT_SIZE,
4832             .type = QEMU_OPT_SIZE,
4833             .help = "Virtual disk size"
4834         },
4835         {
4836             .name = BLOCK_OPT_COMPAT_LEVEL,
4837             .type = QEMU_OPT_STRING,
4838             .help = "Compatibility level (0.10 or 1.1)"
4839         },
4840         {
4841             .name = BLOCK_OPT_BACKING_FILE,
4842             .type = QEMU_OPT_STRING,
4843             .help = "File name of a base image"
4844         },
4845         {
4846             .name = BLOCK_OPT_BACKING_FMT,
4847             .type = QEMU_OPT_STRING,
4848             .help = "Image format of the base image"
4849         },
4850         {
4851             .name = BLOCK_OPT_ENCRYPT,
4852             .type = QEMU_OPT_BOOL,
4853             .help = "Encrypt the image with format 'aes'. (Deprecated "
4854                     "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4855         },
4856         {
4857             .name = BLOCK_OPT_ENCRYPT_FORMAT,
4858             .type = QEMU_OPT_STRING,
4859             .help = "Encrypt the image, format choices: 'aes', 'luks'",
4860         },
4861         BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4862             "ID of secret providing qcow AES key or LUKS passphrase"),
4863         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4864         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4865         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4866         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4867         BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4868         BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4869         {
4870             .name = BLOCK_OPT_CLUSTER_SIZE,
4871             .type = QEMU_OPT_SIZE,
4872             .help = "qcow2 cluster size",
4873             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4874         },
4875         {
4876             .name = BLOCK_OPT_PREALLOC,
4877             .type = QEMU_OPT_STRING,
4878             .help = "Preallocation mode (allowed values: off, metadata, "
4879                     "falloc, full)"
4880         },
4881         {
4882             .name = BLOCK_OPT_LAZY_REFCOUNTS,
4883             .type = QEMU_OPT_BOOL,
4884             .help = "Postpone refcount updates",
4885             .def_value_str = "off"
4886         },
4887         {
4888             .name = BLOCK_OPT_REFCOUNT_BITS,
4889             .type = QEMU_OPT_NUMBER,
4890             .help = "Width of a reference count entry in bits",
4891             .def_value_str = "16"
4892         },
4893         { /* end of list */ }
4894     }
4895 };
4896
4897 BlockDriver bdrv_qcow2 = {
4898     .format_name        = "qcow2",
4899     .instance_size      = sizeof(BDRVQcow2State),
4900     .bdrv_probe         = qcow2_probe,
4901     .bdrv_open          = qcow2_open,
4902     .bdrv_close         = qcow2_close,
4903     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
4904     .bdrv_reopen_commit   = qcow2_reopen_commit,
4905     .bdrv_reopen_abort    = qcow2_reopen_abort,
4906     .bdrv_join_options    = qcow2_join_options,
4907     .bdrv_child_perm      = bdrv_format_default_perms,
4908     .bdrv_co_create_opts  = qcow2_co_create_opts,
4909     .bdrv_co_create       = qcow2_co_create,
4910     .bdrv_has_zero_init = bdrv_has_zero_init_1,
4911     .bdrv_co_block_status = qcow2_co_block_status,
4912
4913     .bdrv_co_preadv         = qcow2_co_preadv,
4914     .bdrv_co_pwritev        = qcow2_co_pwritev,
4915     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
4916
4917     .bdrv_co_pwrite_zeroes  = qcow2_co_pwrite_zeroes,
4918     .bdrv_co_pdiscard       = qcow2_co_pdiscard,
4919     .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
4920     .bdrv_co_copy_range_to  = qcow2_co_copy_range_to,
4921     .bdrv_co_truncate       = qcow2_co_truncate,
4922     .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4923     .bdrv_make_empty        = qcow2_make_empty,
4924
4925     .bdrv_snapshot_create   = qcow2_snapshot_create,
4926     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
4927     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
4928     .bdrv_snapshot_list     = qcow2_snapshot_list,
4929     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4930     .bdrv_measure           = qcow2_measure,
4931     .bdrv_get_info          = qcow2_get_info,
4932     .bdrv_get_specific_info = qcow2_get_specific_info,
4933
4934     .bdrv_save_vmstate    = qcow2_save_vmstate,
4935     .bdrv_load_vmstate    = qcow2_load_vmstate,
4936
4937     .supports_backing           = true,
4938     .bdrv_change_backing_file   = qcow2_change_backing_file,
4939
4940     .bdrv_refresh_limits        = qcow2_refresh_limits,
4941     .bdrv_co_invalidate_cache   = qcow2_co_invalidate_cache,
4942     .bdrv_inactivate            = qcow2_inactivate,
4943
4944     .create_opts         = &qcow2_create_opts,
4945     .bdrv_co_check       = qcow2_co_check,
4946     .bdrv_amend_options  = qcow2_amend_options,
4947
4948     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
4949     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
4950
4951     .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4952     .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4953     .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4954 };
4955
4956 static void bdrv_qcow2_init(void)
4957 {
4958     bdrv_register(&bdrv_qcow2);
4959 }
4960
4961 block_init(bdrv_qcow2_init);
This page took 0.295407 seconds and 4 git commands to generate.