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