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/qapi-events-block-core.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
40 #include "qapi/qobject-input-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "block/crypto.h"
45 Differences with QCOW:
47 - Support for multiple incremental snapshots.
48 - Memory management by reference counts.
49 - Clusters which have a reference count of one have the bit
50 QCOW_OFLAG_COPIED to optimize write performance.
51 - Size of compressed clusters is stored in sectors to reduce bit usage
52 in the cluster offsets.
53 - Support for storing additional data (such as the VM state) in the
55 - If a backing store is used, the cluster size is not constrained
56 (could be backported to QCOW).
57 - L2 tables have always a size of one cluster.
64 } QEMU_PACKED QCowExtension
;
66 #define QCOW2_EXT_MAGIC_END 0
67 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
68 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
69 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
70 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
72 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
74 const QCowHeader
*cow_header
= (const void *)buf
;
76 if (buf_size
>= sizeof(QCowHeader
) &&
77 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
78 be32_to_cpu(cow_header
->version
) >= 2)
85 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
86 uint8_t *buf
, size_t buflen
,
87 void *opaque
, Error
**errp
)
89 BlockDriverState
*bs
= opaque
;
90 BDRVQcow2State
*s
= bs
->opaque
;
93 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
94 error_setg(errp
, "Request for data outside of extension header");
98 ret
= bdrv_pread(bs
->file
,
99 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
101 error_setg_errno(errp
, -ret
, "Could not read encryption header");
108 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
109 void *opaque
, Error
**errp
)
111 BlockDriverState
*bs
= opaque
;
112 BDRVQcow2State
*s
= bs
->opaque
;
116 ret
= qcow2_alloc_clusters(bs
, headerlen
);
118 error_setg_errno(errp
, -ret
,
119 "Cannot allocate cluster for LUKS header size %zu",
124 s
->crypto_header
.length
= headerlen
;
125 s
->crypto_header
.offset
= ret
;
127 /* Zero fill remaining space in cluster so it has predictable
128 * content in case of future spec changes */
129 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
130 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
) == 0);
131 ret
= bdrv_pwrite_zeroes(bs
->file
,
133 clusterlen
- headerlen
, 0);
135 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
143 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
144 const uint8_t *buf
, size_t buflen
,
145 void *opaque
, Error
**errp
)
147 BlockDriverState
*bs
= opaque
;
148 BDRVQcow2State
*s
= bs
->opaque
;
151 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
152 error_setg(errp
, "Request for data outside of extension header");
156 ret
= bdrv_pwrite(bs
->file
,
157 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
159 error_setg_errno(errp
, -ret
, "Could not read encryption header");
167 * read qcow2 extension and fill bs
168 * start reading from start_offset
169 * finish reading upon magic of value 0 or when end_offset reached
170 * unknown magic is skipped (future extension this version knows nothing about)
171 * return 0 upon success, non-0 otherwise
173 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
174 uint64_t end_offset
, void **p_feature_table
,
175 int flags
, bool *need_update_header
,
178 BDRVQcow2State
*s
= bs
->opaque
;
182 Qcow2BitmapHeaderExt bitmaps_ext
;
184 if (need_update_header
!= NULL
) {
185 *need_update_header
= false;
189 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
191 offset
= start_offset
;
192 while (offset
< end_offset
) {
196 if (offset
> s
->cluster_size
)
197 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
199 printf("attempting to read extended header in offset %lu\n", offset
);
202 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
204 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
205 "pread fail from offset %" PRIu64
, offset
);
208 be32_to_cpus(&ext
.magic
);
209 be32_to_cpus(&ext
.len
);
210 offset
+= sizeof(ext
);
212 printf("ext.magic = 0x%x\n", ext
.magic
);
214 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
215 error_setg(errp
, "Header extension too large");
220 case QCOW2_EXT_MAGIC_END
:
223 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
224 if (ext
.len
>= sizeof(bs
->backing_format
)) {
225 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
226 " too large (>=%zu)", ext
.len
,
227 sizeof(bs
->backing_format
));
230 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
232 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
233 "Could not read format name");
236 bs
->backing_format
[ext
.len
] = '\0';
237 s
->image_backing_format
= g_strdup(bs
->backing_format
);
239 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
243 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
244 if (p_feature_table
!= NULL
) {
245 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
246 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
248 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
249 "Could not read table");
253 *p_feature_table
= feature_table
;
257 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
258 unsigned int cflags
= 0;
259 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
260 error_setg(errp
, "CRYPTO header extension only "
261 "expected with LUKS encryption method");
264 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
265 error_setg(errp
, "CRYPTO header extension size %u, "
266 "but expected size %zu", ext
.len
,
267 sizeof(Qcow2CryptoHeaderExtension
));
271 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
273 error_setg_errno(errp
, -ret
,
274 "Unable to read CRYPTO header extension");
277 be64_to_cpus(&s
->crypto_header
.offset
);
278 be64_to_cpus(&s
->crypto_header
.length
);
280 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
281 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
282 "not a multiple of cluster size '%u'",
283 s
->crypto_header
.offset
, s
->cluster_size
);
287 if (flags
& BDRV_O_NO_IO
) {
288 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
290 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
291 qcow2_crypto_hdr_read_func
,
298 case QCOW2_EXT_MAGIC_BITMAPS
:
299 if (ext
.len
!= sizeof(bitmaps_ext
)) {
300 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
301 "Invalid extension length");
305 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
306 if (s
->qcow_version
< 3) {
307 /* Let's be a bit more specific */
308 warn_report("This qcow2 v2 image contains bitmaps, but "
309 "they may have been modified by a program "
310 "without persistent bitmap support; so now "
311 "they must all be considered inconsistent");
313 warn_report("a program lacking bitmap support "
314 "modified this file, so all bitmaps are now "
315 "considered inconsistent");
317 error_printf("Some clusters may be leaked, "
318 "run 'qemu-img check -r' on the image "
320 if (need_update_header
!= NULL
) {
321 /* Updating is needed to drop invalid bitmap extension. */
322 *need_update_header
= true;
327 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
329 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
330 "Could not read ext header");
334 if (bitmaps_ext
.reserved32
!= 0) {
335 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
336 "Reserved field is not zero");
340 be32_to_cpus(&bitmaps_ext
.nb_bitmaps
);
341 be64_to_cpus(&bitmaps_ext
.bitmap_directory_size
);
342 be64_to_cpus(&bitmaps_ext
.bitmap_directory_offset
);
344 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
346 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
347 "exceeding the QEMU supported maximum of %d",
348 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
352 if (bitmaps_ext
.nb_bitmaps
== 0) {
353 error_setg(errp
, "found bitmaps extension with zero bitmaps");
357 if (bitmaps_ext
.bitmap_directory_offset
& (s
->cluster_size
- 1)) {
358 error_setg(errp
, "bitmaps_ext: "
359 "invalid bitmap directory offset");
363 if (bitmaps_ext
.bitmap_directory_size
>
364 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
365 error_setg(errp
, "bitmaps_ext: "
366 "bitmap directory size (%" PRIu64
") exceeds "
367 "the maximum supported size (%d)",
368 bitmaps_ext
.bitmap_directory_size
,
369 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
373 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
374 s
->bitmap_directory_offset
=
375 bitmaps_ext
.bitmap_directory_offset
;
376 s
->bitmap_directory_size
=
377 bitmaps_ext
.bitmap_directory_size
;
380 printf("Qcow2: Got bitmaps extension: "
381 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
382 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
387 /* unknown magic - save it in case we need to rewrite the header */
388 /* If you add a new feature, make sure to also update the fast
389 * path of qcow2_make_empty() to deal with it. */
391 Qcow2UnknownHeaderExtension
*uext
;
393 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
394 uext
->magic
= ext
.magic
;
396 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
398 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
400 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
401 "Could not read data");
408 offset
+= ((ext
.len
+ 7) & ~7);
414 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
416 BDRVQcow2State
*s
= bs
->opaque
;
417 Qcow2UnknownHeaderExtension
*uext
, *next
;
419 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
420 QLIST_REMOVE(uext
, next
);
425 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
428 char *features
= g_strdup("");
431 while (table
&& table
->name
[0] != '\0') {
432 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
433 if (mask
& (1ULL << table
->bit
)) {
435 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
438 mask
&= ~(1ULL << table
->bit
);
446 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
447 old
, *old
? ", " : "", mask
);
451 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
456 * Sets the dirty bit and flushes afterwards if necessary.
458 * The incompatible_features bit is only set if the image file header was
459 * updated successfully. Therefore it is not required to check the return
460 * value of this function.
462 int qcow2_mark_dirty(BlockDriverState
*bs
)
464 BDRVQcow2State
*s
= bs
->opaque
;
468 assert(s
->qcow_version
>= 3);
470 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
471 return 0; /* already dirty */
474 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
475 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
480 ret
= bdrv_flush(bs
->file
->bs
);
485 /* Only treat image as dirty if the header was updated successfully */
486 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
491 * Clears the dirty bit and flushes before if necessary. Only call this
492 * function when there are no pending requests, it does not guard against
493 * concurrent requests dirtying the image.
495 static int qcow2_mark_clean(BlockDriverState
*bs
)
497 BDRVQcow2State
*s
= bs
->opaque
;
499 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
502 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
504 ret
= qcow2_flush_caches(bs
);
509 return qcow2_update_header(bs
);
515 * Marks the image as corrupt.
517 int qcow2_mark_corrupt(BlockDriverState
*bs
)
519 BDRVQcow2State
*s
= bs
->opaque
;
521 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
522 return qcow2_update_header(bs
);
526 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
527 * before if necessary.
529 int qcow2_mark_consistent(BlockDriverState
*bs
)
531 BDRVQcow2State
*s
= bs
->opaque
;
533 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
534 int ret
= qcow2_flush_caches(bs
);
539 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
540 return qcow2_update_header(bs
);
545 static int coroutine_fn
qcow2_co_check_locked(BlockDriverState
*bs
,
546 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 coroutine_fn
qcow2_co_check(BlockDriverState
*bs
,
565 BdrvCheckResult
*result
,
568 BDRVQcow2State
*s
= bs
->opaque
;
571 qemu_co_mutex_lock(&s
->lock
);
572 ret
= qcow2_co_check_locked(bs
, result
, fix
);
573 qemu_co_mutex_unlock(&s
->lock
);
577 int qcow2_validate_table(BlockDriverState
*bs
, uint64_t offset
,
578 uint64_t entries
, size_t entry_len
,
579 int64_t max_size_bytes
, const char *table_name
,
582 BDRVQcow2State
*s
= bs
->opaque
;
584 if (entries
> max_size_bytes
/ entry_len
) {
585 error_setg(errp
, "%s too large", table_name
);
589 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
590 * because values will be passed to qemu functions taking int64_t. */
591 if ((INT64_MAX
- entries
* entry_len
< offset
) ||
592 (offset_into_cluster(s
, offset
) != 0)) {
593 error_setg(errp
, "%s offset invalid", table_name
);
600 static QemuOptsList qcow2_runtime_opts
= {
602 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
605 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
606 .type
= QEMU_OPT_BOOL
,
607 .help
= "Postpone refcount updates",
610 .name
= QCOW2_OPT_DISCARD_REQUEST
,
611 .type
= QEMU_OPT_BOOL
,
612 .help
= "Pass guest discard requests to the layer below",
615 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
616 .type
= QEMU_OPT_BOOL
,
617 .help
= "Generate discard requests when snapshot related space "
621 .name
= QCOW2_OPT_DISCARD_OTHER
,
622 .type
= QEMU_OPT_BOOL
,
623 .help
= "Generate discard requests when other clusters are freed",
626 .name
= QCOW2_OPT_OVERLAP
,
627 .type
= QEMU_OPT_STRING
,
628 .help
= "Selects which overlap checks to perform from a range of "
629 "templates (none, constant, cached, all)",
632 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
633 .type
= QEMU_OPT_STRING
,
634 .help
= "Selects which overlap checks to perform from a range of "
635 "templates (none, constant, cached, all)",
638 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
639 .type
= QEMU_OPT_BOOL
,
640 .help
= "Check for unintended writes into the main qcow2 header",
643 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
644 .type
= QEMU_OPT_BOOL
,
645 .help
= "Check for unintended writes into the active L1 table",
648 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
649 .type
= QEMU_OPT_BOOL
,
650 .help
= "Check for unintended writes into an active L2 table",
653 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
654 .type
= QEMU_OPT_BOOL
,
655 .help
= "Check for unintended writes into the refcount table",
658 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
659 .type
= QEMU_OPT_BOOL
,
660 .help
= "Check for unintended writes into a refcount block",
663 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
664 .type
= QEMU_OPT_BOOL
,
665 .help
= "Check for unintended writes into the snapshot table",
668 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
669 .type
= QEMU_OPT_BOOL
,
670 .help
= "Check for unintended writes into an inactive L1 table",
673 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
674 .type
= QEMU_OPT_BOOL
,
675 .help
= "Check for unintended writes into an inactive L2 table",
678 .name
= QCOW2_OPT_CACHE_SIZE
,
679 .type
= QEMU_OPT_SIZE
,
680 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
684 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
685 .type
= QEMU_OPT_SIZE
,
686 .help
= "Maximum L2 table cache size",
689 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
690 .type
= QEMU_OPT_SIZE
,
691 .help
= "Size of each entry in the L2 cache",
694 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
695 .type
= QEMU_OPT_SIZE
,
696 .help
= "Maximum refcount block cache size",
699 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
700 .type
= QEMU_OPT_NUMBER
,
701 .help
= "Clean unused cache entries after this time (in seconds)",
703 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
704 "ID of secret providing qcow2 AES key or LUKS passphrase"),
705 { /* end of list */ }
709 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
710 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
711 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
712 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
713 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
714 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
715 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
716 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
717 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
720 static void cache_clean_timer_cb(void *opaque
)
722 BlockDriverState
*bs
= opaque
;
723 BDRVQcow2State
*s
= bs
->opaque
;
724 qcow2_cache_clean_unused(s
->l2_table_cache
);
725 qcow2_cache_clean_unused(s
->refcount_block_cache
);
726 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
727 (int64_t) s
->cache_clean_interval
* 1000);
730 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
732 BDRVQcow2State
*s
= bs
->opaque
;
733 if (s
->cache_clean_interval
> 0) {
734 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
735 SCALE_MS
, cache_clean_timer_cb
,
737 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
738 (int64_t) s
->cache_clean_interval
* 1000);
742 static void cache_clean_timer_del(BlockDriverState
*bs
)
744 BDRVQcow2State
*s
= bs
->opaque
;
745 if (s
->cache_clean_timer
) {
746 timer_del(s
->cache_clean_timer
);
747 timer_free(s
->cache_clean_timer
);
748 s
->cache_clean_timer
= NULL
;
752 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
754 cache_clean_timer_del(bs
);
757 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
758 AioContext
*new_context
)
760 cache_clean_timer_init(bs
, new_context
);
763 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
764 uint64_t *l2_cache_size
,
765 uint64_t *l2_cache_entry_size
,
766 uint64_t *refcount_cache_size
, Error
**errp
)
768 BDRVQcow2State
*s
= bs
->opaque
;
769 uint64_t combined_cache_size
;
770 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
771 int min_refcount_cache
= MIN_REFCOUNT_CACHE_SIZE
* s
->cluster_size
;
773 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
774 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
775 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
777 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
778 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
779 *refcount_cache_size
= qemu_opt_get_size(opts
,
780 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
782 *l2_cache_entry_size
= qemu_opt_get_size(
783 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
785 if (combined_cache_size_set
) {
786 if (l2_cache_size_set
&& refcount_cache_size_set
) {
787 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
788 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
791 } else if (*l2_cache_size
> combined_cache_size
) {
792 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
793 QCOW2_OPT_CACHE_SIZE
);
795 } else if (*refcount_cache_size
> combined_cache_size
) {
796 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
797 QCOW2_OPT_CACHE_SIZE
);
801 if (l2_cache_size_set
) {
802 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
803 } else if (refcount_cache_size_set
) {
804 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
806 uint64_t virtual_disk_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
807 uint64_t max_l2_cache
= virtual_disk_size
/ (s
->cluster_size
/ 8);
809 /* Assign as much memory as possible to the L2 cache, and
810 * use the remainder for the refcount cache */
811 if (combined_cache_size
>= max_l2_cache
+ min_refcount_cache
) {
812 *l2_cache_size
= max_l2_cache
;
813 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
815 *refcount_cache_size
=
816 MIN(combined_cache_size
, min_refcount_cache
);
817 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
821 if (!l2_cache_size_set
) {
822 *l2_cache_size
= MAX(DEFAULT_L2_CACHE_BYTE_SIZE
,
823 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
826 if (!refcount_cache_size_set
) {
827 *refcount_cache_size
= min_refcount_cache
;
831 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
832 *l2_cache_entry_size
> s
->cluster_size
||
833 !is_power_of_2(*l2_cache_entry_size
)) {
834 error_setg(errp
, "L2 cache entry size must be a power of two "
835 "between %d and the cluster size (%d)",
836 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
841 typedef struct Qcow2ReopenState
{
842 Qcow2Cache
*l2_table_cache
;
843 Qcow2Cache
*refcount_block_cache
;
844 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
845 bool use_lazy_refcounts
;
847 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
848 uint64_t cache_clean_interval
;
849 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
852 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
854 QDict
*options
, int flags
,
857 BDRVQcow2State
*s
= bs
->opaque
;
858 QemuOpts
*opts
= NULL
;
859 const char *opt_overlap_check
, *opt_overlap_check_template
;
860 int overlap_check_template
= 0;
861 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
863 const char *encryptfmt
;
864 QDict
*encryptopts
= NULL
;
865 Error
*local_err
= NULL
;
868 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
869 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
871 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
872 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
874 error_propagate(errp
, local_err
);
879 /* get L2 table/refcount block cache size from command line options */
880 read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
881 &refcount_cache_size
, &local_err
);
883 error_propagate(errp
, local_err
);
888 l2_cache_size
/= l2_cache_entry_size
;
889 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
890 l2_cache_size
= MIN_L2_CACHE_SIZE
;
892 if (l2_cache_size
> INT_MAX
) {
893 error_setg(errp
, "L2 cache size too big");
898 refcount_cache_size
/= s
->cluster_size
;
899 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
900 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
902 if (refcount_cache_size
> INT_MAX
) {
903 error_setg(errp
, "Refcount cache size too big");
908 /* alloc new L2 table/refcount block cache, flush old one */
909 if (s
->l2_table_cache
) {
910 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
912 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
917 if (s
->refcount_block_cache
) {
918 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
920 error_setg_errno(errp
, -ret
,
921 "Failed to flush the refcount block cache");
926 r
->l2_slice_size
= l2_cache_entry_size
/ sizeof(uint64_t);
927 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
928 l2_cache_entry_size
);
929 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
931 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
932 error_setg(errp
, "Could not allocate metadata caches");
937 /* New interval for cache cleanup timer */
938 r
->cache_clean_interval
=
939 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
940 s
->cache_clean_interval
);
942 if (r
->cache_clean_interval
!= 0) {
943 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
944 " not supported on this host");
949 if (r
->cache_clean_interval
> UINT_MAX
) {
950 error_setg(errp
, "Cache clean interval too big");
955 /* lazy-refcounts; flush if going from enabled to disabled */
956 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
957 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
958 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
959 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
960 "qemu 1.1 compatibility level");
965 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
966 ret
= qcow2_mark_clean(bs
);
968 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
973 /* Overlap check options */
974 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
975 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
976 if (opt_overlap_check_template
&& opt_overlap_check
&&
977 strcmp(opt_overlap_check_template
, opt_overlap_check
))
979 error_setg(errp
, "Conflicting values for qcow2 options '"
980 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
981 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
985 if (!opt_overlap_check
) {
986 opt_overlap_check
= opt_overlap_check_template
?: "cached";
989 if (!strcmp(opt_overlap_check
, "none")) {
990 overlap_check_template
= 0;
991 } else if (!strcmp(opt_overlap_check
, "constant")) {
992 overlap_check_template
= QCOW2_OL_CONSTANT
;
993 } else if (!strcmp(opt_overlap_check
, "cached")) {
994 overlap_check_template
= QCOW2_OL_CACHED
;
995 } else if (!strcmp(opt_overlap_check
, "all")) {
996 overlap_check_template
= QCOW2_OL_ALL
;
998 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
999 "'overlap-check'. Allowed are any of the following: "
1000 "none, constant, cached, all", opt_overlap_check
);
1005 r
->overlap_check
= 0;
1006 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
1007 /* overlap-check defines a template bitmask, but every flag may be
1008 * overwritten through the associated boolean option */
1010 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
1011 overlap_check_template
& (1 << i
)) << i
;
1014 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
1015 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
1016 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
1017 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1018 flags
& BDRV_O_UNMAP
);
1019 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1020 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1021 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1022 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1024 switch (s
->crypt_method_header
) {
1025 case QCOW_CRYPT_NONE
:
1027 error_setg(errp
, "No encryption in image header, but options "
1028 "specified format '%s'", encryptfmt
);
1034 case QCOW_CRYPT_AES
:
1035 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1037 "Header reported 'aes' encryption format but "
1038 "options specify '%s'", encryptfmt
);
1042 qdict_del(encryptopts
, "format");
1043 r
->crypto_opts
= block_crypto_open_opts_init(
1044 Q_CRYPTO_BLOCK_FORMAT_QCOW
, encryptopts
, errp
);
1047 case QCOW_CRYPT_LUKS
:
1048 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1050 "Header reported 'luks' encryption format but "
1051 "options specify '%s'", encryptfmt
);
1055 qdict_del(encryptopts
, "format");
1056 r
->crypto_opts
= block_crypto_open_opts_init(
1057 Q_CRYPTO_BLOCK_FORMAT_LUKS
, encryptopts
, errp
);
1061 error_setg(errp
, "Unsupported encryption method %d",
1062 s
->crypt_method_header
);
1065 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1072 qobject_unref(encryptopts
);
1073 qemu_opts_del(opts
);
1078 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1079 Qcow2ReopenState
*r
)
1081 BDRVQcow2State
*s
= bs
->opaque
;
1084 if (s
->l2_table_cache
) {
1085 qcow2_cache_destroy(s
->l2_table_cache
);
1087 if (s
->refcount_block_cache
) {
1088 qcow2_cache_destroy(s
->refcount_block_cache
);
1090 s
->l2_table_cache
= r
->l2_table_cache
;
1091 s
->refcount_block_cache
= r
->refcount_block_cache
;
1092 s
->l2_slice_size
= r
->l2_slice_size
;
1094 s
->overlap_check
= r
->overlap_check
;
1095 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1097 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1098 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1101 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1102 cache_clean_timer_del(bs
);
1103 s
->cache_clean_interval
= r
->cache_clean_interval
;
1104 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1107 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1108 s
->crypto_opts
= r
->crypto_opts
;
1111 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1112 Qcow2ReopenState
*r
)
1114 if (r
->l2_table_cache
) {
1115 qcow2_cache_destroy(r
->l2_table_cache
);
1117 if (r
->refcount_block_cache
) {
1118 qcow2_cache_destroy(r
->refcount_block_cache
);
1120 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1123 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1124 int flags
, Error
**errp
)
1126 Qcow2ReopenState r
= {};
1129 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1131 qcow2_update_options_commit(bs
, &r
);
1133 qcow2_update_options_abort(bs
, &r
);
1139 /* Called with s->lock held. */
1140 static int coroutine_fn
qcow2_do_open(BlockDriverState
*bs
, QDict
*options
,
1141 int flags
, Error
**errp
)
1143 BDRVQcow2State
*s
= bs
->opaque
;
1144 unsigned int len
, i
;
1147 Error
*local_err
= NULL
;
1149 uint64_t l1_vm_state_index
;
1150 bool update_header
= false;
1151 bool header_updated
= false;
1153 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1155 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1158 be32_to_cpus(&header
.magic
);
1159 be32_to_cpus(&header
.version
);
1160 be64_to_cpus(&header
.backing_file_offset
);
1161 be32_to_cpus(&header
.backing_file_size
);
1162 be64_to_cpus(&header
.size
);
1163 be32_to_cpus(&header
.cluster_bits
);
1164 be32_to_cpus(&header
.crypt_method
);
1165 be64_to_cpus(&header
.l1_table_offset
);
1166 be32_to_cpus(&header
.l1_size
);
1167 be64_to_cpus(&header
.refcount_table_offset
);
1168 be32_to_cpus(&header
.refcount_table_clusters
);
1169 be64_to_cpus(&header
.snapshots_offset
);
1170 be32_to_cpus(&header
.nb_snapshots
);
1172 if (header
.magic
!= QCOW_MAGIC
) {
1173 error_setg(errp
, "Image is not in qcow2 format");
1177 if (header
.version
< 2 || header
.version
> 3) {
1178 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1183 s
->qcow_version
= header
.version
;
1185 /* Initialise cluster size */
1186 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1187 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1188 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1189 header
.cluster_bits
);
1194 s
->cluster_bits
= header
.cluster_bits
;
1195 s
->cluster_size
= 1 << s
->cluster_bits
;
1196 s
->cluster_sectors
= 1 << (s
->cluster_bits
- BDRV_SECTOR_BITS
);
1198 /* Initialise version 3 header fields */
1199 if (header
.version
== 2) {
1200 header
.incompatible_features
= 0;
1201 header
.compatible_features
= 0;
1202 header
.autoclear_features
= 0;
1203 header
.refcount_order
= 4;
1204 header
.header_length
= 72;
1206 be64_to_cpus(&header
.incompatible_features
);
1207 be64_to_cpus(&header
.compatible_features
);
1208 be64_to_cpus(&header
.autoclear_features
);
1209 be32_to_cpus(&header
.refcount_order
);
1210 be32_to_cpus(&header
.header_length
);
1212 if (header
.header_length
< 104) {
1213 error_setg(errp
, "qcow2 header too short");
1219 if (header
.header_length
> s
->cluster_size
) {
1220 error_setg(errp
, "qcow2 header exceeds cluster size");
1225 if (header
.header_length
> sizeof(header
)) {
1226 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1227 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1228 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1229 s
->unknown_header_fields_size
);
1231 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1237 if (header
.backing_file_offset
> s
->cluster_size
) {
1238 error_setg(errp
, "Invalid backing file offset");
1243 if (header
.backing_file_offset
) {
1244 ext_end
= header
.backing_file_offset
;
1246 ext_end
= 1 << header
.cluster_bits
;
1249 /* Handle feature bits */
1250 s
->incompatible_features
= header
.incompatible_features
;
1251 s
->compatible_features
= header
.compatible_features
;
1252 s
->autoclear_features
= header
.autoclear_features
;
1254 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1255 void *feature_table
= NULL
;
1256 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1257 &feature_table
, flags
, NULL
, NULL
);
1258 report_unsupported_feature(errp
, feature_table
,
1259 s
->incompatible_features
&
1260 ~QCOW2_INCOMPAT_MASK
);
1262 g_free(feature_table
);
1266 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1267 /* Corrupt images may not be written to unless they are being repaired
1269 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1270 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1277 /* Check support for various header values */
1278 if (header
.refcount_order
> 6) {
1279 error_setg(errp
, "Reference count entry width too large; may not "
1284 s
->refcount_order
= header
.refcount_order
;
1285 s
->refcount_bits
= 1 << s
->refcount_order
;
1286 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1287 s
->refcount_max
+= s
->refcount_max
- 1;
1289 s
->crypt_method_header
= header
.crypt_method
;
1290 if (s
->crypt_method_header
) {
1291 if (bdrv_uses_whitelist() &&
1292 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1294 "Use of AES-CBC encrypted qcow2 images is no longer "
1295 "supported in system emulators");
1296 error_append_hint(errp
,
1297 "You can use 'qemu-img convert' to convert your "
1298 "image to an alternative supported format, such "
1299 "as unencrypted qcow2, or raw with the LUKS "
1300 "format instead.\n");
1305 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1306 s
->crypt_physical_offset
= false;
1308 /* Assuming LUKS and any future crypt methods we
1309 * add will all use physical offsets, due to the
1310 * fact that the alternative is insecure... */
1311 s
->crypt_physical_offset
= true;
1314 bs
->encrypted
= true;
1317 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
1318 s
->l2_size
= 1 << s
->l2_bits
;
1319 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1320 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1321 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1322 bs
->total_sectors
= header
.size
/ 512;
1323 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1324 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1325 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1327 s
->refcount_table_offset
= header
.refcount_table_offset
;
1328 s
->refcount_table_size
=
1329 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1331 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1332 error_setg(errp
, "Image does not contain a reference count table");
1337 ret
= qcow2_validate_table(bs
, s
->refcount_table_offset
,
1338 header
.refcount_table_clusters
,
1339 s
->cluster_size
, QCOW_MAX_REFTABLE_SIZE
,
1340 "Reference count table", errp
);
1345 /* The total size in bytes of the snapshot table is checked in
1346 * qcow2_read_snapshots() because the size of each snapshot is
1347 * variable and we don't know it yet.
1348 * Here we only check the offset and number of snapshots. */
1349 ret
= qcow2_validate_table(bs
, header
.snapshots_offset
,
1350 header
.nb_snapshots
,
1351 sizeof(QCowSnapshotHeader
),
1352 sizeof(QCowSnapshotHeader
) * QCOW_MAX_SNAPSHOTS
,
1353 "Snapshot table", errp
);
1358 /* read the level 1 table */
1359 ret
= qcow2_validate_table(bs
, header
.l1_table_offset
,
1360 header
.l1_size
, sizeof(uint64_t),
1361 QCOW_MAX_L1_SIZE
, "Active L1 table", errp
);
1365 s
->l1_size
= header
.l1_size
;
1366 s
->l1_table_offset
= header
.l1_table_offset
;
1368 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1369 if (l1_vm_state_index
> INT_MAX
) {
1370 error_setg(errp
, "Image is too big");
1374 s
->l1_vm_state_index
= l1_vm_state_index
;
1376 /* the L1 table must contain at least enough entries to put
1377 header.size bytes */
1378 if (s
->l1_size
< s
->l1_vm_state_index
) {
1379 error_setg(errp
, "L1 table is too small");
1384 if (s
->l1_size
> 0) {
1385 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1386 ROUND_UP(s
->l1_size
* sizeof(uint64_t), 512));
1387 if (s
->l1_table
== NULL
) {
1388 error_setg(errp
, "Could not allocate L1 table");
1392 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1393 s
->l1_size
* sizeof(uint64_t));
1395 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1398 for(i
= 0;i
< s
->l1_size
; i
++) {
1399 be64_to_cpus(&s
->l1_table
[i
]);
1403 /* Parse driver-specific options */
1404 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1409 s
->cluster_cache_offset
= -1;
1412 ret
= qcow2_refcount_init(bs
);
1414 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1418 QLIST_INIT(&s
->cluster_allocs
);
1419 QTAILQ_INIT(&s
->discards
);
1421 /* read qcow2 extensions */
1422 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1423 flags
, &update_header
, &local_err
)) {
1424 error_propagate(errp
, local_err
);
1429 /* qcow2_read_extension may have set up the crypto context
1430 * if the crypt method needs a header region, some methods
1431 * don't need header extensions, so must check here
1433 if (s
->crypt_method_header
&& !s
->crypto
) {
1434 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1435 unsigned int cflags
= 0;
1436 if (flags
& BDRV_O_NO_IO
) {
1437 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1439 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1440 NULL
, NULL
, cflags
, errp
);
1445 } else if (!(flags
& BDRV_O_NO_IO
)) {
1446 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1447 s
->crypt_method_header
);
1453 /* read the backing file name */
1454 if (header
.backing_file_offset
!= 0) {
1455 len
= header
.backing_file_size
;
1456 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1457 len
>= sizeof(bs
->backing_file
)) {
1458 error_setg(errp
, "Backing file name too long");
1462 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1463 bs
->backing_file
, len
);
1465 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1468 bs
->backing_file
[len
] = '\0';
1469 s
->image_backing_file
= g_strdup(bs
->backing_file
);
1472 /* Internal snapshots */
1473 s
->snapshots_offset
= header
.snapshots_offset
;
1474 s
->nb_snapshots
= header
.nb_snapshots
;
1476 ret
= qcow2_read_snapshots(bs
);
1478 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1482 /* Clear unknown autoclear feature bits */
1483 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1485 update_header
&& !bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
);
1486 if (update_header
) {
1487 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1490 if (s
->dirty_bitmaps_loaded
) {
1491 /* It's some kind of reopen. There are no known cases where we need to
1492 * reload bitmaps in such a situation, so it's safer to skip them.
1494 * Moreover, if we have some readonly bitmaps and we are reopening for
1495 * rw we should reopen bitmaps correspondingly.
1497 if (bdrv_has_readonly_bitmaps(bs
) &&
1498 !bdrv_is_read_only(bs
) && !(bdrv_get_flags(bs
) & BDRV_O_INACTIVE
))
1500 qcow2_reopen_bitmaps_rw_hint(bs
, &header_updated
, &local_err
);
1503 header_updated
= qcow2_load_dirty_bitmaps(bs
, &local_err
);
1504 s
->dirty_bitmaps_loaded
= true;
1506 update_header
= update_header
&& !header_updated
;
1507 if (local_err
!= NULL
) {
1508 error_propagate(errp
, local_err
);
1513 if (update_header
) {
1514 ret
= qcow2_update_header(bs
);
1516 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1521 bs
->supported_zero_flags
= header
.version
>= 3 ? BDRV_REQ_MAY_UNMAP
: 0;
1523 /* Repair image if dirty */
1524 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1525 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1526 BdrvCheckResult result
= {0};
1528 ret
= qcow2_co_check_locked(bs
, &result
,
1529 BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1530 if (ret
< 0 || result
.check_errors
) {
1534 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1541 BdrvCheckResult result
= {0};
1542 qcow2_check_refcounts(bs
, &result
, 0);
1548 g_free(s
->unknown_header_fields
);
1549 cleanup_unknown_header_ext(bs
);
1550 qcow2_free_snapshots(bs
);
1551 qcow2_refcount_close(bs
);
1552 qemu_vfree(s
->l1_table
);
1553 /* else pre-write overlap checks in cache_destroy may crash */
1555 cache_clean_timer_del(bs
);
1556 if (s
->l2_table_cache
) {
1557 qcow2_cache_destroy(s
->l2_table_cache
);
1559 if (s
->refcount_block_cache
) {
1560 qcow2_cache_destroy(s
->refcount_block_cache
);
1562 qcrypto_block_free(s
->crypto
);
1563 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1567 typedef struct QCow2OpenCo
{
1568 BlockDriverState
*bs
;
1575 static void coroutine_fn
qcow2_open_entry(void *opaque
)
1577 QCow2OpenCo
*qoc
= opaque
;
1578 BDRVQcow2State
*s
= qoc
->bs
->opaque
;
1580 qemu_co_mutex_lock(&s
->lock
);
1581 qoc
->ret
= qcow2_do_open(qoc
->bs
, qoc
->options
, qoc
->flags
, qoc
->errp
);
1582 qemu_co_mutex_unlock(&s
->lock
);
1585 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1588 BDRVQcow2State
*s
= bs
->opaque
;
1597 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1603 /* Initialise locks */
1604 qemu_co_mutex_init(&s
->lock
);
1606 if (qemu_in_coroutine()) {
1607 /* From bdrv_co_create. */
1608 qcow2_open_entry(&qoc
);
1610 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry
, &qoc
));
1611 BDRV_POLL_WHILE(bs
, qoc
.ret
== -EINPROGRESS
);
1616 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1618 BDRVQcow2State
*s
= bs
->opaque
;
1620 if (bs
->encrypted
) {
1621 /* Encryption works on a sector granularity */
1622 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1624 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1625 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1628 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1629 BlockReopenQueue
*queue
, Error
**errp
)
1631 Qcow2ReopenState
*r
;
1634 r
= g_new0(Qcow2ReopenState
, 1);
1637 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1638 state
->flags
, errp
);
1643 /* We need to write out any unwritten data if we reopen read-only. */
1644 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1645 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1650 ret
= bdrv_flush(state
->bs
);
1655 ret
= qcow2_mark_clean(state
->bs
);
1664 qcow2_update_options_abort(state
->bs
, r
);
1669 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1671 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1672 g_free(state
->opaque
);
1675 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1677 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1678 g_free(state
->opaque
);
1681 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1683 bool has_new_overlap_template
=
1684 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1685 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1686 bool has_new_total_cache_size
=
1687 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1688 bool has_all_cache_options
;
1690 /* New overlap template overrides all old overlap options */
1691 if (has_new_overlap_template
) {
1692 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1693 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1694 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1695 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1696 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1697 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1698 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1699 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1700 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1701 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1704 /* New total cache size overrides all old options */
1705 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1706 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1707 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1710 qdict_join(options
, old_options
, false);
1713 * If after merging all cache size options are set, an old total size is
1714 * overwritten. Do keep all options, however, if all three are new. The
1715 * resulting error message is what we want to happen.
1717 has_all_cache_options
=
1718 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1719 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1720 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1722 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1723 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1727 static int coroutine_fn
qcow2_co_block_status(BlockDriverState
*bs
,
1729 int64_t offset
, int64_t count
,
1730 int64_t *pnum
, int64_t *map
,
1731 BlockDriverState
**file
)
1733 BDRVQcow2State
*s
= bs
->opaque
;
1734 uint64_t cluster_offset
;
1735 int index_in_cluster
, ret
;
1739 bytes
= MIN(INT_MAX
, count
);
1740 qemu_co_mutex_lock(&s
->lock
);
1741 ret
= qcow2_get_cluster_offset(bs
, offset
, &bytes
, &cluster_offset
);
1742 qemu_co_mutex_unlock(&s
->lock
);
1749 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1751 index_in_cluster
= offset
& (s
->cluster_size
- 1);
1752 *map
= cluster_offset
| index_in_cluster
;
1753 *file
= bs
->file
->bs
;
1754 status
|= BDRV_BLOCK_OFFSET_VALID
;
1756 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1757 status
|= BDRV_BLOCK_ZERO
;
1758 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1759 status
|= BDRV_BLOCK_DATA
;
1764 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1765 uint64_t bytes
, QEMUIOVector
*qiov
,
1768 BDRVQcow2State
*s
= bs
->opaque
;
1769 int offset_in_cluster
;
1771 unsigned int cur_bytes
; /* number of bytes in current iteration */
1772 uint64_t cluster_offset
= 0;
1773 uint64_t bytes_done
= 0;
1774 QEMUIOVector hd_qiov
;
1775 uint8_t *cluster_data
= NULL
;
1777 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1779 qemu_co_mutex_lock(&s
->lock
);
1781 while (bytes
!= 0) {
1783 /* prepare next request */
1784 cur_bytes
= MIN(bytes
, INT_MAX
);
1786 cur_bytes
= MIN(cur_bytes
,
1787 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1790 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1795 offset_in_cluster
= offset_into_cluster(s
, offset
);
1797 qemu_iovec_reset(&hd_qiov
);
1798 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1801 case QCOW2_CLUSTER_UNALLOCATED
:
1804 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1805 qemu_co_mutex_unlock(&s
->lock
);
1806 ret
= bdrv_co_preadv(bs
->backing
, offset
, cur_bytes
,
1808 qemu_co_mutex_lock(&s
->lock
);
1813 /* Note: in this case, no need to wait */
1814 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1818 case QCOW2_CLUSTER_ZERO_PLAIN
:
1819 case QCOW2_CLUSTER_ZERO_ALLOC
:
1820 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1823 case QCOW2_CLUSTER_COMPRESSED
:
1824 /* add AIO support for compressed blocks ? */
1825 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1830 qemu_iovec_from_buf(&hd_qiov
, 0,
1831 s
->cluster_cache
+ offset_in_cluster
,
1835 case QCOW2_CLUSTER_NORMAL
:
1836 if ((cluster_offset
& 511) != 0) {
1841 if (bs
->encrypted
) {
1845 * For encrypted images, read everything into a temporary
1846 * contiguous buffer on which the AES functions can work.
1848 if (!cluster_data
) {
1850 qemu_try_blockalign(bs
->file
->bs
,
1851 QCOW_MAX_CRYPT_CLUSTERS
1853 if (cluster_data
== NULL
) {
1859 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1860 qemu_iovec_reset(&hd_qiov
);
1861 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1864 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1865 qemu_co_mutex_unlock(&s
->lock
);
1866 ret
= bdrv_co_preadv(bs
->file
,
1867 cluster_offset
+ offset_in_cluster
,
1868 cur_bytes
, &hd_qiov
, 0);
1869 qemu_co_mutex_lock(&s
->lock
);
1873 if (bs
->encrypted
) {
1875 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1876 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1877 if (qcrypto_block_decrypt(s
->crypto
,
1878 (s
->crypt_physical_offset
?
1879 cluster_offset
+ offset_in_cluster
:
1887 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1892 g_assert_not_reached();
1898 offset
+= cur_bytes
;
1899 bytes_done
+= cur_bytes
;
1904 qemu_co_mutex_unlock(&s
->lock
);
1906 qemu_iovec_destroy(&hd_qiov
);
1907 qemu_vfree(cluster_data
);
1912 /* Check if it's possible to merge a write request with the writing of
1913 * the data from the COW regions */
1914 static bool merge_cow(uint64_t offset
, unsigned bytes
,
1915 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
1919 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
1920 /* If both COW regions are empty then there's nothing to merge */
1921 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
1925 /* The data (middle) region must be immediately after the
1927 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
1931 /* The end region must be immediately after the data (middle)
1933 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
1937 /* Make sure that adding both COW regions to the QEMUIOVector
1938 * does not exceed IOV_MAX */
1939 if (hd_qiov
->niov
> IOV_MAX
- 2) {
1943 m
->data_qiov
= hd_qiov
;
1950 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1951 uint64_t bytes
, QEMUIOVector
*qiov
,
1954 BDRVQcow2State
*s
= bs
->opaque
;
1955 int offset_in_cluster
;
1957 unsigned int cur_bytes
; /* number of sectors in current iteration */
1958 uint64_t cluster_offset
;
1959 QEMUIOVector hd_qiov
;
1960 uint64_t bytes_done
= 0;
1961 uint8_t *cluster_data
= NULL
;
1962 QCowL2Meta
*l2meta
= NULL
;
1964 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
1966 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1968 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1970 qemu_co_mutex_lock(&s
->lock
);
1972 while (bytes
!= 0) {
1976 trace_qcow2_writev_start_part(qemu_coroutine_self());
1977 offset_in_cluster
= offset_into_cluster(s
, offset
);
1978 cur_bytes
= MIN(bytes
, INT_MAX
);
1979 if (bs
->encrypted
) {
1980 cur_bytes
= MIN(cur_bytes
,
1981 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
1982 - offset_in_cluster
);
1985 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
1986 &cluster_offset
, &l2meta
);
1991 assert((cluster_offset
& 511) == 0);
1993 qemu_iovec_reset(&hd_qiov
);
1994 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1996 if (bs
->encrypted
) {
1998 if (!cluster_data
) {
1999 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
2000 QCOW_MAX_CRYPT_CLUSTERS
2002 if (cluster_data
== NULL
) {
2008 assert(hd_qiov
.size
<=
2009 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2010 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
2012 if (qcrypto_block_encrypt(s
->crypto
,
2013 (s
->crypt_physical_offset
?
2014 cluster_offset
+ offset_in_cluster
:
2017 cur_bytes
, NULL
) < 0) {
2022 qemu_iovec_reset(&hd_qiov
);
2023 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
2026 ret
= qcow2_pre_write_overlap_check(bs
, 0,
2027 cluster_offset
+ offset_in_cluster
, cur_bytes
);
2032 /* If we need to do COW, check if it's possible to merge the
2033 * writing of the guest data together with that of the COW regions.
2034 * If it's not possible (or not necessary) then write the
2035 * guest data now. */
2036 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
2037 qemu_co_mutex_unlock(&s
->lock
);
2038 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
2039 trace_qcow2_writev_data(qemu_coroutine_self(),
2040 cluster_offset
+ offset_in_cluster
);
2041 ret
= bdrv_co_pwritev(bs
->file
,
2042 cluster_offset
+ offset_in_cluster
,
2043 cur_bytes
, &hd_qiov
, 0);
2044 qemu_co_mutex_lock(&s
->lock
);
2050 while (l2meta
!= NULL
) {
2053 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
2058 /* Take the request off the list of running requests */
2059 if (l2meta
->nb_clusters
!= 0) {
2060 QLIST_REMOVE(l2meta
, next_in_flight
);
2063 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2065 next
= l2meta
->next
;
2071 offset
+= cur_bytes
;
2072 bytes_done
+= cur_bytes
;
2073 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2078 while (l2meta
!= NULL
) {
2081 if (l2meta
->nb_clusters
!= 0) {
2082 QLIST_REMOVE(l2meta
, next_in_flight
);
2084 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2086 next
= l2meta
->next
;
2091 qemu_co_mutex_unlock(&s
->lock
);
2093 qemu_iovec_destroy(&hd_qiov
);
2094 qemu_vfree(cluster_data
);
2095 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2100 static int qcow2_inactivate(BlockDriverState
*bs
)
2102 BDRVQcow2State
*s
= bs
->opaque
;
2103 int ret
, result
= 0;
2104 Error
*local_err
= NULL
;
2106 qcow2_store_persistent_dirty_bitmaps(bs
, &local_err
);
2107 if (local_err
!= NULL
) {
2109 error_report_err(local_err
);
2110 error_report("Persistent bitmaps are lost for node '%s'",
2111 bdrv_get_device_or_node_name(bs
));
2114 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2117 error_report("Failed to flush the L2 table cache: %s",
2121 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2124 error_report("Failed to flush the refcount block cache: %s",
2129 qcow2_mark_clean(bs
);
2135 static void qcow2_close(BlockDriverState
*bs
)
2137 BDRVQcow2State
*s
= bs
->opaque
;
2138 qemu_vfree(s
->l1_table
);
2139 /* else pre-write overlap checks in cache_destroy may crash */
2142 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2143 qcow2_inactivate(bs
);
2146 cache_clean_timer_del(bs
);
2147 qcow2_cache_destroy(s
->l2_table_cache
);
2148 qcow2_cache_destroy(s
->refcount_block_cache
);
2150 qcrypto_block_free(s
->crypto
);
2153 g_free(s
->unknown_header_fields
);
2154 cleanup_unknown_header_ext(bs
);
2156 g_free(s
->image_backing_file
);
2157 g_free(s
->image_backing_format
);
2159 g_free(s
->cluster_cache
);
2160 qemu_vfree(s
->cluster_data
);
2161 qcow2_refcount_close(bs
);
2162 qcow2_free_snapshots(bs
);
2165 static void coroutine_fn
qcow2_co_invalidate_cache(BlockDriverState
*bs
,
2168 BDRVQcow2State
*s
= bs
->opaque
;
2169 int flags
= s
->flags
;
2170 QCryptoBlock
*crypto
= NULL
;
2172 Error
*local_err
= NULL
;
2176 * Backing files are read-only which makes all of their metadata immutable,
2177 * that means we don't have to worry about reopening them here.
2185 memset(s
, 0, sizeof(BDRVQcow2State
));
2186 options
= qdict_clone_shallow(bs
->options
);
2188 flags
&= ~BDRV_O_INACTIVE
;
2189 qemu_co_mutex_lock(&s
->lock
);
2190 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2191 qemu_co_mutex_unlock(&s
->lock
);
2192 qobject_unref(options
);
2194 error_propagate(errp
, local_err
);
2195 error_prepend(errp
, "Could not reopen qcow2 layer: ");
2198 } else if (ret
< 0) {
2199 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2207 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2208 size_t len
, size_t buflen
)
2210 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2211 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2213 if (buflen
< ext_len
) {
2217 *ext_backing_fmt
= (QCowExtension
) {
2218 .magic
= cpu_to_be32(magic
),
2219 .len
= cpu_to_be32(len
),
2223 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2230 * Updates the qcow2 header, including the variable length parts of it, i.e.
2231 * the backing file name and all extensions. qcow2 was not designed to allow
2232 * such changes, so if we run out of space (we can only use the first cluster)
2233 * this function may fail.
2235 * Returns 0 on success, -errno in error cases.
2237 int qcow2_update_header(BlockDriverState
*bs
)
2239 BDRVQcow2State
*s
= bs
->opaque
;
2242 size_t buflen
= s
->cluster_size
;
2244 uint64_t total_size
;
2245 uint32_t refcount_table_clusters
;
2246 size_t header_length
;
2247 Qcow2UnknownHeaderExtension
*uext
;
2249 buf
= qemu_blockalign(bs
, buflen
);
2251 /* Header structure */
2252 header
= (QCowHeader
*) buf
;
2254 if (buflen
< sizeof(*header
)) {
2259 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2260 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2261 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2263 *header
= (QCowHeader
) {
2264 /* Version 2 fields */
2265 .magic
= cpu_to_be32(QCOW_MAGIC
),
2266 .version
= cpu_to_be32(s
->qcow_version
),
2267 .backing_file_offset
= 0,
2268 .backing_file_size
= 0,
2269 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2270 .size
= cpu_to_be64(total_size
),
2271 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2272 .l1_size
= cpu_to_be32(s
->l1_size
),
2273 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2274 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2275 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2276 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2277 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2279 /* Version 3 fields */
2280 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2281 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2282 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2283 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2284 .header_length
= cpu_to_be32(header_length
),
2287 /* For older versions, write a shorter header */
2288 switch (s
->qcow_version
) {
2290 ret
= offsetof(QCowHeader
, incompatible_features
);
2293 ret
= sizeof(*header
);
2302 memset(buf
, 0, buflen
);
2304 /* Preserve any unknown field in the header */
2305 if (s
->unknown_header_fields_size
) {
2306 if (buflen
< s
->unknown_header_fields_size
) {
2311 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2312 buf
+= s
->unknown_header_fields_size
;
2313 buflen
-= s
->unknown_header_fields_size
;
2316 /* Backing file format header extension */
2317 if (s
->image_backing_format
) {
2318 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2319 s
->image_backing_format
,
2320 strlen(s
->image_backing_format
),
2330 /* Full disk encryption header pointer extension */
2331 if (s
->crypto_header
.offset
!= 0) {
2332 cpu_to_be64s(&s
->crypto_header
.offset
);
2333 cpu_to_be64s(&s
->crypto_header
.length
);
2334 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2335 &s
->crypto_header
, sizeof(s
->crypto_header
),
2337 be64_to_cpus(&s
->crypto_header
.offset
);
2338 be64_to_cpus(&s
->crypto_header
.length
);
2347 if (s
->qcow_version
>= 3) {
2348 Qcow2Feature features
[] = {
2350 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2351 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2352 .name
= "dirty bit",
2355 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2356 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2357 .name
= "corrupt bit",
2360 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2361 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2362 .name
= "lazy refcounts",
2366 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2367 features
, sizeof(features
), buflen
);
2375 /* Bitmap extension */
2376 if (s
->nb_bitmaps
> 0) {
2377 Qcow2BitmapHeaderExt bitmaps_header
= {
2378 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2379 .bitmap_directory_size
=
2380 cpu_to_be64(s
->bitmap_directory_size
),
2381 .bitmap_directory_offset
=
2382 cpu_to_be64(s
->bitmap_directory_offset
)
2384 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2385 &bitmaps_header
, sizeof(bitmaps_header
),
2394 /* Keep unknown header extensions */
2395 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2396 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2405 /* End of header extensions */
2406 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2414 /* Backing file name */
2415 if (s
->image_backing_file
) {
2416 size_t backing_file_len
= strlen(s
->image_backing_file
);
2418 if (buflen
< backing_file_len
) {
2423 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2424 strncpy(buf
, s
->image_backing_file
, buflen
);
2426 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2427 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2430 /* Write the new header */
2431 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2442 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2443 const char *backing_file
, const char *backing_fmt
)
2445 BDRVQcow2State
*s
= bs
->opaque
;
2447 if (backing_file
&& strlen(backing_file
) > 1023) {
2451 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2452 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2454 g_free(s
->image_backing_file
);
2455 g_free(s
->image_backing_format
);
2457 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2458 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2460 return qcow2_update_header(bs
);
2463 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2465 if (g_str_equal(encryptfmt
, "luks")) {
2466 return QCOW_CRYPT_LUKS
;
2467 } else if (g_str_equal(encryptfmt
, "aes")) {
2468 return QCOW_CRYPT_AES
;
2474 static int qcow2_set_up_encryption(BlockDriverState
*bs
,
2475 QCryptoBlockCreateOptions
*cryptoopts
,
2478 BDRVQcow2State
*s
= bs
->opaque
;
2479 QCryptoBlock
*crypto
= NULL
;
2482 switch (cryptoopts
->format
) {
2483 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
2484 fmt
= QCOW_CRYPT_LUKS
;
2486 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
2487 fmt
= QCOW_CRYPT_AES
;
2490 error_setg(errp
, "Crypto format not supported in qcow2");
2494 s
->crypt_method_header
= fmt
;
2496 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2497 qcow2_crypto_hdr_init_func
,
2498 qcow2_crypto_hdr_write_func
,
2504 ret
= qcow2_update_header(bs
);
2506 error_setg_errno(errp
, -ret
, "Could not write encryption header");
2512 qcrypto_block_free(crypto
);
2517 typedef struct PreallocCo
{
2518 BlockDriverState
*bs
;
2520 uint64_t new_length
;
2526 * Preallocates metadata structures for data clusters between @offset (in the
2527 * guest disk) and @new_length (which is thus generally the new guest disk
2530 * Returns: 0 on success, -errno on failure.
2532 static void coroutine_fn
preallocate_co(void *opaque
)
2534 PreallocCo
*params
= opaque
;
2535 BlockDriverState
*bs
= params
->bs
;
2536 uint64_t offset
= params
->offset
;
2537 uint64_t new_length
= params
->new_length
;
2538 BDRVQcow2State
*s
= bs
->opaque
;
2540 uint64_t host_offset
= 0;
2541 unsigned int cur_bytes
;
2545 qemu_co_mutex_lock(&s
->lock
);
2547 assert(offset
<= new_length
);
2548 bytes
= new_length
- offset
;
2551 cur_bytes
= MIN(bytes
, INT_MAX
);
2552 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2553 &host_offset
, &meta
);
2559 QCowL2Meta
*next
= meta
->next
;
2561 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2563 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2564 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2568 /* There are no dependent requests, but we need to remove our
2569 * request from the list of in-flight requests */
2570 QLIST_REMOVE(meta
, next_in_flight
);
2576 /* TODO Preallocate data if requested */
2579 offset
+= cur_bytes
;
2583 * It is expected that the image file is large enough to actually contain
2584 * all of the allocated clusters (otherwise we get failing reads after
2585 * EOF). Extend the image to the last allocated sector.
2587 if (host_offset
!= 0) {
2589 ret
= bdrv_pwrite(bs
->file
, (host_offset
+ cur_bytes
) - 1,
2599 qemu_co_mutex_unlock(&s
->lock
);
2603 static int preallocate(BlockDriverState
*bs
,
2604 uint64_t offset
, uint64_t new_length
)
2606 PreallocCo params
= {
2609 .new_length
= new_length
,
2610 .ret
= -EINPROGRESS
,
2613 if (qemu_in_coroutine()) {
2614 preallocate_co(¶ms
);
2616 Coroutine
*co
= qemu_coroutine_create(preallocate_co
, ¶ms
);
2617 bdrv_coroutine_enter(bs
, co
);
2618 BDRV_POLL_WHILE(bs
, params
.ret
== -EINPROGRESS
);
2623 /* qcow2_refcount_metadata_size:
2624 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2625 * @cluster_size: size of a cluster, in bytes
2626 * @refcount_order: refcount bits power-of-2 exponent
2627 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2630 * Returns: Number of bytes required for refcount blocks and table metadata.
2632 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
2633 int refcount_order
, bool generous_increase
,
2634 uint64_t *refblock_count
)
2637 * Every host cluster is reference-counted, including metadata (even
2638 * refcount metadata is recursively included).
2640 * An accurate formula for the size of refcount metadata size is difficult
2641 * to derive. An easier method of calculation is finding the fixed point
2642 * where no further refcount blocks or table clusters are required to
2643 * reference count every cluster.
2645 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
2646 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
2647 int64_t table
= 0; /* number of refcount table clusters */
2648 int64_t blocks
= 0; /* number of refcount block clusters */
2654 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
2655 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
2656 n
= clusters
+ blocks
+ table
;
2658 if (n
== last
&& generous_increase
) {
2659 clusters
+= DIV_ROUND_UP(table
, 2);
2660 n
= 0; /* force another loop */
2661 generous_increase
= false;
2663 } while (n
!= last
);
2665 if (refblock_count
) {
2666 *refblock_count
= blocks
;
2669 return (blocks
+ table
) * cluster_size
;
2673 * qcow2_calc_prealloc_size:
2674 * @total_size: virtual disk size in bytes
2675 * @cluster_size: cluster size in bytes
2676 * @refcount_order: refcount bits power-of-2 exponent
2678 * Returns: Total number of bytes required for the fully allocated image
2679 * (including metadata).
2681 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
2682 size_t cluster_size
,
2685 int64_t meta_size
= 0;
2686 uint64_t nl1e
, nl2e
;
2687 int64_t aligned_total_size
= ROUND_UP(total_size
, cluster_size
);
2689 /* header: 1 cluster */
2690 meta_size
+= cluster_size
;
2692 /* total size of L2 tables */
2693 nl2e
= aligned_total_size
/ cluster_size
;
2694 nl2e
= ROUND_UP(nl2e
, cluster_size
/ sizeof(uint64_t));
2695 meta_size
+= nl2e
* sizeof(uint64_t);
2697 /* total size of L1 tables */
2698 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2699 nl1e
= ROUND_UP(nl1e
, cluster_size
/ sizeof(uint64_t));
2700 meta_size
+= nl1e
* sizeof(uint64_t);
2702 /* total size of refcount table and blocks */
2703 meta_size
+= qcow2_refcount_metadata_size(
2704 (meta_size
+ aligned_total_size
) / cluster_size
,
2705 cluster_size
, refcount_order
, false, NULL
);
2707 return meta_size
+ aligned_total_size
;
2710 static bool validate_cluster_size(size_t cluster_size
, Error
**errp
)
2712 int cluster_bits
= ctz32(cluster_size
);
2713 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2714 (1 << cluster_bits
) != cluster_size
)
2716 error_setg(errp
, "Cluster size must be a power of two between %d and "
2717 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2723 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
2725 size_t cluster_size
;
2727 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2728 DEFAULT_CLUSTER_SIZE
);
2729 if (!validate_cluster_size(cluster_size
, errp
)) {
2732 return cluster_size
;
2735 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
2740 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2742 ret
= 3; /* default */
2743 } else if (!strcmp(buf
, "0.10")) {
2745 } else if (!strcmp(buf
, "1.1")) {
2748 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2755 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
2758 uint64_t refcount_bits
;
2760 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
2761 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2762 error_setg(errp
, "Refcount width must be a power of two and may not "
2767 if (version
< 3 && refcount_bits
!= 16) {
2768 error_setg(errp
, "Different refcount widths than 16 bits require "
2769 "compatibility level 1.1 or above (use compat=1.1 or "
2774 return refcount_bits
;
2777 static int coroutine_fn
2778 qcow2_co_create(BlockdevCreateOptions
*create_options
, Error
**errp
)
2780 BlockdevCreateOptionsQcow2
*qcow2_opts
;
2784 * Open the image file and write a minimal qcow2 header.
2786 * We keep things simple and start with a zero-sized image. We also
2787 * do without refcount blocks or a L1 table for now. We'll fix the
2788 * inconsistency later.
2790 * We do need a refcount table because growing the refcount table means
2791 * allocating two new refcount blocks - the seconds of which would be at
2792 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2793 * size for any qcow2 image.
2795 BlockBackend
*blk
= NULL
;
2796 BlockDriverState
*bs
= NULL
;
2798 size_t cluster_size
;
2801 uint64_t* refcount_table
;
2802 Error
*local_err
= NULL
;
2805 assert(create_options
->driver
== BLOCKDEV_DRIVER_QCOW2
);
2806 qcow2_opts
= &create_options
->u
.qcow2
;
2808 bs
= bdrv_open_blockdev_ref(qcow2_opts
->file
, errp
);
2813 /* Validate options and set default values */
2814 if (!QEMU_IS_ALIGNED(qcow2_opts
->size
, BDRV_SECTOR_SIZE
)) {
2815 error_setg(errp
, "Image size must be a multiple of 512 bytes");
2820 if (qcow2_opts
->has_version
) {
2821 switch (qcow2_opts
->version
) {
2822 case BLOCKDEV_QCOW2_VERSION_V2
:
2825 case BLOCKDEV_QCOW2_VERSION_V3
:
2829 g_assert_not_reached();
2835 if (qcow2_opts
->has_cluster_size
) {
2836 cluster_size
= qcow2_opts
->cluster_size
;
2838 cluster_size
= DEFAULT_CLUSTER_SIZE
;
2841 if (!validate_cluster_size(cluster_size
, errp
)) {
2846 if (!qcow2_opts
->has_preallocation
) {
2847 qcow2_opts
->preallocation
= PREALLOC_MODE_OFF
;
2849 if (qcow2_opts
->has_backing_file
&&
2850 qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
)
2852 error_setg(errp
, "Backing file and preallocation cannot be used at "
2857 if (qcow2_opts
->has_backing_fmt
&& !qcow2_opts
->has_backing_file
) {
2858 error_setg(errp
, "Backing format cannot be used without backing file");
2863 if (!qcow2_opts
->has_lazy_refcounts
) {
2864 qcow2_opts
->lazy_refcounts
= false;
2866 if (version
< 3 && qcow2_opts
->lazy_refcounts
) {
2867 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2868 "level 1.1 and above (use version=v3 or greater)");
2873 if (!qcow2_opts
->has_refcount_bits
) {
2874 qcow2_opts
->refcount_bits
= 16;
2876 if (qcow2_opts
->refcount_bits
> 64 ||
2877 !is_power_of_2(qcow2_opts
->refcount_bits
))
2879 error_setg(errp
, "Refcount width must be a power of two and may not "
2884 if (version
< 3 && qcow2_opts
->refcount_bits
!= 16) {
2885 error_setg(errp
, "Different refcount widths than 16 bits require "
2886 "compatibility level 1.1 or above (use version=v3 or "
2891 refcount_order
= ctz32(qcow2_opts
->refcount_bits
);
2894 /* Create BlockBackend to write to the image */
2895 blk
= blk_new(BLK_PERM_WRITE
| BLK_PERM_RESIZE
, BLK_PERM_ALL
);
2896 ret
= blk_insert_bs(blk
, bs
, errp
);
2900 blk_set_allow_write_beyond_eof(blk
, true);
2902 /* Clear the protocol layer and preallocate it if necessary */
2903 ret
= blk_truncate(blk
, 0, PREALLOC_MODE_OFF
, errp
);
2908 if (qcow2_opts
->preallocation
== PREALLOC_MODE_FULL
||
2909 qcow2_opts
->preallocation
== PREALLOC_MODE_FALLOC
)
2911 int64_t prealloc_size
=
2912 qcow2_calc_prealloc_size(qcow2_opts
->size
, cluster_size
,
2915 ret
= blk_truncate(blk
, prealloc_size
, qcow2_opts
->preallocation
, errp
);
2921 /* Write the header */
2922 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2923 header
= g_malloc0(cluster_size
);
2924 *header
= (QCowHeader
) {
2925 .magic
= cpu_to_be32(QCOW_MAGIC
),
2926 .version
= cpu_to_be32(version
),
2927 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
2928 .size
= cpu_to_be64(0),
2929 .l1_table_offset
= cpu_to_be64(0),
2930 .l1_size
= cpu_to_be32(0),
2931 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2932 .refcount_table_clusters
= cpu_to_be32(1),
2933 .refcount_order
= cpu_to_be32(refcount_order
),
2934 .header_length
= cpu_to_be32(sizeof(*header
)),
2937 /* We'll update this to correct value later */
2938 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2940 if (qcow2_opts
->lazy_refcounts
) {
2941 header
->compatible_features
|=
2942 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2945 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2948 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2952 /* Write a refcount table with one refcount block */
2953 refcount_table
= g_malloc0(2 * cluster_size
);
2954 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2955 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2956 g_free(refcount_table
);
2959 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2967 * And now open the image and make it consistent first (i.e. increase the
2968 * refcount of the cluster that is occupied by the header and the refcount
2971 options
= qdict_new();
2972 qdict_put_str(options
, "driver", "qcow2");
2973 qdict_put_str(options
, "file", bs
->node_name
);
2974 blk
= blk_new_open(NULL
, NULL
, options
,
2975 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
2978 error_propagate(errp
, local_err
);
2983 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2985 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2986 "header and refcount table");
2989 } else if (ret
!= 0) {
2990 error_report("Huh, first cluster in empty image is already in use?");
2994 /* Create a full header (including things like feature table) */
2995 ret
= qcow2_update_header(blk_bs(blk
));
2997 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
3001 /* Okay, now that we have a valid image, let's give it the right size */
3002 ret
= blk_truncate(blk
, qcow2_opts
->size
, PREALLOC_MODE_OFF
, errp
);
3004 error_prepend(errp
, "Could not resize image: ");
3008 /* Want a backing file? There you go.*/
3009 if (qcow2_opts
->has_backing_file
) {
3010 const char *backing_format
= NULL
;
3012 if (qcow2_opts
->has_backing_fmt
) {
3013 backing_format
= BlockdevDriver_str(qcow2_opts
->backing_fmt
);
3016 ret
= bdrv_change_backing_file(blk_bs(blk
), qcow2_opts
->backing_file
,
3019 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
3020 "with format '%s'", qcow2_opts
->backing_file
,
3026 /* Want encryption? There you go. */
3027 if (qcow2_opts
->has_encrypt
) {
3028 ret
= qcow2_set_up_encryption(blk_bs(blk
), qcow2_opts
->encrypt
, errp
);
3034 /* And if we're supposed to preallocate metadata, do that now */
3035 if (qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
) {
3036 ret
= preallocate(blk_bs(blk
), 0, qcow2_opts
->size
);
3038 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
3046 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3047 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3048 * have to setup decryption context. We're not doing any I/O on the top
3049 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3052 options
= qdict_new();
3053 qdict_put_str(options
, "driver", "qcow2");
3054 qdict_put_str(options
, "file", bs
->node_name
);
3055 blk
= blk_new_open(NULL
, NULL
, options
,
3056 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
3059 error_propagate(errp
, local_err
);
3071 static int coroutine_fn
qcow2_co_create_opts(const char *filename
, QemuOpts
*opts
,
3074 BlockdevCreateOptions
*create_options
= NULL
;
3075 QDict
*qdict
= NULL
;
3078 BlockDriverState
*bs
= NULL
;
3079 Error
*local_err
= NULL
;
3083 /* Only the keyval visitor supports the dotted syntax needed for
3084 * encryption, so go through a QDict before getting a QAPI type. Ignore
3085 * options meant for the protocol layer so that the visitor doesn't
3087 qdict
= qemu_opts_to_qdict_filtered(opts
, NULL
, bdrv_qcow2
.create_opts
,
3090 /* Handle encryption options */
3091 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT
);
3092 if (val
&& !strcmp(val
, "on")) {
3093 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT
, "qcow");
3094 } else if (val
&& !strcmp(val
, "off")) {
3095 qdict_del(qdict
, BLOCK_OPT_ENCRYPT
);
3098 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
);
3099 if (val
&& !strcmp(val
, "aes")) {
3100 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
, "qcow");
3103 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3104 * version=v2/v3 below. */
3105 val
= qdict_get_try_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
);
3106 if (val
&& !strcmp(val
, "0.10")) {
3107 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v2");
3108 } else if (val
&& !strcmp(val
, "1.1")) {
3109 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v3");
3112 /* Change legacy command line options into QMP ones */
3113 static const QDictRenames opt_renames
[] = {
3114 { BLOCK_OPT_BACKING_FILE
, "backing-file" },
3115 { BLOCK_OPT_BACKING_FMT
, "backing-fmt" },
3116 { BLOCK_OPT_CLUSTER_SIZE
, "cluster-size" },
3117 { BLOCK_OPT_LAZY_REFCOUNTS
, "lazy-refcounts" },
3118 { BLOCK_OPT_REFCOUNT_BITS
, "refcount-bits" },
3119 { BLOCK_OPT_ENCRYPT
, BLOCK_OPT_ENCRYPT_FORMAT
},
3120 { BLOCK_OPT_COMPAT_LEVEL
, "version" },
3124 if (!qdict_rename_keys(qdict
, opt_renames
, errp
)) {
3129 /* Create and open the file (protocol layer) */
3130 ret
= bdrv_create_file(filename
, opts
, errp
);
3135 bs
= bdrv_open(filename
, NULL
, NULL
,
3136 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
, errp
);
3142 /* Set 'driver' and 'node' options */
3143 qdict_put_str(qdict
, "driver", "qcow2");
3144 qdict_put_str(qdict
, "file", bs
->node_name
);
3146 /* Now get the QAPI type BlockdevCreateOptions */
3147 qobj
= qdict_crumple(qdict
, errp
);
3148 qobject_unref(qdict
);
3149 qdict
= qobject_to(QDict
, qobj
);
3150 if (qdict
== NULL
) {
3155 v
= qobject_input_visitor_new_keyval(QOBJECT(qdict
));
3156 visit_type_BlockdevCreateOptions(v
, NULL
, &create_options
, &local_err
);
3160 error_propagate(errp
, local_err
);
3165 /* Silently round up size */
3166 create_options
->u
.qcow2
.size
= ROUND_UP(create_options
->u
.qcow2
.size
,
3169 /* Create the qcow2 image (format layer) */
3170 ret
= qcow2_co_create(create_options
, errp
);
3177 qobject_unref(qdict
);
3179 qapi_free_BlockdevCreateOptions(create_options
);
3184 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3189 /* Clamp to image length, before checking status of underlying sectors */
3190 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3191 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3197 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3198 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3201 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3202 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3205 BDRVQcow2State
*s
= bs
->opaque
;
3207 uint32_t head
= offset
% s
->cluster_size
;
3208 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3210 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3211 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3219 assert(head
+ bytes
<= s
->cluster_size
);
3221 /* check whether remainder of cluster already reads as zero */
3222 if (!(is_zero(bs
, offset
- head
, head
) &&
3223 is_zero(bs
, offset
+ bytes
,
3224 tail
? s
->cluster_size
- tail
: 0))) {
3228 qemu_co_mutex_lock(&s
->lock
);
3229 /* We can have new write after previous check */
3230 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3231 bytes
= s
->cluster_size
;
3232 nr
= s
->cluster_size
;
3233 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3234 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3235 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3236 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3237 qemu_co_mutex_unlock(&s
->lock
);
3241 qemu_co_mutex_lock(&s
->lock
);
3244 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3246 /* Whatever is left can use real zero clusters */
3247 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3248 qemu_co_mutex_unlock(&s
->lock
);
3253 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3254 int64_t offset
, int bytes
)
3257 BDRVQcow2State
*s
= bs
->opaque
;
3259 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3260 assert(bytes
< s
->cluster_size
);
3261 /* Ignore partial clusters, except for the special case of the
3262 * complete partial cluster at the end of an unaligned file */
3263 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3264 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3269 qemu_co_mutex_lock(&s
->lock
);
3270 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3272 qemu_co_mutex_unlock(&s
->lock
);
3276 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
,
3277 PreallocMode prealloc
, Error
**errp
)
3279 BDRVQcow2State
*s
= bs
->opaque
;
3280 uint64_t old_length
;
3281 int64_t new_l1_size
;
3284 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3285 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3287 error_setg(errp
, "Unsupported preallocation mode '%s'",
3288 PreallocMode_str(prealloc
));
3293 error_setg(errp
, "The new size must be a multiple of 512");
3297 /* cannot proceed if image has snapshots */
3298 if (s
->nb_snapshots
) {
3299 error_setg(errp
, "Can't resize an image which has snapshots");
3303 /* cannot proceed if image has bitmaps */
3304 if (s
->nb_bitmaps
) {
3305 /* TODO: resize bitmaps in the image */
3306 error_setg(errp
, "Can't resize an image which has bitmaps");
3310 old_length
= bs
->total_sectors
* 512;
3311 new_l1_size
= size_to_l1(s
, offset
);
3313 if (offset
< old_length
) {
3314 int64_t last_cluster
, old_file_size
;
3315 if (prealloc
!= PREALLOC_MODE_OFF
) {
3317 "Preallocation can't be used for shrinking an image");
3321 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3322 old_length
- ROUND_UP(offset
,
3324 QCOW2_DISCARD_ALWAYS
, true);
3326 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3330 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
3332 error_setg_errno(errp
, -ret
,
3333 "Failed to reduce the number of L2 tables");
3337 ret
= qcow2_shrink_reftable(bs
);
3339 error_setg_errno(errp
, -ret
,
3340 "Failed to discard unused refblocks");
3344 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3345 if (old_file_size
< 0) {
3346 error_setg_errno(errp
, -old_file_size
,
3347 "Failed to inquire current file length");
3348 return old_file_size
;
3350 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
3351 if (last_cluster
< 0) {
3352 error_setg_errno(errp
, -last_cluster
,
3353 "Failed to find the last cluster");
3354 return last_cluster
;
3356 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
3357 Error
*local_err
= NULL
;
3359 bdrv_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
3360 PREALLOC_MODE_OFF
, &local_err
);
3362 warn_reportf_err(local_err
,
3363 "Failed to truncate the tail of the image: ");
3367 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
3369 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
3375 case PREALLOC_MODE_OFF
:
3378 case PREALLOC_MODE_METADATA
:
3379 ret
= preallocate(bs
, old_length
, offset
);
3381 error_setg_errno(errp
, -ret
, "Preallocation failed");
3386 case PREALLOC_MODE_FALLOC
:
3387 case PREALLOC_MODE_FULL
:
3389 int64_t allocation_start
, host_offset
, guest_offset
;
3390 int64_t clusters_allocated
;
3391 int64_t old_file_size
, new_file_size
;
3392 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
3394 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3395 if (old_file_size
< 0) {
3396 error_setg_errno(errp
, -old_file_size
,
3397 "Failed to inquire current file length");
3398 return old_file_size
;
3400 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
3402 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
3405 /* This is an overestimation; we will not actually allocate space for
3406 * these in the file but just make sure the new refcount structures are
3407 * able to cover them so we will not have to allocate new refblocks
3408 * while entering the data blocks in the potentially new L2 tables.
3409 * (We do not actually care where the L2 tables are placed. Maybe they
3410 * are already allocated or they can be placed somewhere before
3411 * @old_file_size. It does not matter because they will be fully
3412 * allocated automatically, so they do not need to be covered by the
3413 * preallocation. All that matters is that we will not have to allocate
3414 * new refcount structures for them.) */
3415 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
3416 s
->cluster_size
/ sizeof(uint64_t));
3417 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3418 * table for a potential head/tail */
3421 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
3422 nb_new_data_clusters
+
3425 if (allocation_start
< 0) {
3426 error_setg_errno(errp
, -allocation_start
,
3427 "Failed to resize refcount structures");
3428 return allocation_start
;
3431 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
3432 nb_new_data_clusters
);
3433 if (clusters_allocated
< 0) {
3434 error_setg_errno(errp
, -clusters_allocated
,
3435 "Failed to allocate data clusters");
3436 return -clusters_allocated
;
3439 assert(clusters_allocated
== nb_new_data_clusters
);
3441 /* Allocate the data area */
3442 new_file_size
= allocation_start
+
3443 nb_new_data_clusters
* s
->cluster_size
;
3444 ret
= bdrv_truncate(bs
->file
, new_file_size
, prealloc
, errp
);
3446 error_prepend(errp
, "Failed to resize underlying file: ");
3447 qcow2_free_clusters(bs
, allocation_start
,
3448 nb_new_data_clusters
* s
->cluster_size
,
3449 QCOW2_DISCARD_OTHER
);
3453 /* Create the necessary L2 entries */
3454 host_offset
= allocation_start
;
3455 guest_offset
= old_length
;
3456 while (nb_new_data_clusters
) {
3457 int64_t nb_clusters
= MIN(
3458 nb_new_data_clusters
,
3459 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
3460 QCowL2Meta allocation
= {
3461 .offset
= guest_offset
,
3462 .alloc_offset
= host_offset
,
3463 .nb_clusters
= nb_clusters
,
3465 qemu_co_queue_init(&allocation
.dependent_requests
);
3467 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
3469 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
3470 qcow2_free_clusters(bs
, host_offset
,
3471 nb_new_data_clusters
* s
->cluster_size
,
3472 QCOW2_DISCARD_OTHER
);
3476 guest_offset
+= nb_clusters
* s
->cluster_size
;
3477 host_offset
+= nb_clusters
* s
->cluster_size
;
3478 nb_new_data_clusters
-= nb_clusters
;
3484 g_assert_not_reached();
3487 if (prealloc
!= PREALLOC_MODE_OFF
) {
3488 /* Flush metadata before actually changing the image size */
3489 ret
= bdrv_flush(bs
);
3491 error_setg_errno(errp
, -ret
,
3492 "Failed to flush the preallocated area to disk");
3497 /* write updated header.size */
3498 offset
= cpu_to_be64(offset
);
3499 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
3500 &offset
, sizeof(uint64_t));
3502 error_setg_errno(errp
, -ret
, "Failed to update the image size");
3506 s
->l1_vm_state_index
= new_l1_size
;
3510 /* XXX: put compressed sectors first, then all the cluster aligned
3511 tables to avoid losing bytes in alignment */
3512 static coroutine_fn
int
3513 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
3514 uint64_t bytes
, QEMUIOVector
*qiov
)
3516 BDRVQcow2State
*s
= bs
->opaque
;
3517 QEMUIOVector hd_qiov
;
3521 uint8_t *buf
, *out_buf
;
3522 int64_t cluster_offset
;
3525 /* align end of file to a sector boundary to ease reading with
3526 sector based I/Os */
3527 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
3528 if (cluster_offset
< 0) {
3529 return cluster_offset
;
3531 return bdrv_truncate(bs
->file
, cluster_offset
, PREALLOC_MODE_OFF
, NULL
);
3534 if (offset_into_cluster(s
, offset
)) {
3538 buf
= qemu_blockalign(bs
, s
->cluster_size
);
3539 if (bytes
!= s
->cluster_size
) {
3540 if (bytes
> s
->cluster_size
||
3541 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
3546 /* Zero-pad last write if image size is not cluster aligned */
3547 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
3549 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
3551 out_buf
= g_malloc(s
->cluster_size
);
3553 /* best compression, small window, no zlib header */
3554 memset(&strm
, 0, sizeof(strm
));
3555 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
3557 9, Z_DEFAULT_STRATEGY
);
3563 strm
.avail_in
= s
->cluster_size
;
3564 strm
.next_in
= (uint8_t *)buf
;
3565 strm
.avail_out
= s
->cluster_size
;
3566 strm
.next_out
= out_buf
;
3568 ret
= deflate(&strm
, Z_FINISH
);
3569 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
3574 out_len
= strm
.next_out
- out_buf
;
3578 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
3579 /* could not compress: write normal cluster */
3580 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
3587 qemu_co_mutex_lock(&s
->lock
);
3589 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
3590 if (!cluster_offset
) {
3591 qemu_co_mutex_unlock(&s
->lock
);
3595 cluster_offset
&= s
->cluster_offset_mask
;
3597 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
3598 qemu_co_mutex_unlock(&s
->lock
);
3603 iov
= (struct iovec
) {
3604 .iov_base
= out_buf
,
3607 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
3609 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
3610 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
3622 static int make_completely_empty(BlockDriverState
*bs
)
3624 BDRVQcow2State
*s
= bs
->opaque
;
3625 Error
*local_err
= NULL
;
3626 int ret
, l1_clusters
;
3628 uint64_t *new_reftable
= NULL
;
3629 uint64_t rt_entry
, l1_size2
;
3632 uint64_t reftable_offset
;
3633 uint32_t reftable_clusters
;
3634 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
3636 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
3641 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
3646 /* Refcounts will be broken utterly */
3647 ret
= qcow2_mark_dirty(bs
);
3652 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3654 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3655 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
3657 /* After this call, neither the in-memory nor the on-disk refcount
3658 * information accurately describe the actual references */
3660 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
3661 l1_clusters
* s
->cluster_size
, 0);
3663 goto fail_broken_refcounts
;
3665 memset(s
->l1_table
, 0, l1_size2
);
3667 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
3669 /* Overwrite enough clusters at the beginning of the sectors to place
3670 * the refcount table, a refcount block and the L1 table in; this may
3671 * overwrite parts of the existing refcount and L1 table, which is not
3672 * an issue because the dirty flag is set, complete data loss is in fact
3673 * desired and partial data loss is consequently fine as well */
3674 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
3675 (2 + l1_clusters
) * s
->cluster_size
, 0);
3676 /* This call (even if it failed overall) may have overwritten on-disk
3677 * refcount structures; in that case, the in-memory refcount information
3678 * will probably differ from the on-disk information which makes the BDS
3681 goto fail_broken_refcounts
;
3684 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3685 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
3687 /* "Create" an empty reftable (one cluster) directly after the image
3688 * header and an empty L1 table three clusters after the image header;
3689 * the cluster between those two will be used as the first refblock */
3690 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
3691 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
3692 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
3693 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
3694 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
3696 goto fail_broken_refcounts
;
3699 s
->l1_table_offset
= 3 * s
->cluster_size
;
3701 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
3702 if (!new_reftable
) {
3704 goto fail_broken_refcounts
;
3707 s
->refcount_table_offset
= s
->cluster_size
;
3708 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
3709 s
->max_refcount_table_index
= 0;
3711 g_free(s
->refcount_table
);
3712 s
->refcount_table
= new_reftable
;
3713 new_reftable
= NULL
;
3715 /* Now the in-memory refcount information again corresponds to the on-disk
3716 * information (reftable is empty and no refblocks (the refblock cache is
3717 * empty)); however, this means some clusters (e.g. the image header) are
3718 * referenced, but not refcounted, but the normal qcow2 code assumes that
3719 * the in-memory information is always correct */
3721 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
3723 /* Enter the first refblock into the reftable */
3724 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
3725 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
3726 &rt_entry
, sizeof(rt_entry
));
3728 goto fail_broken_refcounts
;
3730 s
->refcount_table
[0] = 2 * s
->cluster_size
;
3732 s
->free_cluster_index
= 0;
3733 assert(3 + l1_clusters
<= s
->refcount_block_size
);
3734 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
3737 goto fail_broken_refcounts
;
3738 } else if (offset
> 0) {
3739 error_report("First cluster in emptied image is in use");
3743 /* Now finally the in-memory information corresponds to the on-disk
3744 * structures and is correct */
3745 ret
= qcow2_mark_clean(bs
);
3750 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
3751 PREALLOC_MODE_OFF
, &local_err
);
3753 error_report_err(local_err
);
3759 fail_broken_refcounts
:
3760 /* The BDS is unusable at this point. If we wanted to make it usable, we
3761 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3762 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3763 * again. However, because the functions which could have caused this error
3764 * path to be taken are used by those functions as well, it's very likely
3765 * that that sequence will fail as well. Therefore, just eject the BDS. */
3769 g_free(new_reftable
);
3773 static int qcow2_make_empty(BlockDriverState
*bs
)
3775 BDRVQcow2State
*s
= bs
->opaque
;
3776 uint64_t offset
, end_offset
;
3777 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
3778 int l1_clusters
, ret
= 0;
3780 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3782 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
3783 3 + l1_clusters
<= s
->refcount_block_size
&&
3784 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
3785 /* The following function only works for qcow2 v3 images (it
3786 * requires the dirty flag) and only as long as there are no
3787 * features that reserve extra clusters (such as snapshots,
3788 * LUKS header, or persistent bitmaps), because it completely
3789 * empties the image. Furthermore, the L1 table and three
3790 * additional clusters (image header, refcount table, one
3791 * refcount block) have to fit inside one refcount block. */
3792 return make_completely_empty(bs
);
3795 /* This fallback code simply discards every active cluster; this is slow,
3796 * but works in all cases */
3797 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3798 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
3799 /* As this function is generally used after committing an external
3800 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3801 * default action for this kind of discard is to pass the discard,
3802 * which will ideally result in an actually smaller image file, as
3803 * is probably desired. */
3804 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
3805 QCOW2_DISCARD_SNAPSHOT
, true);
3814 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
3816 BDRVQcow2State
*s
= bs
->opaque
;
3819 qemu_co_mutex_lock(&s
->lock
);
3820 ret
= qcow2_write_caches(bs
);
3821 qemu_co_mutex_unlock(&s
->lock
);
3826 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
3829 Error
*local_err
= NULL
;
3830 BlockMeasureInfo
*info
;
3831 uint64_t required
= 0; /* bytes that contribute to required size */
3832 uint64_t virtual_size
; /* disk size as seen by guest */
3833 uint64_t refcount_bits
;
3835 size_t cluster_size
;
3838 PreallocMode prealloc
;
3839 bool has_backing_file
;
3841 /* Parse image creation options */
3842 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
3847 version
= qcow2_opt_get_version_del(opts
, &local_err
);
3852 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
3857 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
3858 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
3859 PREALLOC_MODE_OFF
, &local_err
);
3865 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
3866 has_backing_file
= !!optstr
;
3869 virtual_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
3870 virtual_size
= ROUND_UP(virtual_size
, cluster_size
);
3872 /* Check that virtual disk size is valid */
3873 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
3874 cluster_size
/ sizeof(uint64_t));
3875 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
3876 error_setg(&local_err
, "The image size is too large "
3877 "(try using a larger cluster size)");
3881 /* Account for input image */
3883 int64_t ssize
= bdrv_getlength(in_bs
);
3885 error_setg_errno(&local_err
, -ssize
,
3886 "Unable to get image virtual_size");
3890 virtual_size
= ROUND_UP(ssize
, cluster_size
);
3892 if (has_backing_file
) {
3893 /* We don't how much of the backing chain is shared by the input
3894 * image and the new image file. In the worst case the new image's
3895 * backing file has nothing in common with the input image. Be
3896 * conservative and assume all clusters need to be written.
3898 required
= virtual_size
;
3903 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
3906 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
3907 ssize
- offset
, &pnum
, NULL
,
3910 error_setg_errno(&local_err
, -ret
,
3911 "Unable to get block status");
3915 if (ret
& BDRV_BLOCK_ZERO
) {
3916 /* Skip zero regions (safe with no backing file) */
3917 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
3918 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
3919 /* Extend pnum to end of cluster for next iteration */
3920 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
3922 /* Count clusters we've seen */
3923 required
+= offset
% cluster_size
+ pnum
;
3929 /* Take into account preallocation. Nothing special is needed for
3930 * PREALLOC_MODE_METADATA since metadata is always counted.
3932 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
3933 required
= virtual_size
;
3936 info
= g_new(BlockMeasureInfo
, 1);
3937 info
->fully_allocated
=
3938 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
3939 ctz32(refcount_bits
));
3941 /* Remove data clusters that are not required. This overestimates the
3942 * required size because metadata needed for the fully allocated file is
3945 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
3949 error_propagate(errp
, local_err
);
3953 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3955 BDRVQcow2State
*s
= bs
->opaque
;
3956 bdi
->unallocated_blocks_are_zero
= true;
3957 bdi
->cluster_size
= s
->cluster_size
;
3958 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
3962 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
3964 BDRVQcow2State
*s
= bs
->opaque
;
3965 ImageInfoSpecific
*spec_info
;
3966 QCryptoBlockInfo
*encrypt_info
= NULL
;
3968 if (s
->crypto
!= NULL
) {
3969 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &error_abort
);
3972 spec_info
= g_new(ImageInfoSpecific
, 1);
3973 *spec_info
= (ImageInfoSpecific
){
3974 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
3975 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
3977 if (s
->qcow_version
== 2) {
3978 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3979 .compat
= g_strdup("0.10"),
3980 .refcount_bits
= s
->refcount_bits
,
3982 } else if (s
->qcow_version
== 3) {
3983 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3984 .compat
= g_strdup("1.1"),
3985 .lazy_refcounts
= s
->compatible_features
&
3986 QCOW2_COMPAT_LAZY_REFCOUNTS
,
3987 .has_lazy_refcounts
= true,
3988 .corrupt
= s
->incompatible_features
&
3989 QCOW2_INCOMPAT_CORRUPT
,
3990 .has_corrupt
= true,
3991 .refcount_bits
= s
->refcount_bits
,
3994 /* if this assertion fails, this probably means a new version was
3995 * added without having it covered here */
4000 ImageInfoSpecificQCow2Encryption
*qencrypt
=
4001 g_new(ImageInfoSpecificQCow2Encryption
, 1);
4002 switch (encrypt_info
->format
) {
4003 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
4004 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
4005 qencrypt
->u
.aes
= encrypt_info
->u
.qcow
;
4007 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
4008 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
4009 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
4014 /* Since we did shallow copy above, erase any pointers
4015 * in the original info */
4016 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
4017 qapi_free_QCryptoBlockInfo(encrypt_info
);
4019 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
4020 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
4026 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4029 BDRVQcow2State
*s
= bs
->opaque
;
4031 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
4032 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
4033 qiov
->size
, qiov
, 0);
4036 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4039 BDRVQcow2State
*s
= bs
->opaque
;
4041 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
4042 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
4043 qiov
->size
, qiov
, 0);
4047 * Downgrades an image's version. To achieve this, any incompatible features
4048 * have to be removed.
4050 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
4051 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
)
4053 BDRVQcow2State
*s
= bs
->opaque
;
4054 int current_version
= s
->qcow_version
;
4057 if (target_version
== current_version
) {
4059 } else if (target_version
> current_version
) {
4061 } else if (target_version
!= 2) {
4065 if (s
->refcount_order
!= 4) {
4066 error_report("compat=0.10 requires refcount_bits=16");
4070 /* clear incompatible features */
4071 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
4072 ret
= qcow2_mark_clean(bs
);
4078 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4079 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4080 * best thing to do anyway */
4082 if (s
->incompatible_features
) {
4086 /* since we can ignore compatible features, we can set them to 0 as well */
4087 s
->compatible_features
= 0;
4088 /* if lazy refcounts have been used, they have already been fixed through
4089 * clearing the dirty flag */
4091 /* clearing autoclear features is trivial */
4092 s
->autoclear_features
= 0;
4094 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
4099 s
->qcow_version
= target_version
;
4100 ret
= qcow2_update_header(bs
);
4102 s
->qcow_version
= current_version
;
4108 typedef enum Qcow2AmendOperation
{
4109 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4110 * statically initialized to so that the helper CB can discern the first
4111 * invocation from an operation change */
4112 QCOW2_NO_OPERATION
= 0,
4114 QCOW2_CHANGING_REFCOUNT_ORDER
,
4116 } Qcow2AmendOperation
;
4118 typedef struct Qcow2AmendHelperCBInfo
{
4119 /* The code coordinating the amend operations should only modify
4120 * these four fields; the rest will be managed by the CB */
4121 BlockDriverAmendStatusCB
*original_status_cb
;
4122 void *original_cb_opaque
;
4124 Qcow2AmendOperation current_operation
;
4126 /* Total number of operations to perform (only set once) */
4127 int total_operations
;
4129 /* The following fields are managed by the CB */
4131 /* Number of operations completed */
4132 int operations_completed
;
4134 /* Cumulative offset of all completed operations */
4135 int64_t offset_completed
;
4137 Qcow2AmendOperation last_operation
;
4138 int64_t last_work_size
;
4139 } Qcow2AmendHelperCBInfo
;
4141 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
4142 int64_t operation_offset
,
4143 int64_t operation_work_size
, void *opaque
)
4145 Qcow2AmendHelperCBInfo
*info
= opaque
;
4146 int64_t current_work_size
;
4147 int64_t projected_work_size
;
4149 if (info
->current_operation
!= info
->last_operation
) {
4150 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
4151 info
->offset_completed
+= info
->last_work_size
;
4152 info
->operations_completed
++;
4155 info
->last_operation
= info
->current_operation
;
4158 assert(info
->total_operations
> 0);
4159 assert(info
->operations_completed
< info
->total_operations
);
4161 info
->last_work_size
= operation_work_size
;
4163 current_work_size
= info
->offset_completed
+ operation_work_size
;
4165 /* current_work_size is the total work size for (operations_completed + 1)
4166 * operations (which includes this one), so multiply it by the number of
4167 * operations not covered and divide it by the number of operations
4168 * covered to get a projection for the operations not covered */
4169 projected_work_size
= current_work_size
* (info
->total_operations
-
4170 info
->operations_completed
- 1)
4171 / (info
->operations_completed
+ 1);
4173 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
4174 current_work_size
+ projected_work_size
,
4175 info
->original_cb_opaque
);
4178 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
4179 BlockDriverAmendStatusCB
*status_cb
,
4182 BDRVQcow2State
*s
= bs
->opaque
;
4183 int old_version
= s
->qcow_version
, new_version
= old_version
;
4184 uint64_t new_size
= 0;
4185 const char *backing_file
= NULL
, *backing_format
= NULL
;
4186 bool lazy_refcounts
= s
->use_lazy_refcounts
;
4187 const char *compat
= NULL
;
4188 uint64_t cluster_size
= s
->cluster_size
;
4191 int refcount_bits
= s
->refcount_bits
;
4192 Error
*local_err
= NULL
;
4194 QemuOptDesc
*desc
= opts
->list
->desc
;
4195 Qcow2AmendHelperCBInfo helper_cb_info
;
4197 while (desc
&& desc
->name
) {
4198 if (!qemu_opt_find(opts
, desc
->name
)) {
4199 /* only change explicitly defined options */
4204 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
4205 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
4207 /* preserve default */
4208 } else if (!strcmp(compat
, "0.10")) {
4210 } else if (!strcmp(compat
, "1.1")) {
4213 error_report("Unknown compatibility level %s", compat
);
4216 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
4217 error_report("Cannot change preallocation mode");
4219 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
4220 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
4221 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
4222 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
4223 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
4224 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
4225 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
4226 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
4229 if (encrypt
!= !!s
->crypto
) {
4230 error_report("Changing the encryption flag is not supported");
4233 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
4234 encformat
= qcow2_crypt_method_from_format(
4235 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
4237 if (encformat
!= s
->crypt_method_header
) {
4238 error_report("Changing the encryption format is not supported");
4241 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
4242 error_report("Changing the encryption parameters is not supported");
4244 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
4245 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
4247 if (cluster_size
!= s
->cluster_size
) {
4248 error_report("Changing the cluster size is not supported");
4251 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
4252 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
4254 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
4255 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
4258 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
4259 !is_power_of_2(refcount_bits
))
4261 error_report("Refcount width must be a power of two and may "
4262 "not exceed 64 bits");
4266 /* if this point is reached, this probably means a new option was
4267 * added without having it covered here */
4274 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
4275 .original_status_cb
= status_cb
,
4276 .original_cb_opaque
= cb_opaque
,
4277 .total_operations
= (new_version
< old_version
)
4278 + (s
->refcount_bits
!= refcount_bits
)
4281 /* Upgrade first (some features may require compat=1.1) */
4282 if (new_version
> old_version
) {
4283 s
->qcow_version
= new_version
;
4284 ret
= qcow2_update_header(bs
);
4286 s
->qcow_version
= old_version
;
4291 if (s
->refcount_bits
!= refcount_bits
) {
4292 int refcount_order
= ctz32(refcount_bits
);
4294 if (new_version
< 3 && refcount_bits
!= 16) {
4295 error_report("Different refcount widths than 16 bits require "
4296 "compatibility level 1.1 or above (use compat=1.1 or "
4301 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
4302 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
4303 &qcow2_amend_helper_cb
,
4304 &helper_cb_info
, &local_err
);
4306 error_report_err(local_err
);
4311 if (backing_file
|| backing_format
) {
4312 ret
= qcow2_change_backing_file(bs
,
4313 backing_file
?: s
->image_backing_file
,
4314 backing_format
?: s
->image_backing_format
);
4320 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
4321 if (lazy_refcounts
) {
4322 if (new_version
< 3) {
4323 error_report("Lazy refcounts only supported with compatibility "
4324 "level 1.1 and above (use compat=1.1 or greater)");
4327 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4328 ret
= qcow2_update_header(bs
);
4330 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4333 s
->use_lazy_refcounts
= true;
4335 /* make image clean first */
4336 ret
= qcow2_mark_clean(bs
);
4340 /* now disallow lazy refcounts */
4341 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4342 ret
= qcow2_update_header(bs
);
4344 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4347 s
->use_lazy_refcounts
= false;
4352 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
4353 ret
= blk_insert_bs(blk
, bs
, &local_err
);
4355 error_report_err(local_err
);
4360 ret
= blk_truncate(blk
, new_size
, PREALLOC_MODE_OFF
, &local_err
);
4363 error_report_err(local_err
);
4368 /* Downgrade last (so unsupported features can be removed before) */
4369 if (new_version
< old_version
) {
4370 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
4371 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
4382 * If offset or size are negative, respectively, they will not be included in
4383 * the BLOCK_IMAGE_CORRUPTED event emitted.
4384 * fatal will be ignored for read-only BDS; corruptions found there will always
4385 * be considered non-fatal.
4387 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
4388 int64_t size
, const char *message_format
, ...)
4390 BDRVQcow2State
*s
= bs
->opaque
;
4391 const char *node_name
;
4395 fatal
= fatal
&& !bs
->read_only
;
4397 if (s
->signaled_corruption
&&
4398 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
4403 va_start(ap
, message_format
);
4404 message
= g_strdup_vprintf(message_format
, ap
);
4408 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
4409 "corruption events will be suppressed\n", message
);
4411 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
4412 "corruption events will be suppressed\n", message
);
4415 node_name
= bdrv_get_node_name(bs
);
4416 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
4417 *node_name
!= '\0', node_name
,
4418 message
, offset
>= 0, offset
,
4420 fatal
, &error_abort
);
4424 qcow2_mark_corrupt(bs
);
4425 bs
->drv
= NULL
; /* make BDS unusable */
4428 s
->signaled_corruption
= true;
4431 static QemuOptsList qcow2_create_opts
= {
4432 .name
= "qcow2-create-opts",
4433 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
4436 .name
= BLOCK_OPT_SIZE
,
4437 .type
= QEMU_OPT_SIZE
,
4438 .help
= "Virtual disk size"
4441 .name
= BLOCK_OPT_COMPAT_LEVEL
,
4442 .type
= QEMU_OPT_STRING
,
4443 .help
= "Compatibility level (0.10 or 1.1)"
4446 .name
= BLOCK_OPT_BACKING_FILE
,
4447 .type
= QEMU_OPT_STRING
,
4448 .help
= "File name of a base image"
4451 .name
= BLOCK_OPT_BACKING_FMT
,
4452 .type
= QEMU_OPT_STRING
,
4453 .help
= "Image format of the base image"
4456 .name
= BLOCK_OPT_ENCRYPT
,
4457 .type
= QEMU_OPT_BOOL
,
4458 .help
= "Encrypt the image with format 'aes'. (Deprecated "
4459 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
4462 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
4463 .type
= QEMU_OPT_STRING
,
4464 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
4466 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4467 "ID of secret providing qcow AES key or LUKS passphrase"),
4468 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4469 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4470 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4471 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4472 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4473 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4475 .name
= BLOCK_OPT_CLUSTER_SIZE
,
4476 .type
= QEMU_OPT_SIZE
,
4477 .help
= "qcow2 cluster size",
4478 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
4481 .name
= BLOCK_OPT_PREALLOC
,
4482 .type
= QEMU_OPT_STRING
,
4483 .help
= "Preallocation mode (allowed values: off, metadata, "
4487 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
4488 .type
= QEMU_OPT_BOOL
,
4489 .help
= "Postpone refcount updates",
4490 .def_value_str
= "off"
4493 .name
= BLOCK_OPT_REFCOUNT_BITS
,
4494 .type
= QEMU_OPT_NUMBER
,
4495 .help
= "Width of a reference count entry in bits",
4496 .def_value_str
= "16"
4498 { /* end of list */ }
4502 BlockDriver bdrv_qcow2
= {
4503 .format_name
= "qcow2",
4504 .instance_size
= sizeof(BDRVQcow2State
),
4505 .bdrv_probe
= qcow2_probe
,
4506 .bdrv_open
= qcow2_open
,
4507 .bdrv_close
= qcow2_close
,
4508 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
4509 .bdrv_reopen_commit
= qcow2_reopen_commit
,
4510 .bdrv_reopen_abort
= qcow2_reopen_abort
,
4511 .bdrv_join_options
= qcow2_join_options
,
4512 .bdrv_child_perm
= bdrv_format_default_perms
,
4513 .bdrv_co_create_opts
= qcow2_co_create_opts
,
4514 .bdrv_co_create
= qcow2_co_create
,
4515 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
4516 .bdrv_co_block_status
= qcow2_co_block_status
,
4518 .bdrv_co_preadv
= qcow2_co_preadv
,
4519 .bdrv_co_pwritev
= qcow2_co_pwritev
,
4520 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
4522 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
4523 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
4524 .bdrv_truncate
= qcow2_truncate
,
4525 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
4526 .bdrv_make_empty
= qcow2_make_empty
,
4528 .bdrv_snapshot_create
= qcow2_snapshot_create
,
4529 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
4530 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
4531 .bdrv_snapshot_list
= qcow2_snapshot_list
,
4532 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
4533 .bdrv_measure
= qcow2_measure
,
4534 .bdrv_get_info
= qcow2_get_info
,
4535 .bdrv_get_specific_info
= qcow2_get_specific_info
,
4537 .bdrv_save_vmstate
= qcow2_save_vmstate
,
4538 .bdrv_load_vmstate
= qcow2_load_vmstate
,
4540 .supports_backing
= true,
4541 .bdrv_change_backing_file
= qcow2_change_backing_file
,
4543 .bdrv_refresh_limits
= qcow2_refresh_limits
,
4544 .bdrv_co_invalidate_cache
= qcow2_co_invalidate_cache
,
4545 .bdrv_inactivate
= qcow2_inactivate
,
4547 .create_opts
= &qcow2_create_opts
,
4548 .bdrv_co_check
= qcow2_co_check
,
4549 .bdrv_amend_options
= qcow2_amend_options
,
4551 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
4552 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
4554 .bdrv_reopen_bitmaps_rw
= qcow2_reopen_bitmaps_rw
,
4555 .bdrv_can_store_new_dirty_bitmap
= qcow2_can_store_new_dirty_bitmap
,
4556 .bdrv_remove_persistent_dirty_bitmap
= qcow2_remove_persistent_dirty_bitmap
,
4559 static void bdrv_qcow2_init(void)
4561 bdrv_register(&bdrv_qcow2
);
4564 block_init(bdrv_qcow2_init
);