2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
25 #include "qemu/osdep.h"
26 #include "block/block_int.h"
27 #include "sysemu/block-backend.h"
28 #include "qemu/module.h"
30 #include "block/qcow2.h"
31 #include "qemu/error-report.h"
32 #include "qapi/error.h"
33 #include "qapi/qmp/qerror.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "qapi-event.h"
38 #include "qemu/option_int.h"
39 #include "qemu/cutils.h"
40 #include "qemu/bswap.h"
41 #include "qapi/opts-visitor.h"
42 #include "qapi-visit.h"
43 #include "block/crypto.h"
46 Differences with QCOW:
48 - Support for multiple incremental snapshots.
49 - Memory management by reference counts.
50 - Clusters which have a reference count of one have the bit
51 QCOW_OFLAG_COPIED to optimize write performance.
52 - Size of compressed clusters is stored in sectors to reduce bit usage
53 in the cluster offsets.
54 - Support for storing additional data (such as the VM state) in the
56 - If a backing store is used, the cluster size is not constrained
57 (could be backported to QCOW).
58 - L2 tables have always a size of one cluster.
65 } QEMU_PACKED QCowExtension
;
67 #define QCOW2_EXT_MAGIC_END 0
68 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
69 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
70 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
71 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
73 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
75 const QCowHeader
*cow_header
= (const void *)buf
;
77 if (buf_size
>= sizeof(QCowHeader
) &&
78 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
79 be32_to_cpu(cow_header
->version
) >= 2)
86 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
87 uint8_t *buf
, size_t buflen
,
88 void *opaque
, Error
**errp
)
90 BlockDriverState
*bs
= opaque
;
91 BDRVQcow2State
*s
= bs
->opaque
;
94 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
95 error_setg(errp
, "Request for data outside of extension header");
99 ret
= bdrv_pread(bs
->file
,
100 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
102 error_setg_errno(errp
, -ret
, "Could not read encryption header");
109 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
110 void *opaque
, Error
**errp
)
112 BlockDriverState
*bs
= opaque
;
113 BDRVQcow2State
*s
= bs
->opaque
;
117 ret
= qcow2_alloc_clusters(bs
, headerlen
);
119 error_setg_errno(errp
, -ret
,
120 "Cannot allocate cluster for LUKS header size %zu",
125 s
->crypto_header
.length
= headerlen
;
126 s
->crypto_header
.offset
= ret
;
128 /* Zero fill remaining space in cluster so it has predictable
129 * content in case of future spec changes */
130 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
131 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
) == 0);
132 ret
= bdrv_pwrite_zeroes(bs
->file
,
134 clusterlen
- headerlen
, 0);
136 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
144 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
145 const uint8_t *buf
, size_t buflen
,
146 void *opaque
, Error
**errp
)
148 BlockDriverState
*bs
= opaque
;
149 BDRVQcow2State
*s
= bs
->opaque
;
152 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
153 error_setg(errp
, "Request for data outside of extension header");
157 ret
= bdrv_pwrite(bs
->file
,
158 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
160 error_setg_errno(errp
, -ret
, "Could not read encryption header");
168 * read qcow2 extension and fill bs
169 * start reading from start_offset
170 * finish reading upon magic of value 0 or when end_offset reached
171 * unknown magic is skipped (future extension this version knows nothing about)
172 * return 0 upon success, non-0 otherwise
174 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
175 uint64_t end_offset
, void **p_feature_table
,
176 int flags
, bool *need_update_header
,
179 BDRVQcow2State
*s
= bs
->opaque
;
183 Qcow2BitmapHeaderExt bitmaps_ext
;
185 if (need_update_header
!= NULL
) {
186 *need_update_header
= false;
190 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
192 offset
= start_offset
;
193 while (offset
< end_offset
) {
197 if (offset
> s
->cluster_size
)
198 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
200 printf("attempting to read extended header in offset %lu\n", offset
);
203 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
205 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
206 "pread fail from offset %" PRIu64
, offset
);
209 be32_to_cpus(&ext
.magic
);
210 be32_to_cpus(&ext
.len
);
211 offset
+= sizeof(ext
);
213 printf("ext.magic = 0x%x\n", ext
.magic
);
215 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
216 error_setg(errp
, "Header extension too large");
221 case QCOW2_EXT_MAGIC_END
:
224 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
225 if (ext
.len
>= sizeof(bs
->backing_format
)) {
226 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
227 " too large (>=%zu)", ext
.len
,
228 sizeof(bs
->backing_format
));
231 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
233 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
234 "Could not read format name");
237 bs
->backing_format
[ext
.len
] = '\0';
238 s
->image_backing_format
= g_strdup(bs
->backing_format
);
240 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
244 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
245 if (p_feature_table
!= NULL
) {
246 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
247 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
249 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
250 "Could not read table");
254 *p_feature_table
= feature_table
;
258 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
259 unsigned int cflags
= 0;
260 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
261 error_setg(errp
, "CRYPTO header extension only "
262 "expected with LUKS encryption method");
265 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
266 error_setg(errp
, "CRYPTO header extension size %u, "
267 "but expected size %zu", ext
.len
,
268 sizeof(Qcow2CryptoHeaderExtension
));
272 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
274 error_setg_errno(errp
, -ret
,
275 "Unable to read CRYPTO header extension");
278 be64_to_cpus(&s
->crypto_header
.offset
);
279 be64_to_cpus(&s
->crypto_header
.length
);
281 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
282 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
283 "not a multiple of cluster size '%u'",
284 s
->crypto_header
.offset
, s
->cluster_size
);
288 if (flags
& BDRV_O_NO_IO
) {
289 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
291 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
292 qcow2_crypto_hdr_read_func
,
299 case QCOW2_EXT_MAGIC_BITMAPS
:
300 if (ext
.len
!= sizeof(bitmaps_ext
)) {
301 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
302 "Invalid extension length");
306 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
307 if (s
->qcow_version
< 3) {
308 /* Let's be a bit more specific */
309 warn_report("This qcow2 v2 image contains bitmaps, but "
310 "they may have been modified by a program "
311 "without persistent bitmap support; so now "
312 "they must all be considered inconsistent");
314 warn_report("a program lacking bitmap support "
315 "modified this file, so all bitmaps are now "
316 "considered inconsistent");
318 error_printf("Some clusters may be leaked, "
319 "run 'qemu-img check -r' on the image "
321 if (need_update_header
!= NULL
) {
322 /* Updating is needed to drop invalid bitmap extension. */
323 *need_update_header
= true;
328 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
330 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
331 "Could not read ext header");
335 if (bitmaps_ext
.reserved32
!= 0) {
336 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
337 "Reserved field is not zero");
341 be32_to_cpus(&bitmaps_ext
.nb_bitmaps
);
342 be64_to_cpus(&bitmaps_ext
.bitmap_directory_size
);
343 be64_to_cpus(&bitmaps_ext
.bitmap_directory_offset
);
345 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
347 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
348 "exceeding the QEMU supported maximum of %d",
349 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
353 if (bitmaps_ext
.nb_bitmaps
== 0) {
354 error_setg(errp
, "found bitmaps extension with zero bitmaps");
358 if (bitmaps_ext
.bitmap_directory_offset
& (s
->cluster_size
- 1)) {
359 error_setg(errp
, "bitmaps_ext: "
360 "invalid bitmap directory offset");
364 if (bitmaps_ext
.bitmap_directory_size
>
365 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
366 error_setg(errp
, "bitmaps_ext: "
367 "bitmap directory size (%" PRIu64
") exceeds "
368 "the maximum supported size (%d)",
369 bitmaps_ext
.bitmap_directory_size
,
370 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
374 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
375 s
->bitmap_directory_offset
=
376 bitmaps_ext
.bitmap_directory_offset
;
377 s
->bitmap_directory_size
=
378 bitmaps_ext
.bitmap_directory_size
;
381 printf("Qcow2: Got bitmaps extension: "
382 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
383 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
388 /* unknown magic - save it in case we need to rewrite the header */
389 /* If you add a new feature, make sure to also update the fast
390 * path of qcow2_make_empty() to deal with it. */
392 Qcow2UnknownHeaderExtension
*uext
;
394 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
395 uext
->magic
= ext
.magic
;
397 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
399 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
401 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
402 "Could not read data");
409 offset
+= ((ext
.len
+ 7) & ~7);
415 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
417 BDRVQcow2State
*s
= bs
->opaque
;
418 Qcow2UnknownHeaderExtension
*uext
, *next
;
420 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
421 QLIST_REMOVE(uext
, next
);
426 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
429 char *features
= g_strdup("");
432 while (table
&& table
->name
[0] != '\0') {
433 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
434 if (mask
& (1ULL << table
->bit
)) {
436 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
439 mask
&= ~(1ULL << table
->bit
);
447 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
448 old
, *old
? ", " : "", mask
);
452 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
457 * Sets the dirty bit and flushes afterwards if necessary.
459 * The incompatible_features bit is only set if the image file header was
460 * updated successfully. Therefore it is not required to check the return
461 * value of this function.
463 int qcow2_mark_dirty(BlockDriverState
*bs
)
465 BDRVQcow2State
*s
= bs
->opaque
;
469 assert(s
->qcow_version
>= 3);
471 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
472 return 0; /* already dirty */
475 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
476 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
481 ret
= bdrv_flush(bs
->file
->bs
);
486 /* Only treat image as dirty if the header was updated successfully */
487 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
492 * Clears the dirty bit and flushes before if necessary. Only call this
493 * function when there are no pending requests, it does not guard against
494 * concurrent requests dirtying the image.
496 static int qcow2_mark_clean(BlockDriverState
*bs
)
498 BDRVQcow2State
*s
= bs
->opaque
;
500 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
503 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
505 ret
= bdrv_flush(bs
);
510 return qcow2_update_header(bs
);
516 * Marks the image as corrupt.
518 int qcow2_mark_corrupt(BlockDriverState
*bs
)
520 BDRVQcow2State
*s
= bs
->opaque
;
522 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
523 return qcow2_update_header(bs
);
527 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
528 * before if necessary.
530 int qcow2_mark_consistent(BlockDriverState
*bs
)
532 BDRVQcow2State
*s
= bs
->opaque
;
534 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
535 int ret
= bdrv_flush(bs
);
540 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
541 return qcow2_update_header(bs
);
546 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
549 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
554 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
555 ret
= qcow2_mark_clean(bs
);
559 return qcow2_mark_consistent(bs
);
564 static int validate_table_offset(BlockDriverState
*bs
, uint64_t offset
,
565 uint64_t entries
, size_t entry_len
)
567 BDRVQcow2State
*s
= bs
->opaque
;
570 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
571 * because values will be passed to qemu functions taking int64_t. */
572 if (entries
> INT64_MAX
/ entry_len
) {
576 size
= entries
* entry_len
;
578 if (INT64_MAX
- size
< offset
) {
582 /* Tables must be cluster aligned */
583 if (offset_into_cluster(s
, offset
) != 0) {
590 static QemuOptsList qcow2_runtime_opts
= {
592 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
595 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
596 .type
= QEMU_OPT_BOOL
,
597 .help
= "Postpone refcount updates",
600 .name
= QCOW2_OPT_DISCARD_REQUEST
,
601 .type
= QEMU_OPT_BOOL
,
602 .help
= "Pass guest discard requests to the layer below",
605 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
606 .type
= QEMU_OPT_BOOL
,
607 .help
= "Generate discard requests when snapshot related space "
611 .name
= QCOW2_OPT_DISCARD_OTHER
,
612 .type
= QEMU_OPT_BOOL
,
613 .help
= "Generate discard requests when other clusters are freed",
616 .name
= QCOW2_OPT_OVERLAP
,
617 .type
= QEMU_OPT_STRING
,
618 .help
= "Selects which overlap checks to perform from a range of "
619 "templates (none, constant, cached, all)",
622 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
623 .type
= QEMU_OPT_STRING
,
624 .help
= "Selects which overlap checks to perform from a range of "
625 "templates (none, constant, cached, all)",
628 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
629 .type
= QEMU_OPT_BOOL
,
630 .help
= "Check for unintended writes into the main qcow2 header",
633 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
634 .type
= QEMU_OPT_BOOL
,
635 .help
= "Check for unintended writes into the active L1 table",
638 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
639 .type
= QEMU_OPT_BOOL
,
640 .help
= "Check for unintended writes into an active L2 table",
643 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
644 .type
= QEMU_OPT_BOOL
,
645 .help
= "Check for unintended writes into the refcount table",
648 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
649 .type
= QEMU_OPT_BOOL
,
650 .help
= "Check for unintended writes into a refcount block",
653 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
654 .type
= QEMU_OPT_BOOL
,
655 .help
= "Check for unintended writes into the snapshot table",
658 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
659 .type
= QEMU_OPT_BOOL
,
660 .help
= "Check for unintended writes into an inactive L1 table",
663 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
664 .type
= QEMU_OPT_BOOL
,
665 .help
= "Check for unintended writes into an inactive L2 table",
668 .name
= QCOW2_OPT_CACHE_SIZE
,
669 .type
= QEMU_OPT_SIZE
,
670 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
674 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
675 .type
= QEMU_OPT_SIZE
,
676 .help
= "Maximum L2 table cache size",
679 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
680 .type
= QEMU_OPT_SIZE
,
681 .help
= "Maximum refcount block cache size",
684 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
685 .type
= QEMU_OPT_NUMBER
,
686 .help
= "Clean unused cache entries after this time (in seconds)",
688 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
689 "ID of secret providing qcow2 AES key or LUKS passphrase"),
690 { /* end of list */ }
694 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
695 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
696 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
697 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
698 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
699 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
700 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
701 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
702 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
705 static void cache_clean_timer_cb(void *opaque
)
707 BlockDriverState
*bs
= opaque
;
708 BDRVQcow2State
*s
= bs
->opaque
;
709 qcow2_cache_clean_unused(s
->l2_table_cache
);
710 qcow2_cache_clean_unused(s
->refcount_block_cache
);
711 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
712 (int64_t) s
->cache_clean_interval
* 1000);
715 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
717 BDRVQcow2State
*s
= bs
->opaque
;
718 if (s
->cache_clean_interval
> 0) {
719 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
720 SCALE_MS
, cache_clean_timer_cb
,
722 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
723 (int64_t) s
->cache_clean_interval
* 1000);
727 static void cache_clean_timer_del(BlockDriverState
*bs
)
729 BDRVQcow2State
*s
= bs
->opaque
;
730 if (s
->cache_clean_timer
) {
731 timer_del(s
->cache_clean_timer
);
732 timer_free(s
->cache_clean_timer
);
733 s
->cache_clean_timer
= NULL
;
737 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
739 cache_clean_timer_del(bs
);
742 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
743 AioContext
*new_context
)
745 cache_clean_timer_init(bs
, new_context
);
748 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
749 uint64_t *l2_cache_size
,
750 uint64_t *refcount_cache_size
, Error
**errp
)
752 BDRVQcow2State
*s
= bs
->opaque
;
753 uint64_t combined_cache_size
;
754 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
756 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
757 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
758 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
760 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
761 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
762 *refcount_cache_size
= qemu_opt_get_size(opts
,
763 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
765 if (combined_cache_size_set
) {
766 if (l2_cache_size_set
&& refcount_cache_size_set
) {
767 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
768 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
771 } else if (*l2_cache_size
> combined_cache_size
) {
772 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
773 QCOW2_OPT_CACHE_SIZE
);
775 } else if (*refcount_cache_size
> combined_cache_size
) {
776 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
777 QCOW2_OPT_CACHE_SIZE
);
781 if (l2_cache_size_set
) {
782 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
783 } else if (refcount_cache_size_set
) {
784 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
786 *refcount_cache_size
= combined_cache_size
787 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO
+ 1);
788 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
791 if (!l2_cache_size_set
&& !refcount_cache_size_set
) {
792 *l2_cache_size
= MAX(DEFAULT_L2_CACHE_BYTE_SIZE
,
793 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
795 *refcount_cache_size
= *l2_cache_size
796 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
797 } else if (!l2_cache_size_set
) {
798 *l2_cache_size
= *refcount_cache_size
799 * DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
800 } else if (!refcount_cache_size_set
) {
801 *refcount_cache_size
= *l2_cache_size
802 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
807 typedef struct Qcow2ReopenState
{
808 Qcow2Cache
*l2_table_cache
;
809 Qcow2Cache
*refcount_block_cache
;
810 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
811 bool use_lazy_refcounts
;
813 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
814 uint64_t cache_clean_interval
;
815 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
818 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
820 QDict
*options
, int flags
,
823 BDRVQcow2State
*s
= bs
->opaque
;
824 QemuOpts
*opts
= NULL
;
825 const char *opt_overlap_check
, *opt_overlap_check_template
;
826 int overlap_check_template
= 0;
827 uint64_t l2_cache_size
, refcount_cache_size
;
829 const char *encryptfmt
;
830 QDict
*encryptopts
= NULL
;
831 Error
*local_err
= NULL
;
834 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
835 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
837 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
838 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
840 error_propagate(errp
, local_err
);
845 /* get L2 table/refcount block cache size from command line options */
846 read_cache_sizes(bs
, opts
, &l2_cache_size
, &refcount_cache_size
,
849 error_propagate(errp
, local_err
);
854 l2_cache_size
/= s
->cluster_size
;
855 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
856 l2_cache_size
= MIN_L2_CACHE_SIZE
;
858 if (l2_cache_size
> INT_MAX
) {
859 error_setg(errp
, "L2 cache size too big");
864 refcount_cache_size
/= s
->cluster_size
;
865 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
866 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
868 if (refcount_cache_size
> INT_MAX
) {
869 error_setg(errp
, "Refcount cache size too big");
874 /* alloc new L2 table/refcount block cache, flush old one */
875 if (s
->l2_table_cache
) {
876 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
878 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
883 if (s
->refcount_block_cache
) {
884 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
886 error_setg_errno(errp
, -ret
,
887 "Failed to flush the refcount block cache");
892 r
->l2_slice_size
= s
->cluster_size
/ sizeof(uint64_t);
893 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
);
894 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
);
895 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
896 error_setg(errp
, "Could not allocate metadata caches");
901 /* New interval for cache cleanup timer */
902 r
->cache_clean_interval
=
903 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
904 s
->cache_clean_interval
);
906 if (r
->cache_clean_interval
!= 0) {
907 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
908 " not supported on this host");
913 if (r
->cache_clean_interval
> UINT_MAX
) {
914 error_setg(errp
, "Cache clean interval too big");
919 /* lazy-refcounts; flush if going from enabled to disabled */
920 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
921 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
922 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
923 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
924 "qemu 1.1 compatibility level");
929 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
930 ret
= qcow2_mark_clean(bs
);
932 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
937 /* Overlap check options */
938 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
939 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
940 if (opt_overlap_check_template
&& opt_overlap_check
&&
941 strcmp(opt_overlap_check_template
, opt_overlap_check
))
943 error_setg(errp
, "Conflicting values for qcow2 options '"
944 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
945 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
949 if (!opt_overlap_check
) {
950 opt_overlap_check
= opt_overlap_check_template
?: "cached";
953 if (!strcmp(opt_overlap_check
, "none")) {
954 overlap_check_template
= 0;
955 } else if (!strcmp(opt_overlap_check
, "constant")) {
956 overlap_check_template
= QCOW2_OL_CONSTANT
;
957 } else if (!strcmp(opt_overlap_check
, "cached")) {
958 overlap_check_template
= QCOW2_OL_CACHED
;
959 } else if (!strcmp(opt_overlap_check
, "all")) {
960 overlap_check_template
= QCOW2_OL_ALL
;
962 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
963 "'overlap-check'. Allowed are any of the following: "
964 "none, constant, cached, all", opt_overlap_check
);
969 r
->overlap_check
= 0;
970 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
971 /* overlap-check defines a template bitmask, but every flag may be
972 * overwritten through the associated boolean option */
974 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
975 overlap_check_template
& (1 << i
)) << i
;
978 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
979 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
980 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
981 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
982 flags
& BDRV_O_UNMAP
);
983 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
984 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
985 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
986 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
988 switch (s
->crypt_method_header
) {
989 case QCOW_CRYPT_NONE
:
991 error_setg(errp
, "No encryption in image header, but options "
992 "specified format '%s'", encryptfmt
);
999 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1001 "Header reported 'aes' encryption format but "
1002 "options specify '%s'", encryptfmt
);
1006 qdict_del(encryptopts
, "format");
1007 r
->crypto_opts
= block_crypto_open_opts_init(
1008 Q_CRYPTO_BLOCK_FORMAT_QCOW
, encryptopts
, errp
);
1011 case QCOW_CRYPT_LUKS
:
1012 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1014 "Header reported 'luks' encryption format but "
1015 "options specify '%s'", encryptfmt
);
1019 qdict_del(encryptopts
, "format");
1020 r
->crypto_opts
= block_crypto_open_opts_init(
1021 Q_CRYPTO_BLOCK_FORMAT_LUKS
, encryptopts
, errp
);
1025 error_setg(errp
, "Unsupported encryption method %d",
1026 s
->crypt_method_header
);
1029 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1036 QDECREF(encryptopts
);
1037 qemu_opts_del(opts
);
1042 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1043 Qcow2ReopenState
*r
)
1045 BDRVQcow2State
*s
= bs
->opaque
;
1048 if (s
->l2_table_cache
) {
1049 qcow2_cache_destroy(s
->l2_table_cache
);
1051 if (s
->refcount_block_cache
) {
1052 qcow2_cache_destroy(s
->refcount_block_cache
);
1054 s
->l2_table_cache
= r
->l2_table_cache
;
1055 s
->refcount_block_cache
= r
->refcount_block_cache
;
1056 s
->l2_slice_size
= r
->l2_slice_size
;
1058 s
->overlap_check
= r
->overlap_check
;
1059 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1061 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1062 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1065 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1066 cache_clean_timer_del(bs
);
1067 s
->cache_clean_interval
= r
->cache_clean_interval
;
1068 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1071 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1072 s
->crypto_opts
= r
->crypto_opts
;
1075 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1076 Qcow2ReopenState
*r
)
1078 if (r
->l2_table_cache
) {
1079 qcow2_cache_destroy(r
->l2_table_cache
);
1081 if (r
->refcount_block_cache
) {
1082 qcow2_cache_destroy(r
->refcount_block_cache
);
1084 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1087 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1088 int flags
, Error
**errp
)
1090 Qcow2ReopenState r
= {};
1093 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1095 qcow2_update_options_commit(bs
, &r
);
1097 qcow2_update_options_abort(bs
, &r
);
1103 static int qcow2_do_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1106 BDRVQcow2State
*s
= bs
->opaque
;
1107 unsigned int len
, i
;
1110 Error
*local_err
= NULL
;
1112 uint64_t l1_vm_state_index
;
1113 bool update_header
= false;
1115 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1117 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1120 be32_to_cpus(&header
.magic
);
1121 be32_to_cpus(&header
.version
);
1122 be64_to_cpus(&header
.backing_file_offset
);
1123 be32_to_cpus(&header
.backing_file_size
);
1124 be64_to_cpus(&header
.size
);
1125 be32_to_cpus(&header
.cluster_bits
);
1126 be32_to_cpus(&header
.crypt_method
);
1127 be64_to_cpus(&header
.l1_table_offset
);
1128 be32_to_cpus(&header
.l1_size
);
1129 be64_to_cpus(&header
.refcount_table_offset
);
1130 be32_to_cpus(&header
.refcount_table_clusters
);
1131 be64_to_cpus(&header
.snapshots_offset
);
1132 be32_to_cpus(&header
.nb_snapshots
);
1134 if (header
.magic
!= QCOW_MAGIC
) {
1135 error_setg(errp
, "Image is not in qcow2 format");
1139 if (header
.version
< 2 || header
.version
> 3) {
1140 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1145 s
->qcow_version
= header
.version
;
1147 /* Initialise cluster size */
1148 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1149 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1150 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1151 header
.cluster_bits
);
1156 s
->cluster_bits
= header
.cluster_bits
;
1157 s
->cluster_size
= 1 << s
->cluster_bits
;
1158 s
->cluster_sectors
= 1 << (s
->cluster_bits
- BDRV_SECTOR_BITS
);
1160 /* Initialise version 3 header fields */
1161 if (header
.version
== 2) {
1162 header
.incompatible_features
= 0;
1163 header
.compatible_features
= 0;
1164 header
.autoclear_features
= 0;
1165 header
.refcount_order
= 4;
1166 header
.header_length
= 72;
1168 be64_to_cpus(&header
.incompatible_features
);
1169 be64_to_cpus(&header
.compatible_features
);
1170 be64_to_cpus(&header
.autoclear_features
);
1171 be32_to_cpus(&header
.refcount_order
);
1172 be32_to_cpus(&header
.header_length
);
1174 if (header
.header_length
< 104) {
1175 error_setg(errp
, "qcow2 header too short");
1181 if (header
.header_length
> s
->cluster_size
) {
1182 error_setg(errp
, "qcow2 header exceeds cluster size");
1187 if (header
.header_length
> sizeof(header
)) {
1188 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1189 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1190 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1191 s
->unknown_header_fields_size
);
1193 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1199 if (header
.backing_file_offset
> s
->cluster_size
) {
1200 error_setg(errp
, "Invalid backing file offset");
1205 if (header
.backing_file_offset
) {
1206 ext_end
= header
.backing_file_offset
;
1208 ext_end
= 1 << header
.cluster_bits
;
1211 /* Handle feature bits */
1212 s
->incompatible_features
= header
.incompatible_features
;
1213 s
->compatible_features
= header
.compatible_features
;
1214 s
->autoclear_features
= header
.autoclear_features
;
1216 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1217 void *feature_table
= NULL
;
1218 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1219 &feature_table
, flags
, NULL
, NULL
);
1220 report_unsupported_feature(errp
, feature_table
,
1221 s
->incompatible_features
&
1222 ~QCOW2_INCOMPAT_MASK
);
1224 g_free(feature_table
);
1228 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1229 /* Corrupt images may not be written to unless they are being repaired
1231 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1232 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1239 /* Check support for various header values */
1240 if (header
.refcount_order
> 6) {
1241 error_setg(errp
, "Reference count entry width too large; may not "
1246 s
->refcount_order
= header
.refcount_order
;
1247 s
->refcount_bits
= 1 << s
->refcount_order
;
1248 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1249 s
->refcount_max
+= s
->refcount_max
- 1;
1251 s
->crypt_method_header
= header
.crypt_method
;
1252 if (s
->crypt_method_header
) {
1253 if (bdrv_uses_whitelist() &&
1254 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1256 "Use of AES-CBC encrypted qcow2 images is no longer "
1257 "supported in system emulators");
1258 error_append_hint(errp
,
1259 "You can use 'qemu-img convert' to convert your "
1260 "image to an alternative supported format, such "
1261 "as unencrypted qcow2, or raw with the LUKS "
1262 "format instead.\n");
1267 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1268 s
->crypt_physical_offset
= false;
1270 /* Assuming LUKS and any future crypt methods we
1271 * add will all use physical offsets, due to the
1272 * fact that the alternative is insecure... */
1273 s
->crypt_physical_offset
= true;
1276 bs
->encrypted
= true;
1279 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
1280 s
->l2_size
= 1 << s
->l2_bits
;
1281 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1282 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1283 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1284 bs
->total_sectors
= header
.size
/ 512;
1285 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1286 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1287 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1289 s
->refcount_table_offset
= header
.refcount_table_offset
;
1290 s
->refcount_table_size
=
1291 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1293 if (header
.refcount_table_clusters
> qcow2_max_refcount_clusters(s
)) {
1294 error_setg(errp
, "Reference count table too large");
1299 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1300 error_setg(errp
, "Image does not contain a reference count table");
1305 ret
= validate_table_offset(bs
, s
->refcount_table_offset
,
1306 s
->refcount_table_size
, sizeof(uint64_t));
1308 error_setg(errp
, "Invalid reference count table offset");
1312 /* Snapshot table offset/length */
1313 if (header
.nb_snapshots
> QCOW_MAX_SNAPSHOTS
) {
1314 error_setg(errp
, "Too many snapshots");
1319 ret
= validate_table_offset(bs
, header
.snapshots_offset
,
1320 header
.nb_snapshots
,
1321 sizeof(QCowSnapshotHeader
));
1323 error_setg(errp
, "Invalid snapshot table offset");
1327 /* read the level 1 table */
1328 if (header
.l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
1329 error_setg(errp
, "Active L1 table too large");
1333 s
->l1_size
= header
.l1_size
;
1335 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1336 if (l1_vm_state_index
> INT_MAX
) {
1337 error_setg(errp
, "Image is too big");
1341 s
->l1_vm_state_index
= l1_vm_state_index
;
1343 /* the L1 table must contain at least enough entries to put
1344 header.size bytes */
1345 if (s
->l1_size
< s
->l1_vm_state_index
) {
1346 error_setg(errp
, "L1 table is too small");
1351 ret
= validate_table_offset(bs
, header
.l1_table_offset
,
1352 header
.l1_size
, sizeof(uint64_t));
1354 error_setg(errp
, "Invalid L1 table offset");
1357 s
->l1_table_offset
= header
.l1_table_offset
;
1360 if (s
->l1_size
> 0) {
1361 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1362 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
1363 if (s
->l1_table
== NULL
) {
1364 error_setg(errp
, "Could not allocate L1 table");
1368 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1369 s
->l1_size
* sizeof(uint64_t));
1371 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1374 for(i
= 0;i
< s
->l1_size
; i
++) {
1375 be64_to_cpus(&s
->l1_table
[i
]);
1379 /* Parse driver-specific options */
1380 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1385 s
->cluster_cache_offset
= -1;
1388 ret
= qcow2_refcount_init(bs
);
1390 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1394 QLIST_INIT(&s
->cluster_allocs
);
1395 QTAILQ_INIT(&s
->discards
);
1397 /* read qcow2 extensions */
1398 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1399 flags
, &update_header
, &local_err
)) {
1400 error_propagate(errp
, local_err
);
1405 /* qcow2_read_extension may have set up the crypto context
1406 * if the crypt method needs a header region, some methods
1407 * don't need header extensions, so must check here
1409 if (s
->crypt_method_header
&& !s
->crypto
) {
1410 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1411 unsigned int cflags
= 0;
1412 if (flags
& BDRV_O_NO_IO
) {
1413 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1415 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1416 NULL
, NULL
, cflags
, errp
);
1421 } else if (!(flags
& BDRV_O_NO_IO
)) {
1422 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1423 s
->crypt_method_header
);
1429 /* read the backing file name */
1430 if (header
.backing_file_offset
!= 0) {
1431 len
= header
.backing_file_size
;
1432 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1433 len
>= sizeof(bs
->backing_file
)) {
1434 error_setg(errp
, "Backing file name too long");
1438 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1439 bs
->backing_file
, len
);
1441 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1444 bs
->backing_file
[len
] = '\0';
1445 s
->image_backing_file
= g_strdup(bs
->backing_file
);
1448 /* Internal snapshots */
1449 s
->snapshots_offset
= header
.snapshots_offset
;
1450 s
->nb_snapshots
= header
.nb_snapshots
;
1452 ret
= qcow2_read_snapshots(bs
);
1454 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1458 /* Clear unknown autoclear feature bits */
1459 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1461 update_header
&& !bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
);
1462 if (update_header
) {
1463 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1466 if (qcow2_load_dirty_bitmaps(bs
, &local_err
)) {
1467 update_header
= false;
1469 if (local_err
!= NULL
) {
1470 error_propagate(errp
, local_err
);
1475 if (update_header
) {
1476 ret
= qcow2_update_header(bs
);
1478 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1483 /* Initialise locks */
1484 qemu_co_mutex_init(&s
->lock
);
1485 bs
->supported_zero_flags
= header
.version
>= 3 ? BDRV_REQ_MAY_UNMAP
: 0;
1487 /* Repair image if dirty */
1488 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1489 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1490 BdrvCheckResult result
= {0};
1492 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1493 if (ret
< 0 || result
.check_errors
) {
1497 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1504 BdrvCheckResult result
= {0};
1505 qcow2_check_refcounts(bs
, &result
, 0);
1511 g_free(s
->unknown_header_fields
);
1512 cleanup_unknown_header_ext(bs
);
1513 qcow2_free_snapshots(bs
);
1514 qcow2_refcount_close(bs
);
1515 qemu_vfree(s
->l1_table
);
1516 /* else pre-write overlap checks in cache_destroy may crash */
1518 cache_clean_timer_del(bs
);
1519 if (s
->l2_table_cache
) {
1520 qcow2_cache_destroy(s
->l2_table_cache
);
1522 if (s
->refcount_block_cache
) {
1523 qcow2_cache_destroy(s
->refcount_block_cache
);
1525 qcrypto_block_free(s
->crypto
);
1526 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1530 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1533 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1539 return qcow2_do_open(bs
, options
, flags
, errp
);
1542 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1544 BDRVQcow2State
*s
= bs
->opaque
;
1546 if (bs
->encrypted
) {
1547 /* Encryption works on a sector granularity */
1548 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1550 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1551 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1554 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1555 BlockReopenQueue
*queue
, Error
**errp
)
1557 Qcow2ReopenState
*r
;
1560 r
= g_new0(Qcow2ReopenState
, 1);
1563 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1564 state
->flags
, errp
);
1569 /* We need to write out any unwritten data if we reopen read-only. */
1570 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1571 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1576 ret
= bdrv_flush(state
->bs
);
1581 ret
= qcow2_mark_clean(state
->bs
);
1590 qcow2_update_options_abort(state
->bs
, r
);
1595 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1597 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1598 g_free(state
->opaque
);
1601 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1603 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1604 g_free(state
->opaque
);
1607 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1609 bool has_new_overlap_template
=
1610 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1611 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1612 bool has_new_total_cache_size
=
1613 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1614 bool has_all_cache_options
;
1616 /* New overlap template overrides all old overlap options */
1617 if (has_new_overlap_template
) {
1618 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1619 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1620 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1621 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1622 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1623 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1624 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1625 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1626 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1627 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1630 /* New total cache size overrides all old options */
1631 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1632 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1633 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1636 qdict_join(options
, old_options
, false);
1639 * If after merging all cache size options are set, an old total size is
1640 * overwritten. Do keep all options, however, if all three are new. The
1641 * resulting error message is what we want to happen.
1643 has_all_cache_options
=
1644 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1645 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1646 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1648 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1649 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1653 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
1654 int64_t sector_num
, int nb_sectors
, int *pnum
, BlockDriverState
**file
)
1656 BDRVQcow2State
*s
= bs
->opaque
;
1657 uint64_t cluster_offset
;
1658 int index_in_cluster
, ret
;
1662 bytes
= MIN(INT_MAX
, nb_sectors
* BDRV_SECTOR_SIZE
);
1663 qemu_co_mutex_lock(&s
->lock
);
1664 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< BDRV_SECTOR_BITS
, &bytes
,
1666 qemu_co_mutex_unlock(&s
->lock
);
1671 *pnum
= bytes
>> BDRV_SECTOR_BITS
;
1673 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1675 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1676 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
1677 *file
= bs
->file
->bs
;
1678 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
1680 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1681 status
|= BDRV_BLOCK_ZERO
;
1682 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1683 status
|= BDRV_BLOCK_DATA
;
1688 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1689 uint64_t bytes
, QEMUIOVector
*qiov
,
1692 BDRVQcow2State
*s
= bs
->opaque
;
1693 int offset_in_cluster
;
1695 unsigned int cur_bytes
; /* number of bytes in current iteration */
1696 uint64_t cluster_offset
= 0;
1697 uint64_t bytes_done
= 0;
1698 QEMUIOVector hd_qiov
;
1699 uint8_t *cluster_data
= NULL
;
1701 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1703 qemu_co_mutex_lock(&s
->lock
);
1705 while (bytes
!= 0) {
1707 /* prepare next request */
1708 cur_bytes
= MIN(bytes
, INT_MAX
);
1710 cur_bytes
= MIN(cur_bytes
,
1711 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1714 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1719 offset_in_cluster
= offset_into_cluster(s
, offset
);
1721 qemu_iovec_reset(&hd_qiov
);
1722 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1725 case QCOW2_CLUSTER_UNALLOCATED
:
1728 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1729 qemu_co_mutex_unlock(&s
->lock
);
1730 ret
= bdrv_co_preadv(bs
->backing
, offset
, cur_bytes
,
1732 qemu_co_mutex_lock(&s
->lock
);
1737 /* Note: in this case, no need to wait */
1738 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1742 case QCOW2_CLUSTER_ZERO_PLAIN
:
1743 case QCOW2_CLUSTER_ZERO_ALLOC
:
1744 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1747 case QCOW2_CLUSTER_COMPRESSED
:
1748 /* add AIO support for compressed blocks ? */
1749 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1754 qemu_iovec_from_buf(&hd_qiov
, 0,
1755 s
->cluster_cache
+ offset_in_cluster
,
1759 case QCOW2_CLUSTER_NORMAL
:
1760 if ((cluster_offset
& 511) != 0) {
1765 if (bs
->encrypted
) {
1769 * For encrypted images, read everything into a temporary
1770 * contiguous buffer on which the AES functions can work.
1772 if (!cluster_data
) {
1774 qemu_try_blockalign(bs
->file
->bs
,
1775 QCOW_MAX_CRYPT_CLUSTERS
1777 if (cluster_data
== NULL
) {
1783 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1784 qemu_iovec_reset(&hd_qiov
);
1785 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1788 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1789 qemu_co_mutex_unlock(&s
->lock
);
1790 ret
= bdrv_co_preadv(bs
->file
,
1791 cluster_offset
+ offset_in_cluster
,
1792 cur_bytes
, &hd_qiov
, 0);
1793 qemu_co_mutex_lock(&s
->lock
);
1797 if (bs
->encrypted
) {
1799 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1800 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1801 if (qcrypto_block_decrypt(s
->crypto
,
1802 (s
->crypt_physical_offset
?
1803 cluster_offset
+ offset_in_cluster
:
1811 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1816 g_assert_not_reached();
1822 offset
+= cur_bytes
;
1823 bytes_done
+= cur_bytes
;
1828 qemu_co_mutex_unlock(&s
->lock
);
1830 qemu_iovec_destroy(&hd_qiov
);
1831 qemu_vfree(cluster_data
);
1836 /* Check if it's possible to merge a write request with the writing of
1837 * the data from the COW regions */
1838 static bool merge_cow(uint64_t offset
, unsigned bytes
,
1839 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
1843 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
1844 /* If both COW regions are empty then there's nothing to merge */
1845 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
1849 /* The data (middle) region must be immediately after the
1851 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
1855 /* The end region must be immediately after the data (middle)
1857 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
1861 /* Make sure that adding both COW regions to the QEMUIOVector
1862 * does not exceed IOV_MAX */
1863 if (hd_qiov
->niov
> IOV_MAX
- 2) {
1867 m
->data_qiov
= hd_qiov
;
1874 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1875 uint64_t bytes
, QEMUIOVector
*qiov
,
1878 BDRVQcow2State
*s
= bs
->opaque
;
1879 int offset_in_cluster
;
1881 unsigned int cur_bytes
; /* number of sectors in current iteration */
1882 uint64_t cluster_offset
;
1883 QEMUIOVector hd_qiov
;
1884 uint64_t bytes_done
= 0;
1885 uint8_t *cluster_data
= NULL
;
1886 QCowL2Meta
*l2meta
= NULL
;
1888 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
1890 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1892 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1894 qemu_co_mutex_lock(&s
->lock
);
1896 while (bytes
!= 0) {
1900 trace_qcow2_writev_start_part(qemu_coroutine_self());
1901 offset_in_cluster
= offset_into_cluster(s
, offset
);
1902 cur_bytes
= MIN(bytes
, INT_MAX
);
1903 if (bs
->encrypted
) {
1904 cur_bytes
= MIN(cur_bytes
,
1905 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
1906 - offset_in_cluster
);
1909 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
1910 &cluster_offset
, &l2meta
);
1915 assert((cluster_offset
& 511) == 0);
1917 qemu_iovec_reset(&hd_qiov
);
1918 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1920 if (bs
->encrypted
) {
1922 if (!cluster_data
) {
1923 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
1924 QCOW_MAX_CRYPT_CLUSTERS
1926 if (cluster_data
== NULL
) {
1932 assert(hd_qiov
.size
<=
1933 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1934 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
1936 if (qcrypto_block_encrypt(s
->crypto
,
1937 (s
->crypt_physical_offset
?
1938 cluster_offset
+ offset_in_cluster
:
1941 cur_bytes
, NULL
) < 0) {
1946 qemu_iovec_reset(&hd_qiov
);
1947 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1950 ret
= qcow2_pre_write_overlap_check(bs
, 0,
1951 cluster_offset
+ offset_in_cluster
, cur_bytes
);
1956 /* If we need to do COW, check if it's possible to merge the
1957 * writing of the guest data together with that of the COW regions.
1958 * If it's not possible (or not necessary) then write the
1959 * guest data now. */
1960 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
1961 qemu_co_mutex_unlock(&s
->lock
);
1962 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
1963 trace_qcow2_writev_data(qemu_coroutine_self(),
1964 cluster_offset
+ offset_in_cluster
);
1965 ret
= bdrv_co_pwritev(bs
->file
,
1966 cluster_offset
+ offset_in_cluster
,
1967 cur_bytes
, &hd_qiov
, 0);
1968 qemu_co_mutex_lock(&s
->lock
);
1974 while (l2meta
!= NULL
) {
1977 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1982 /* Take the request off the list of running requests */
1983 if (l2meta
->nb_clusters
!= 0) {
1984 QLIST_REMOVE(l2meta
, next_in_flight
);
1987 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1989 next
= l2meta
->next
;
1995 offset
+= cur_bytes
;
1996 bytes_done
+= cur_bytes
;
1997 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2002 while (l2meta
!= NULL
) {
2005 if (l2meta
->nb_clusters
!= 0) {
2006 QLIST_REMOVE(l2meta
, next_in_flight
);
2008 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2010 next
= l2meta
->next
;
2015 qemu_co_mutex_unlock(&s
->lock
);
2017 qemu_iovec_destroy(&hd_qiov
);
2018 qemu_vfree(cluster_data
);
2019 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2024 static int qcow2_inactivate(BlockDriverState
*bs
)
2026 BDRVQcow2State
*s
= bs
->opaque
;
2027 int ret
, result
= 0;
2028 Error
*local_err
= NULL
;
2030 qcow2_store_persistent_dirty_bitmaps(bs
, &local_err
);
2031 if (local_err
!= NULL
) {
2033 error_report_err(local_err
);
2034 error_report("Persistent bitmaps are lost for node '%s'",
2035 bdrv_get_device_or_node_name(bs
));
2038 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2041 error_report("Failed to flush the L2 table cache: %s",
2045 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2048 error_report("Failed to flush the refcount block cache: %s",
2053 qcow2_mark_clean(bs
);
2059 static void qcow2_close(BlockDriverState
*bs
)
2061 BDRVQcow2State
*s
= bs
->opaque
;
2062 qemu_vfree(s
->l1_table
);
2063 /* else pre-write overlap checks in cache_destroy may crash */
2066 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2067 qcow2_inactivate(bs
);
2070 cache_clean_timer_del(bs
);
2071 qcow2_cache_destroy(s
->l2_table_cache
);
2072 qcow2_cache_destroy(s
->refcount_block_cache
);
2074 qcrypto_block_free(s
->crypto
);
2077 g_free(s
->unknown_header_fields
);
2078 cleanup_unknown_header_ext(bs
);
2080 g_free(s
->image_backing_file
);
2081 g_free(s
->image_backing_format
);
2083 g_free(s
->cluster_cache
);
2084 qemu_vfree(s
->cluster_data
);
2085 qcow2_refcount_close(bs
);
2086 qcow2_free_snapshots(bs
);
2089 static void qcow2_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
2091 BDRVQcow2State
*s
= bs
->opaque
;
2092 int flags
= s
->flags
;
2093 QCryptoBlock
*crypto
= NULL
;
2095 Error
*local_err
= NULL
;
2099 * Backing files are read-only which makes all of their metadata immutable,
2100 * that means we don't have to worry about reopening them here.
2108 memset(s
, 0, sizeof(BDRVQcow2State
));
2109 options
= qdict_clone_shallow(bs
->options
);
2111 flags
&= ~BDRV_O_INACTIVE
;
2112 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2115 error_propagate(errp
, local_err
);
2116 error_prepend(errp
, "Could not reopen qcow2 layer: ");
2119 } else if (ret
< 0) {
2120 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2128 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2129 size_t len
, size_t buflen
)
2131 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2132 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2134 if (buflen
< ext_len
) {
2138 *ext_backing_fmt
= (QCowExtension
) {
2139 .magic
= cpu_to_be32(magic
),
2140 .len
= cpu_to_be32(len
),
2144 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2151 * Updates the qcow2 header, including the variable length parts of it, i.e.
2152 * the backing file name and all extensions. qcow2 was not designed to allow
2153 * such changes, so if we run out of space (we can only use the first cluster)
2154 * this function may fail.
2156 * Returns 0 on success, -errno in error cases.
2158 int qcow2_update_header(BlockDriverState
*bs
)
2160 BDRVQcow2State
*s
= bs
->opaque
;
2163 size_t buflen
= s
->cluster_size
;
2165 uint64_t total_size
;
2166 uint32_t refcount_table_clusters
;
2167 size_t header_length
;
2168 Qcow2UnknownHeaderExtension
*uext
;
2170 buf
= qemu_blockalign(bs
, buflen
);
2172 /* Header structure */
2173 header
= (QCowHeader
*) buf
;
2175 if (buflen
< sizeof(*header
)) {
2180 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2181 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2182 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2184 *header
= (QCowHeader
) {
2185 /* Version 2 fields */
2186 .magic
= cpu_to_be32(QCOW_MAGIC
),
2187 .version
= cpu_to_be32(s
->qcow_version
),
2188 .backing_file_offset
= 0,
2189 .backing_file_size
= 0,
2190 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2191 .size
= cpu_to_be64(total_size
),
2192 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2193 .l1_size
= cpu_to_be32(s
->l1_size
),
2194 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2195 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2196 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2197 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2198 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2200 /* Version 3 fields */
2201 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2202 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2203 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2204 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2205 .header_length
= cpu_to_be32(header_length
),
2208 /* For older versions, write a shorter header */
2209 switch (s
->qcow_version
) {
2211 ret
= offsetof(QCowHeader
, incompatible_features
);
2214 ret
= sizeof(*header
);
2223 memset(buf
, 0, buflen
);
2225 /* Preserve any unknown field in the header */
2226 if (s
->unknown_header_fields_size
) {
2227 if (buflen
< s
->unknown_header_fields_size
) {
2232 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2233 buf
+= s
->unknown_header_fields_size
;
2234 buflen
-= s
->unknown_header_fields_size
;
2237 /* Backing file format header extension */
2238 if (s
->image_backing_format
) {
2239 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2240 s
->image_backing_format
,
2241 strlen(s
->image_backing_format
),
2251 /* Full disk encryption header pointer extension */
2252 if (s
->crypto_header
.offset
!= 0) {
2253 cpu_to_be64s(&s
->crypto_header
.offset
);
2254 cpu_to_be64s(&s
->crypto_header
.length
);
2255 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2256 &s
->crypto_header
, sizeof(s
->crypto_header
),
2258 be64_to_cpus(&s
->crypto_header
.offset
);
2259 be64_to_cpus(&s
->crypto_header
.length
);
2268 if (s
->qcow_version
>= 3) {
2269 Qcow2Feature features
[] = {
2271 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2272 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2273 .name
= "dirty bit",
2276 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2277 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2278 .name
= "corrupt bit",
2281 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2282 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2283 .name
= "lazy refcounts",
2287 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2288 features
, sizeof(features
), buflen
);
2296 /* Bitmap extension */
2297 if (s
->nb_bitmaps
> 0) {
2298 Qcow2BitmapHeaderExt bitmaps_header
= {
2299 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2300 .bitmap_directory_size
=
2301 cpu_to_be64(s
->bitmap_directory_size
),
2302 .bitmap_directory_offset
=
2303 cpu_to_be64(s
->bitmap_directory_offset
)
2305 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2306 &bitmaps_header
, sizeof(bitmaps_header
),
2315 /* Keep unknown header extensions */
2316 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2317 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2326 /* End of header extensions */
2327 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2335 /* Backing file name */
2336 if (s
->image_backing_file
) {
2337 size_t backing_file_len
= strlen(s
->image_backing_file
);
2339 if (buflen
< backing_file_len
) {
2344 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2345 strncpy(buf
, s
->image_backing_file
, buflen
);
2347 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2348 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2351 /* Write the new header */
2352 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2363 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2364 const char *backing_file
, const char *backing_fmt
)
2366 BDRVQcow2State
*s
= bs
->opaque
;
2368 if (backing_file
&& strlen(backing_file
) > 1023) {
2372 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2373 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2375 g_free(s
->image_backing_file
);
2376 g_free(s
->image_backing_format
);
2378 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2379 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2381 return qcow2_update_header(bs
);
2384 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2386 if (g_str_equal(encryptfmt
, "luks")) {
2387 return QCOW_CRYPT_LUKS
;
2388 } else if (g_str_equal(encryptfmt
, "aes")) {
2389 return QCOW_CRYPT_AES
;
2395 static int qcow2_set_up_encryption(BlockDriverState
*bs
, const char *encryptfmt
,
2396 QemuOpts
*opts
, Error
**errp
)
2398 BDRVQcow2State
*s
= bs
->opaque
;
2399 QCryptoBlockCreateOptions
*cryptoopts
= NULL
;
2400 QCryptoBlock
*crypto
= NULL
;
2402 QDict
*options
, *encryptopts
;
2405 options
= qemu_opts_to_qdict(opts
, NULL
);
2406 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
2409 fmt
= qcow2_crypt_method_from_format(encryptfmt
);
2412 case QCOW_CRYPT_LUKS
:
2413 cryptoopts
= block_crypto_create_opts_init(
2414 Q_CRYPTO_BLOCK_FORMAT_LUKS
, encryptopts
, errp
);
2416 case QCOW_CRYPT_AES
:
2417 cryptoopts
= block_crypto_create_opts_init(
2418 Q_CRYPTO_BLOCK_FORMAT_QCOW
, encryptopts
, errp
);
2421 error_setg(errp
, "Unknown encryption format '%s'", encryptfmt
);
2428 s
->crypt_method_header
= fmt
;
2430 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2431 qcow2_crypto_hdr_init_func
,
2432 qcow2_crypto_hdr_write_func
,
2439 ret
= qcow2_update_header(bs
);
2441 error_setg_errno(errp
, -ret
, "Could not write encryption header");
2446 QDECREF(encryptopts
);
2447 qcrypto_block_free(crypto
);
2448 qapi_free_QCryptoBlockCreateOptions(cryptoopts
);
2453 typedef struct PreallocCo
{
2454 BlockDriverState
*bs
;
2456 uint64_t new_length
;
2462 * Preallocates metadata structures for data clusters between @offset (in the
2463 * guest disk) and @new_length (which is thus generally the new guest disk
2466 * Returns: 0 on success, -errno on failure.
2468 static void coroutine_fn
preallocate_co(void *opaque
)
2470 PreallocCo
*params
= opaque
;
2471 BlockDriverState
*bs
= params
->bs
;
2472 uint64_t offset
= params
->offset
;
2473 uint64_t new_length
= params
->new_length
;
2474 BDRVQcow2State
*s
= bs
->opaque
;
2476 uint64_t host_offset
= 0;
2477 unsigned int cur_bytes
;
2481 qemu_co_mutex_lock(&s
->lock
);
2483 assert(offset
<= new_length
);
2484 bytes
= new_length
- offset
;
2487 cur_bytes
= MIN(bytes
, INT_MAX
);
2488 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2489 &host_offset
, &meta
);
2495 QCowL2Meta
*next
= meta
->next
;
2497 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2499 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2500 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2504 /* There are no dependent requests, but we need to remove our
2505 * request from the list of in-flight requests */
2506 QLIST_REMOVE(meta
, next_in_flight
);
2512 /* TODO Preallocate data if requested */
2515 offset
+= cur_bytes
;
2519 * It is expected that the image file is large enough to actually contain
2520 * all of the allocated clusters (otherwise we get failing reads after
2521 * EOF). Extend the image to the last allocated sector.
2523 if (host_offset
!= 0) {
2525 ret
= bdrv_pwrite(bs
->file
, (host_offset
+ cur_bytes
) - 1,
2535 qemu_co_mutex_unlock(&s
->lock
);
2539 static int preallocate(BlockDriverState
*bs
,
2540 uint64_t offset
, uint64_t new_length
)
2542 PreallocCo params
= {
2545 .new_length
= new_length
,
2546 .ret
= -EINPROGRESS
,
2549 if (qemu_in_coroutine()) {
2550 preallocate_co(¶ms
);
2552 Coroutine
*co
= qemu_coroutine_create(preallocate_co
, ¶ms
);
2553 bdrv_coroutine_enter(bs
, co
);
2554 BDRV_POLL_WHILE(bs
, params
.ret
== -EINPROGRESS
);
2559 /* qcow2_refcount_metadata_size:
2560 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2561 * @cluster_size: size of a cluster, in bytes
2562 * @refcount_order: refcount bits power-of-2 exponent
2563 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2566 * Returns: Number of bytes required for refcount blocks and table metadata.
2568 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
2569 int refcount_order
, bool generous_increase
,
2570 uint64_t *refblock_count
)
2573 * Every host cluster is reference-counted, including metadata (even
2574 * refcount metadata is recursively included).
2576 * An accurate formula for the size of refcount metadata size is difficult
2577 * to derive. An easier method of calculation is finding the fixed point
2578 * where no further refcount blocks or table clusters are required to
2579 * reference count every cluster.
2581 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
2582 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
2583 int64_t table
= 0; /* number of refcount table clusters */
2584 int64_t blocks
= 0; /* number of refcount block clusters */
2590 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
2591 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
2592 n
= clusters
+ blocks
+ table
;
2594 if (n
== last
&& generous_increase
) {
2595 clusters
+= DIV_ROUND_UP(table
, 2);
2596 n
= 0; /* force another loop */
2597 generous_increase
= false;
2599 } while (n
!= last
);
2601 if (refblock_count
) {
2602 *refblock_count
= blocks
;
2605 return (blocks
+ table
) * cluster_size
;
2609 * qcow2_calc_prealloc_size:
2610 * @total_size: virtual disk size in bytes
2611 * @cluster_size: cluster size in bytes
2612 * @refcount_order: refcount bits power-of-2 exponent
2614 * Returns: Total number of bytes required for the fully allocated image
2615 * (including metadata).
2617 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
2618 size_t cluster_size
,
2621 int64_t meta_size
= 0;
2622 uint64_t nl1e
, nl2e
;
2623 int64_t aligned_total_size
= align_offset(total_size
, cluster_size
);
2625 /* header: 1 cluster */
2626 meta_size
+= cluster_size
;
2628 /* total size of L2 tables */
2629 nl2e
= aligned_total_size
/ cluster_size
;
2630 nl2e
= align_offset(nl2e
, cluster_size
/ sizeof(uint64_t));
2631 meta_size
+= nl2e
* sizeof(uint64_t);
2633 /* total size of L1 tables */
2634 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2635 nl1e
= align_offset(nl1e
, cluster_size
/ sizeof(uint64_t));
2636 meta_size
+= nl1e
* sizeof(uint64_t);
2638 /* total size of refcount table and blocks */
2639 meta_size
+= qcow2_refcount_metadata_size(
2640 (meta_size
+ aligned_total_size
) / cluster_size
,
2641 cluster_size
, refcount_order
, false, NULL
);
2643 return meta_size
+ aligned_total_size
;
2646 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
2648 size_t cluster_size
;
2651 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2652 DEFAULT_CLUSTER_SIZE
);
2653 cluster_bits
= ctz32(cluster_size
);
2654 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2655 (1 << cluster_bits
) != cluster_size
)
2657 error_setg(errp
, "Cluster size must be a power of two between %d and "
2658 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2661 return cluster_size
;
2664 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
2669 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2671 ret
= 3; /* default */
2672 } else if (!strcmp(buf
, "0.10")) {
2674 } else if (!strcmp(buf
, "1.1")) {
2677 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2684 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
2687 uint64_t refcount_bits
;
2689 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
2690 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2691 error_setg(errp
, "Refcount width must be a power of two and may not "
2696 if (version
< 3 && refcount_bits
!= 16) {
2697 error_setg(errp
, "Different refcount widths than 16 bits require "
2698 "compatibility level 1.1 or above (use compat=1.1 or "
2703 return refcount_bits
;
2706 static int qcow2_create2(const char *filename
, int64_t total_size
,
2707 const char *backing_file
, const char *backing_format
,
2708 int flags
, size_t cluster_size
, PreallocMode prealloc
,
2709 QemuOpts
*opts
, int version
, int refcount_order
,
2710 const char *encryptfmt
, Error
**errp
)
2715 * Open the image file and write a minimal qcow2 header.
2717 * We keep things simple and start with a zero-sized image. We also
2718 * do without refcount blocks or a L1 table for now. We'll fix the
2719 * inconsistency later.
2721 * We do need a refcount table because growing the refcount table means
2722 * allocating two new refcount blocks - the seconds of which would be at
2723 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2724 * size for any qcow2 image.
2728 uint64_t* refcount_table
;
2729 Error
*local_err
= NULL
;
2732 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
2733 int64_t prealloc_size
=
2734 qcow2_calc_prealloc_size(total_size
, cluster_size
, refcount_order
);
2735 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, prealloc_size
, &error_abort
);
2736 qemu_opt_set(opts
, BLOCK_OPT_PREALLOC
, PreallocMode_str(prealloc
),
2740 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2742 error_propagate(errp
, local_err
);
2746 blk
= blk_new_open(filename
, NULL
, NULL
,
2747 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2750 error_propagate(errp
, local_err
);
2754 blk_set_allow_write_beyond_eof(blk
, true);
2756 /* Write the header */
2757 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2758 header
= g_malloc0(cluster_size
);
2759 *header
= (QCowHeader
) {
2760 .magic
= cpu_to_be32(QCOW_MAGIC
),
2761 .version
= cpu_to_be32(version
),
2762 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
2763 .size
= cpu_to_be64(0),
2764 .l1_table_offset
= cpu_to_be64(0),
2765 .l1_size
= cpu_to_be32(0),
2766 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2767 .refcount_table_clusters
= cpu_to_be32(1),
2768 .refcount_order
= cpu_to_be32(refcount_order
),
2769 .header_length
= cpu_to_be32(sizeof(*header
)),
2772 /* We'll update this to correct value later */
2773 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2775 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
2776 header
->compatible_features
|=
2777 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2780 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2783 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2787 /* Write a refcount table with one refcount block */
2788 refcount_table
= g_malloc0(2 * cluster_size
);
2789 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2790 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2791 g_free(refcount_table
);
2794 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2802 * And now open the image and make it consistent first (i.e. increase the
2803 * refcount of the cluster that is occupied by the header and the refcount
2806 options
= qdict_new();
2807 qdict_put_str(options
, "driver", "qcow2");
2808 blk
= blk_new_open(filename
, NULL
, options
,
2809 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
2812 error_propagate(errp
, local_err
);
2817 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2819 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2820 "header and refcount table");
2823 } else if (ret
!= 0) {
2824 error_report("Huh, first cluster in empty image is already in use?");
2828 /* Create a full header (including things like feature table) */
2829 ret
= qcow2_update_header(blk_bs(blk
));
2831 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
2835 /* Okay, now that we have a valid image, let's give it the right size */
2836 ret
= blk_truncate(blk
, total_size
, PREALLOC_MODE_OFF
, errp
);
2838 error_prepend(errp
, "Could not resize image: ");
2842 /* Want a backing file? There you go.*/
2844 ret
= bdrv_change_backing_file(blk_bs(blk
), backing_file
, backing_format
);
2846 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
2847 "with format '%s'", backing_file
, backing_format
);
2852 /* Want encryption? There you go. */
2854 ret
= qcow2_set_up_encryption(blk_bs(blk
), encryptfmt
, opts
, errp
);
2860 /* And if we're supposed to preallocate metadata, do that now */
2861 if (prealloc
!= PREALLOC_MODE_OFF
) {
2862 ret
= preallocate(blk_bs(blk
), 0, total_size
);
2864 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
2872 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
2873 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
2874 * have to setup decryption context. We're not doing any I/O on the top
2875 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
2878 options
= qdict_new();
2879 qdict_put_str(options
, "driver", "qcow2");
2880 blk
= blk_new_open(filename
, NULL
, options
,
2881 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
2884 error_propagate(errp
, local_err
);
2897 static int qcow2_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
2899 char *backing_file
= NULL
;
2900 char *backing_fmt
= NULL
;
2904 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
2905 PreallocMode prealloc
;
2907 uint64_t refcount_bits
;
2909 char *encryptfmt
= NULL
;
2910 Error
*local_err
= NULL
;
2913 /* Read out options */
2914 size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2916 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
2917 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
2918 encryptfmt
= qemu_opt_get_del(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2920 if (qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT
)) {
2921 error_setg(errp
, "Options " BLOCK_OPT_ENCRYPT
" and "
2922 BLOCK_OPT_ENCRYPT_FORMAT
" are mutually exclusive");
2926 } else if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ENCRYPT
, false)) {
2927 encryptfmt
= g_strdup("aes");
2929 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
2931 error_propagate(errp
, local_err
);
2935 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2936 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
2937 PREALLOC_MODE_OFF
, &local_err
);
2939 error_propagate(errp
, local_err
);
2944 version
= qcow2_opt_get_version_del(opts
, &local_err
);
2946 error_propagate(errp
, local_err
);
2951 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_LAZY_REFCOUNTS
, false)) {
2952 flags
|= BLOCK_FLAG_LAZY_REFCOUNTS
;
2955 if (backing_file
&& prealloc
!= PREALLOC_MODE_OFF
) {
2956 error_setg(errp
, "Backing file and preallocation cannot be used at "
2962 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
2963 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2964 "level 1.1 and above (use compat=1.1 or greater)");
2969 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
2971 error_propagate(errp
, local_err
);
2976 refcount_order
= ctz32(refcount_bits
);
2978 ret
= qcow2_create2(filename
, size
, backing_file
, backing_fmt
, flags
,
2979 cluster_size
, prealloc
, opts
, version
, refcount_order
,
2980 encryptfmt
, &local_err
);
2981 error_propagate(errp
, local_err
);
2984 g_free(backing_file
);
2985 g_free(backing_fmt
);
2992 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
2997 /* Clamp to image length, before checking status of underlying sectors */
2998 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
2999 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3005 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3006 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3009 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3010 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3013 BDRVQcow2State
*s
= bs
->opaque
;
3015 uint32_t head
= offset
% s
->cluster_size
;
3016 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3018 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3019 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3027 assert(head
+ bytes
<= s
->cluster_size
);
3029 /* check whether remainder of cluster already reads as zero */
3030 if (!(is_zero(bs
, offset
- head
, head
) &&
3031 is_zero(bs
, offset
+ bytes
,
3032 tail
? s
->cluster_size
- tail
: 0))) {
3036 qemu_co_mutex_lock(&s
->lock
);
3037 /* We can have new write after previous check */
3038 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3039 bytes
= s
->cluster_size
;
3040 nr
= s
->cluster_size
;
3041 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3042 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3043 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3044 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3045 qemu_co_mutex_unlock(&s
->lock
);
3049 qemu_co_mutex_lock(&s
->lock
);
3052 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3054 /* Whatever is left can use real zero clusters */
3055 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3056 qemu_co_mutex_unlock(&s
->lock
);
3061 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3062 int64_t offset
, int bytes
)
3065 BDRVQcow2State
*s
= bs
->opaque
;
3067 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3068 assert(bytes
< s
->cluster_size
);
3069 /* Ignore partial clusters, except for the special case of the
3070 * complete partial cluster at the end of an unaligned file */
3071 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3072 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3077 qemu_co_mutex_lock(&s
->lock
);
3078 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3080 qemu_co_mutex_unlock(&s
->lock
);
3084 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
,
3085 PreallocMode prealloc
, Error
**errp
)
3087 BDRVQcow2State
*s
= bs
->opaque
;
3088 uint64_t old_length
;
3089 int64_t new_l1_size
;
3092 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3093 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3095 error_setg(errp
, "Unsupported preallocation mode '%s'",
3096 PreallocMode_str(prealloc
));
3101 error_setg(errp
, "The new size must be a multiple of 512");
3105 /* cannot proceed if image has snapshots */
3106 if (s
->nb_snapshots
) {
3107 error_setg(errp
, "Can't resize an image which has snapshots");
3111 /* cannot proceed if image has bitmaps */
3112 if (s
->nb_bitmaps
) {
3113 /* TODO: resize bitmaps in the image */
3114 error_setg(errp
, "Can't resize an image which has bitmaps");
3118 old_length
= bs
->total_sectors
* 512;
3119 new_l1_size
= size_to_l1(s
, offset
);
3121 if (offset
< old_length
) {
3122 int64_t last_cluster
, old_file_size
;
3123 if (prealloc
!= PREALLOC_MODE_OFF
) {
3125 "Preallocation can't be used for shrinking an image");
3129 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3130 old_length
- ROUND_UP(offset
,
3132 QCOW2_DISCARD_ALWAYS
, true);
3134 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3138 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
3140 error_setg_errno(errp
, -ret
,
3141 "Failed to reduce the number of L2 tables");
3145 ret
= qcow2_shrink_reftable(bs
);
3147 error_setg_errno(errp
, -ret
,
3148 "Failed to discard unused refblocks");
3152 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3153 if (old_file_size
< 0) {
3154 error_setg_errno(errp
, -old_file_size
,
3155 "Failed to inquire current file length");
3156 return old_file_size
;
3158 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
3159 if (last_cluster
< 0) {
3160 error_setg_errno(errp
, -last_cluster
,
3161 "Failed to find the last cluster");
3162 return last_cluster
;
3164 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
3165 Error
*local_err
= NULL
;
3167 bdrv_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
3168 PREALLOC_MODE_OFF
, &local_err
);
3170 warn_reportf_err(local_err
,
3171 "Failed to truncate the tail of the image: ");
3175 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
3177 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
3183 case PREALLOC_MODE_OFF
:
3186 case PREALLOC_MODE_METADATA
:
3187 ret
= preallocate(bs
, old_length
, offset
);
3189 error_setg_errno(errp
, -ret
, "Preallocation failed");
3194 case PREALLOC_MODE_FALLOC
:
3195 case PREALLOC_MODE_FULL
:
3197 int64_t allocation_start
, host_offset
, guest_offset
;
3198 int64_t clusters_allocated
;
3199 int64_t old_file_size
, new_file_size
;
3200 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
3202 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3203 if (old_file_size
< 0) {
3204 error_setg_errno(errp
, -old_file_size
,
3205 "Failed to inquire current file length");
3206 return old_file_size
;
3208 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
3210 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
3213 /* This is an overestimation; we will not actually allocate space for
3214 * these in the file but just make sure the new refcount structures are
3215 * able to cover them so we will not have to allocate new refblocks
3216 * while entering the data blocks in the potentially new L2 tables.
3217 * (We do not actually care where the L2 tables are placed. Maybe they
3218 * are already allocated or they can be placed somewhere before
3219 * @old_file_size. It does not matter because they will be fully
3220 * allocated automatically, so they do not need to be covered by the
3221 * preallocation. All that matters is that we will not have to allocate
3222 * new refcount structures for them.) */
3223 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
3224 s
->cluster_size
/ sizeof(uint64_t));
3225 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3226 * table for a potential head/tail */
3229 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
3230 nb_new_data_clusters
+
3233 if (allocation_start
< 0) {
3234 error_setg_errno(errp
, -allocation_start
,
3235 "Failed to resize refcount structures");
3236 return allocation_start
;
3239 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
3240 nb_new_data_clusters
);
3241 if (clusters_allocated
< 0) {
3242 error_setg_errno(errp
, -clusters_allocated
,
3243 "Failed to allocate data clusters");
3244 return -clusters_allocated
;
3247 assert(clusters_allocated
== nb_new_data_clusters
);
3249 /* Allocate the data area */
3250 new_file_size
= allocation_start
+
3251 nb_new_data_clusters
* s
->cluster_size
;
3252 ret
= bdrv_truncate(bs
->file
, new_file_size
, prealloc
, errp
);
3254 error_prepend(errp
, "Failed to resize underlying file: ");
3255 qcow2_free_clusters(bs
, allocation_start
,
3256 nb_new_data_clusters
* s
->cluster_size
,
3257 QCOW2_DISCARD_OTHER
);
3261 /* Create the necessary L2 entries */
3262 host_offset
= allocation_start
;
3263 guest_offset
= old_length
;
3264 while (nb_new_data_clusters
) {
3265 int64_t guest_cluster
= guest_offset
>> s
->cluster_bits
;
3266 int64_t nb_clusters
= MIN(nb_new_data_clusters
,
3267 s
->l2_size
- guest_cluster
% s
->l2_size
);
3268 QCowL2Meta allocation
= {
3269 .offset
= guest_offset
,
3270 .alloc_offset
= host_offset
,
3271 .nb_clusters
= nb_clusters
,
3273 qemu_co_queue_init(&allocation
.dependent_requests
);
3275 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
3277 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
3278 qcow2_free_clusters(bs
, host_offset
,
3279 nb_new_data_clusters
* s
->cluster_size
,
3280 QCOW2_DISCARD_OTHER
);
3284 guest_offset
+= nb_clusters
* s
->cluster_size
;
3285 host_offset
+= nb_clusters
* s
->cluster_size
;
3286 nb_new_data_clusters
-= nb_clusters
;
3292 g_assert_not_reached();
3295 if (prealloc
!= PREALLOC_MODE_OFF
) {
3296 /* Flush metadata before actually changing the image size */
3297 ret
= bdrv_flush(bs
);
3299 error_setg_errno(errp
, -ret
,
3300 "Failed to flush the preallocated area to disk");
3305 /* write updated header.size */
3306 offset
= cpu_to_be64(offset
);
3307 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
3308 &offset
, sizeof(uint64_t));
3310 error_setg_errno(errp
, -ret
, "Failed to update the image size");
3314 s
->l1_vm_state_index
= new_l1_size
;
3318 /* XXX: put compressed sectors first, then all the cluster aligned
3319 tables to avoid losing bytes in alignment */
3320 static coroutine_fn
int
3321 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
3322 uint64_t bytes
, QEMUIOVector
*qiov
)
3324 BDRVQcow2State
*s
= bs
->opaque
;
3325 QEMUIOVector hd_qiov
;
3329 uint8_t *buf
, *out_buf
;
3330 int64_t cluster_offset
;
3333 /* align end of file to a sector boundary to ease reading with
3334 sector based I/Os */
3335 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
3336 if (cluster_offset
< 0) {
3337 return cluster_offset
;
3339 return bdrv_truncate(bs
->file
, cluster_offset
, PREALLOC_MODE_OFF
, NULL
);
3342 if (offset_into_cluster(s
, offset
)) {
3346 buf
= qemu_blockalign(bs
, s
->cluster_size
);
3347 if (bytes
!= s
->cluster_size
) {
3348 if (bytes
> s
->cluster_size
||
3349 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
3354 /* Zero-pad last write if image size is not cluster aligned */
3355 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
3357 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
3359 out_buf
= g_malloc(s
->cluster_size
);
3361 /* best compression, small window, no zlib header */
3362 memset(&strm
, 0, sizeof(strm
));
3363 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
3365 9, Z_DEFAULT_STRATEGY
);
3371 strm
.avail_in
= s
->cluster_size
;
3372 strm
.next_in
= (uint8_t *)buf
;
3373 strm
.avail_out
= s
->cluster_size
;
3374 strm
.next_out
= out_buf
;
3376 ret
= deflate(&strm
, Z_FINISH
);
3377 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
3382 out_len
= strm
.next_out
- out_buf
;
3386 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
3387 /* could not compress: write normal cluster */
3388 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
3395 qemu_co_mutex_lock(&s
->lock
);
3397 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
3398 if (!cluster_offset
) {
3399 qemu_co_mutex_unlock(&s
->lock
);
3403 cluster_offset
&= s
->cluster_offset_mask
;
3405 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
3406 qemu_co_mutex_unlock(&s
->lock
);
3411 iov
= (struct iovec
) {
3412 .iov_base
= out_buf
,
3415 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
3417 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
3418 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
3430 static int make_completely_empty(BlockDriverState
*bs
)
3432 BDRVQcow2State
*s
= bs
->opaque
;
3433 Error
*local_err
= NULL
;
3434 int ret
, l1_clusters
;
3436 uint64_t *new_reftable
= NULL
;
3437 uint64_t rt_entry
, l1_size2
;
3440 uint64_t reftable_offset
;
3441 uint32_t reftable_clusters
;
3442 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
3444 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
3449 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
3454 /* Refcounts will be broken utterly */
3455 ret
= qcow2_mark_dirty(bs
);
3460 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3462 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3463 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
3465 /* After this call, neither the in-memory nor the on-disk refcount
3466 * information accurately describe the actual references */
3468 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
3469 l1_clusters
* s
->cluster_size
, 0);
3471 goto fail_broken_refcounts
;
3473 memset(s
->l1_table
, 0, l1_size2
);
3475 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
3477 /* Overwrite enough clusters at the beginning of the sectors to place
3478 * the refcount table, a refcount block and the L1 table in; this may
3479 * overwrite parts of the existing refcount and L1 table, which is not
3480 * an issue because the dirty flag is set, complete data loss is in fact
3481 * desired and partial data loss is consequently fine as well */
3482 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
3483 (2 + l1_clusters
) * s
->cluster_size
, 0);
3484 /* This call (even if it failed overall) may have overwritten on-disk
3485 * refcount structures; in that case, the in-memory refcount information
3486 * will probably differ from the on-disk information which makes the BDS
3489 goto fail_broken_refcounts
;
3492 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3493 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
3495 /* "Create" an empty reftable (one cluster) directly after the image
3496 * header and an empty L1 table three clusters after the image header;
3497 * the cluster between those two will be used as the first refblock */
3498 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
3499 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
3500 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
3501 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
3502 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
3504 goto fail_broken_refcounts
;
3507 s
->l1_table_offset
= 3 * s
->cluster_size
;
3509 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
3510 if (!new_reftable
) {
3512 goto fail_broken_refcounts
;
3515 s
->refcount_table_offset
= s
->cluster_size
;
3516 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
3517 s
->max_refcount_table_index
= 0;
3519 g_free(s
->refcount_table
);
3520 s
->refcount_table
= new_reftable
;
3521 new_reftable
= NULL
;
3523 /* Now the in-memory refcount information again corresponds to the on-disk
3524 * information (reftable is empty and no refblocks (the refblock cache is
3525 * empty)); however, this means some clusters (e.g. the image header) are
3526 * referenced, but not refcounted, but the normal qcow2 code assumes that
3527 * the in-memory information is always correct */
3529 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
3531 /* Enter the first refblock into the reftable */
3532 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
3533 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
3534 &rt_entry
, sizeof(rt_entry
));
3536 goto fail_broken_refcounts
;
3538 s
->refcount_table
[0] = 2 * s
->cluster_size
;
3540 s
->free_cluster_index
= 0;
3541 assert(3 + l1_clusters
<= s
->refcount_block_size
);
3542 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
3545 goto fail_broken_refcounts
;
3546 } else if (offset
> 0) {
3547 error_report("First cluster in emptied image is in use");
3551 /* Now finally the in-memory information corresponds to the on-disk
3552 * structures and is correct */
3553 ret
= qcow2_mark_clean(bs
);
3558 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
3559 PREALLOC_MODE_OFF
, &local_err
);
3561 error_report_err(local_err
);
3567 fail_broken_refcounts
:
3568 /* The BDS is unusable at this point. If we wanted to make it usable, we
3569 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3570 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3571 * again. However, because the functions which could have caused this error
3572 * path to be taken are used by those functions as well, it's very likely
3573 * that that sequence will fail as well. Therefore, just eject the BDS. */
3577 g_free(new_reftable
);
3581 static int qcow2_make_empty(BlockDriverState
*bs
)
3583 BDRVQcow2State
*s
= bs
->opaque
;
3584 uint64_t offset
, end_offset
;
3585 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
3586 int l1_clusters
, ret
= 0;
3588 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3590 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
3591 3 + l1_clusters
<= s
->refcount_block_size
&&
3592 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
3593 /* The following function only works for qcow2 v3 images (it
3594 * requires the dirty flag) and only as long as there are no
3595 * features that reserve extra clusters (such as snapshots,
3596 * LUKS header, or persistent bitmaps), because it completely
3597 * empties the image. Furthermore, the L1 table and three
3598 * additional clusters (image header, refcount table, one
3599 * refcount block) have to fit inside one refcount block. */
3600 return make_completely_empty(bs
);
3603 /* This fallback code simply discards every active cluster; this is slow,
3604 * but works in all cases */
3605 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3606 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
3607 /* As this function is generally used after committing an external
3608 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3609 * default action for this kind of discard is to pass the discard,
3610 * which will ideally result in an actually smaller image file, as
3611 * is probably desired. */
3612 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
3613 QCOW2_DISCARD_SNAPSHOT
, true);
3622 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
3624 BDRVQcow2State
*s
= bs
->opaque
;
3627 qemu_co_mutex_lock(&s
->lock
);
3628 ret
= qcow2_cache_write(bs
, s
->l2_table_cache
);
3630 qemu_co_mutex_unlock(&s
->lock
);
3634 if (qcow2_need_accurate_refcounts(s
)) {
3635 ret
= qcow2_cache_write(bs
, s
->refcount_block_cache
);
3637 qemu_co_mutex_unlock(&s
->lock
);
3641 qemu_co_mutex_unlock(&s
->lock
);
3646 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
3649 Error
*local_err
= NULL
;
3650 BlockMeasureInfo
*info
;
3651 uint64_t required
= 0; /* bytes that contribute to required size */
3652 uint64_t virtual_size
; /* disk size as seen by guest */
3653 uint64_t refcount_bits
;
3655 size_t cluster_size
;
3658 PreallocMode prealloc
;
3659 bool has_backing_file
;
3661 /* Parse image creation options */
3662 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
3667 version
= qcow2_opt_get_version_del(opts
, &local_err
);
3672 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
3677 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
3678 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
3679 PREALLOC_MODE_OFF
, &local_err
);
3685 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
3686 has_backing_file
= !!optstr
;
3689 virtual_size
= align_offset(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
3692 /* Check that virtual disk size is valid */
3693 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
3694 cluster_size
/ sizeof(uint64_t));
3695 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
3696 error_setg(&local_err
, "The image size is too large "
3697 "(try using a larger cluster size)");
3701 /* Account for input image */
3703 int64_t ssize
= bdrv_getlength(in_bs
);
3705 error_setg_errno(&local_err
, -ssize
,
3706 "Unable to get image virtual_size");
3710 virtual_size
= align_offset(ssize
, cluster_size
);
3712 if (has_backing_file
) {
3713 /* We don't how much of the backing chain is shared by the input
3714 * image and the new image file. In the worst case the new image's
3715 * backing file has nothing in common with the input image. Be
3716 * conservative and assume all clusters need to be written.
3718 required
= virtual_size
;
3723 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
3726 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
3727 ssize
- offset
, &pnum
, NULL
,
3730 error_setg_errno(&local_err
, -ret
,
3731 "Unable to get block status");
3735 if (ret
& BDRV_BLOCK_ZERO
) {
3736 /* Skip zero regions (safe with no backing file) */
3737 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
3738 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
3739 /* Extend pnum to end of cluster for next iteration */
3740 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
3742 /* Count clusters we've seen */
3743 required
+= offset
% cluster_size
+ pnum
;
3749 /* Take into account preallocation. Nothing special is needed for
3750 * PREALLOC_MODE_METADATA since metadata is always counted.
3752 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
3753 required
= virtual_size
;
3756 info
= g_new(BlockMeasureInfo
, 1);
3757 info
->fully_allocated
=
3758 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
3759 ctz32(refcount_bits
));
3761 /* Remove data clusters that are not required. This overestimates the
3762 * required size because metadata needed for the fully allocated file is
3765 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
3769 error_propagate(errp
, local_err
);
3773 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3775 BDRVQcow2State
*s
= bs
->opaque
;
3776 bdi
->unallocated_blocks_are_zero
= true;
3777 bdi
->cluster_size
= s
->cluster_size
;
3778 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
3782 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
3784 BDRVQcow2State
*s
= bs
->opaque
;
3785 ImageInfoSpecific
*spec_info
;
3786 QCryptoBlockInfo
*encrypt_info
= NULL
;
3788 if (s
->crypto
!= NULL
) {
3789 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &error_abort
);
3792 spec_info
= g_new(ImageInfoSpecific
, 1);
3793 *spec_info
= (ImageInfoSpecific
){
3794 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
3795 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
3797 if (s
->qcow_version
== 2) {
3798 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3799 .compat
= g_strdup("0.10"),
3800 .refcount_bits
= s
->refcount_bits
,
3802 } else if (s
->qcow_version
== 3) {
3803 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3804 .compat
= g_strdup("1.1"),
3805 .lazy_refcounts
= s
->compatible_features
&
3806 QCOW2_COMPAT_LAZY_REFCOUNTS
,
3807 .has_lazy_refcounts
= true,
3808 .corrupt
= s
->incompatible_features
&
3809 QCOW2_INCOMPAT_CORRUPT
,
3810 .has_corrupt
= true,
3811 .refcount_bits
= s
->refcount_bits
,
3814 /* if this assertion fails, this probably means a new version was
3815 * added without having it covered here */
3820 ImageInfoSpecificQCow2Encryption
*qencrypt
=
3821 g_new(ImageInfoSpecificQCow2Encryption
, 1);
3822 switch (encrypt_info
->format
) {
3823 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
3824 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
3825 qencrypt
->u
.aes
= encrypt_info
->u
.qcow
;
3827 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
3828 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
3829 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
3834 /* Since we did shallow copy above, erase any pointers
3835 * in the original info */
3836 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
3837 qapi_free_QCryptoBlockInfo(encrypt_info
);
3839 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
3840 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
3846 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3849 BDRVQcow2State
*s
= bs
->opaque
;
3851 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
3852 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
3853 qiov
->size
, qiov
, 0);
3856 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3859 BDRVQcow2State
*s
= bs
->opaque
;
3861 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
3862 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
3863 qiov
->size
, qiov
, 0);
3867 * Downgrades an image's version. To achieve this, any incompatible features
3868 * have to be removed.
3870 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
3871 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
)
3873 BDRVQcow2State
*s
= bs
->opaque
;
3874 int current_version
= s
->qcow_version
;
3877 if (target_version
== current_version
) {
3879 } else if (target_version
> current_version
) {
3881 } else if (target_version
!= 2) {
3885 if (s
->refcount_order
!= 4) {
3886 error_report("compat=0.10 requires refcount_bits=16");
3890 /* clear incompatible features */
3891 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
3892 ret
= qcow2_mark_clean(bs
);
3898 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3899 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3900 * best thing to do anyway */
3902 if (s
->incompatible_features
) {
3906 /* since we can ignore compatible features, we can set them to 0 as well */
3907 s
->compatible_features
= 0;
3908 /* if lazy refcounts have been used, they have already been fixed through
3909 * clearing the dirty flag */
3911 /* clearing autoclear features is trivial */
3912 s
->autoclear_features
= 0;
3914 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
3919 s
->qcow_version
= target_version
;
3920 ret
= qcow2_update_header(bs
);
3922 s
->qcow_version
= current_version
;
3928 typedef enum Qcow2AmendOperation
{
3929 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3930 * statically initialized to so that the helper CB can discern the first
3931 * invocation from an operation change */
3932 QCOW2_NO_OPERATION
= 0,
3934 QCOW2_CHANGING_REFCOUNT_ORDER
,
3936 } Qcow2AmendOperation
;
3938 typedef struct Qcow2AmendHelperCBInfo
{
3939 /* The code coordinating the amend operations should only modify
3940 * these four fields; the rest will be managed by the CB */
3941 BlockDriverAmendStatusCB
*original_status_cb
;
3942 void *original_cb_opaque
;
3944 Qcow2AmendOperation current_operation
;
3946 /* Total number of operations to perform (only set once) */
3947 int total_operations
;
3949 /* The following fields are managed by the CB */
3951 /* Number of operations completed */
3952 int operations_completed
;
3954 /* Cumulative offset of all completed operations */
3955 int64_t offset_completed
;
3957 Qcow2AmendOperation last_operation
;
3958 int64_t last_work_size
;
3959 } Qcow2AmendHelperCBInfo
;
3961 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
3962 int64_t operation_offset
,
3963 int64_t operation_work_size
, void *opaque
)
3965 Qcow2AmendHelperCBInfo
*info
= opaque
;
3966 int64_t current_work_size
;
3967 int64_t projected_work_size
;
3969 if (info
->current_operation
!= info
->last_operation
) {
3970 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
3971 info
->offset_completed
+= info
->last_work_size
;
3972 info
->operations_completed
++;
3975 info
->last_operation
= info
->current_operation
;
3978 assert(info
->total_operations
> 0);
3979 assert(info
->operations_completed
< info
->total_operations
);
3981 info
->last_work_size
= operation_work_size
;
3983 current_work_size
= info
->offset_completed
+ operation_work_size
;
3985 /* current_work_size is the total work size for (operations_completed + 1)
3986 * operations (which includes this one), so multiply it by the number of
3987 * operations not covered and divide it by the number of operations
3988 * covered to get a projection for the operations not covered */
3989 projected_work_size
= current_work_size
* (info
->total_operations
-
3990 info
->operations_completed
- 1)
3991 / (info
->operations_completed
+ 1);
3993 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
3994 current_work_size
+ projected_work_size
,
3995 info
->original_cb_opaque
);
3998 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
3999 BlockDriverAmendStatusCB
*status_cb
,
4002 BDRVQcow2State
*s
= bs
->opaque
;
4003 int old_version
= s
->qcow_version
, new_version
= old_version
;
4004 uint64_t new_size
= 0;
4005 const char *backing_file
= NULL
, *backing_format
= NULL
;
4006 bool lazy_refcounts
= s
->use_lazy_refcounts
;
4007 const char *compat
= NULL
;
4008 uint64_t cluster_size
= s
->cluster_size
;
4011 int refcount_bits
= s
->refcount_bits
;
4012 Error
*local_err
= NULL
;
4014 QemuOptDesc
*desc
= opts
->list
->desc
;
4015 Qcow2AmendHelperCBInfo helper_cb_info
;
4017 while (desc
&& desc
->name
) {
4018 if (!qemu_opt_find(opts
, desc
->name
)) {
4019 /* only change explicitly defined options */
4024 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
4025 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
4027 /* preserve default */
4028 } else if (!strcmp(compat
, "0.10")) {
4030 } else if (!strcmp(compat
, "1.1")) {
4033 error_report("Unknown compatibility level %s", compat
);
4036 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
4037 error_report("Cannot change preallocation mode");
4039 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
4040 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
4041 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
4042 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
4043 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
4044 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
4045 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
4046 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
4049 if (encrypt
!= !!s
->crypto
) {
4050 error_report("Changing the encryption flag is not supported");
4053 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
4054 encformat
= qcow2_crypt_method_from_format(
4055 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
4057 if (encformat
!= s
->crypt_method_header
) {
4058 error_report("Changing the encryption format is not supported");
4061 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
4062 error_report("Changing the encryption parameters is not supported");
4064 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
4065 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
4067 if (cluster_size
!= s
->cluster_size
) {
4068 error_report("Changing the cluster size is not supported");
4071 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
4072 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
4074 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
4075 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
4078 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
4079 !is_power_of_2(refcount_bits
))
4081 error_report("Refcount width must be a power of two and may "
4082 "not exceed 64 bits");
4086 /* if this point is reached, this probably means a new option was
4087 * added without having it covered here */
4094 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
4095 .original_status_cb
= status_cb
,
4096 .original_cb_opaque
= cb_opaque
,
4097 .total_operations
= (new_version
< old_version
)
4098 + (s
->refcount_bits
!= refcount_bits
)
4101 /* Upgrade first (some features may require compat=1.1) */
4102 if (new_version
> old_version
) {
4103 s
->qcow_version
= new_version
;
4104 ret
= qcow2_update_header(bs
);
4106 s
->qcow_version
= old_version
;
4111 if (s
->refcount_bits
!= refcount_bits
) {
4112 int refcount_order
= ctz32(refcount_bits
);
4114 if (new_version
< 3 && refcount_bits
!= 16) {
4115 error_report("Different refcount widths than 16 bits require "
4116 "compatibility level 1.1 or above (use compat=1.1 or "
4121 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
4122 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
4123 &qcow2_amend_helper_cb
,
4124 &helper_cb_info
, &local_err
);
4126 error_report_err(local_err
);
4131 if (backing_file
|| backing_format
) {
4132 ret
= qcow2_change_backing_file(bs
,
4133 backing_file
?: s
->image_backing_file
,
4134 backing_format
?: s
->image_backing_format
);
4140 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
4141 if (lazy_refcounts
) {
4142 if (new_version
< 3) {
4143 error_report("Lazy refcounts only supported with compatibility "
4144 "level 1.1 and above (use compat=1.1 or greater)");
4147 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4148 ret
= qcow2_update_header(bs
);
4150 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4153 s
->use_lazy_refcounts
= true;
4155 /* make image clean first */
4156 ret
= qcow2_mark_clean(bs
);
4160 /* now disallow lazy refcounts */
4161 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4162 ret
= qcow2_update_header(bs
);
4164 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4167 s
->use_lazy_refcounts
= false;
4172 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
4173 ret
= blk_insert_bs(blk
, bs
, &local_err
);
4175 error_report_err(local_err
);
4180 ret
= blk_truncate(blk
, new_size
, PREALLOC_MODE_OFF
, &local_err
);
4183 error_report_err(local_err
);
4188 /* Downgrade last (so unsupported features can be removed before) */
4189 if (new_version
< old_version
) {
4190 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
4191 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
4202 * If offset or size are negative, respectively, they will not be included in
4203 * the BLOCK_IMAGE_CORRUPTED event emitted.
4204 * fatal will be ignored for read-only BDS; corruptions found there will always
4205 * be considered non-fatal.
4207 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
4208 int64_t size
, const char *message_format
, ...)
4210 BDRVQcow2State
*s
= bs
->opaque
;
4211 const char *node_name
;
4215 fatal
= fatal
&& !bs
->read_only
;
4217 if (s
->signaled_corruption
&&
4218 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
4223 va_start(ap
, message_format
);
4224 message
= g_strdup_vprintf(message_format
, ap
);
4228 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
4229 "corruption events will be suppressed\n", message
);
4231 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
4232 "corruption events will be suppressed\n", message
);
4235 node_name
= bdrv_get_node_name(bs
);
4236 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
4237 *node_name
!= '\0', node_name
,
4238 message
, offset
>= 0, offset
,
4240 fatal
, &error_abort
);
4244 qcow2_mark_corrupt(bs
);
4245 bs
->drv
= NULL
; /* make BDS unusable */
4248 s
->signaled_corruption
= true;
4251 static QemuOptsList qcow2_create_opts
= {
4252 .name
= "qcow2-create-opts",
4253 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
4256 .name
= BLOCK_OPT_SIZE
,
4257 .type
= QEMU_OPT_SIZE
,
4258 .help
= "Virtual disk size"
4261 .name
= BLOCK_OPT_COMPAT_LEVEL
,
4262 .type
= QEMU_OPT_STRING
,
4263 .help
= "Compatibility level (0.10 or 1.1)"
4266 .name
= BLOCK_OPT_BACKING_FILE
,
4267 .type
= QEMU_OPT_STRING
,
4268 .help
= "File name of a base image"
4271 .name
= BLOCK_OPT_BACKING_FMT
,
4272 .type
= QEMU_OPT_STRING
,
4273 .help
= "Image format of the base image"
4276 .name
= BLOCK_OPT_ENCRYPT
,
4277 .type
= QEMU_OPT_BOOL
,
4278 .help
= "Encrypt the image with format 'aes'. (Deprecated "
4279 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
4282 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
4283 .type
= QEMU_OPT_STRING
,
4284 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
4286 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4287 "ID of secret providing qcow AES key or LUKS passphrase"),
4288 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4289 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4290 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4291 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4292 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4293 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4295 .name
= BLOCK_OPT_CLUSTER_SIZE
,
4296 .type
= QEMU_OPT_SIZE
,
4297 .help
= "qcow2 cluster size",
4298 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
4301 .name
= BLOCK_OPT_PREALLOC
,
4302 .type
= QEMU_OPT_STRING
,
4303 .help
= "Preallocation mode (allowed values: off, metadata, "
4307 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
4308 .type
= QEMU_OPT_BOOL
,
4309 .help
= "Postpone refcount updates",
4310 .def_value_str
= "off"
4313 .name
= BLOCK_OPT_REFCOUNT_BITS
,
4314 .type
= QEMU_OPT_NUMBER
,
4315 .help
= "Width of a reference count entry in bits",
4316 .def_value_str
= "16"
4318 { /* end of list */ }
4322 BlockDriver bdrv_qcow2
= {
4323 .format_name
= "qcow2",
4324 .instance_size
= sizeof(BDRVQcow2State
),
4325 .bdrv_probe
= qcow2_probe
,
4326 .bdrv_open
= qcow2_open
,
4327 .bdrv_close
= qcow2_close
,
4328 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
4329 .bdrv_reopen_commit
= qcow2_reopen_commit
,
4330 .bdrv_reopen_abort
= qcow2_reopen_abort
,
4331 .bdrv_join_options
= qcow2_join_options
,
4332 .bdrv_child_perm
= bdrv_format_default_perms
,
4333 .bdrv_create
= qcow2_create
,
4334 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
4335 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
4337 .bdrv_co_preadv
= qcow2_co_preadv
,
4338 .bdrv_co_pwritev
= qcow2_co_pwritev
,
4339 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
4341 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
4342 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
4343 .bdrv_truncate
= qcow2_truncate
,
4344 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
4345 .bdrv_make_empty
= qcow2_make_empty
,
4347 .bdrv_snapshot_create
= qcow2_snapshot_create
,
4348 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
4349 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
4350 .bdrv_snapshot_list
= qcow2_snapshot_list
,
4351 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
4352 .bdrv_measure
= qcow2_measure
,
4353 .bdrv_get_info
= qcow2_get_info
,
4354 .bdrv_get_specific_info
= qcow2_get_specific_info
,
4356 .bdrv_save_vmstate
= qcow2_save_vmstate
,
4357 .bdrv_load_vmstate
= qcow2_load_vmstate
,
4359 .supports_backing
= true,
4360 .bdrv_change_backing_file
= qcow2_change_backing_file
,
4362 .bdrv_refresh_limits
= qcow2_refresh_limits
,
4363 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
4364 .bdrv_inactivate
= qcow2_inactivate
,
4366 .create_opts
= &qcow2_create_opts
,
4367 .bdrv_check
= qcow2_check
,
4368 .bdrv_amend_options
= qcow2_amend_options
,
4370 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
4371 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
4373 .bdrv_reopen_bitmaps_rw
= qcow2_reopen_bitmaps_rw
,
4374 .bdrv_can_store_new_dirty_bitmap
= qcow2_can_store_new_dirty_bitmap
,
4375 .bdrv_remove_persistent_dirty_bitmap
= qcow2_remove_persistent_dirty_bitmap
,
4378 static void bdrv_qcow2_init(void)
4380 bdrv_register(&bdrv_qcow2
);
4383 block_init(bdrv_qcow2_init
);