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