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