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