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"
30 #include "block/block_int.h"
31 #include "block/qdict.h"
32 #include "sysemu/block-backend.h"
33 #include "qemu/module.h"
35 #include "qemu/error-report.h"
36 #include "qapi/error.h"
37 #include "qapi/qapi-events-block-core.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qstring.h"
41 #include "qemu/option_int.h"
42 #include "qemu/cutils.h"
43 #include "qemu/bswap.h"
44 #include "qapi/qobject-input-visitor.h"
45 #include "qapi/qapi-visit-block-core.h"
47 #include "block/thread-pool.h"
50 Differences with QCOW:
52 - Support for multiple incremental snapshots.
53 - Memory management by reference counts.
54 - Clusters which have a reference count of one have the bit
55 QCOW_OFLAG_COPIED to optimize write performance.
56 - Size of compressed clusters is stored in sectors to reduce bit usage
57 in the cluster offsets.
58 - Support for storing additional data (such as the VM state) in the
60 - If a backing store is used, the cluster size is not constrained
61 (could be backported to QCOW).
62 - L2 tables have always a size of one cluster.
69 } QEMU_PACKED QCowExtension
;
71 #define QCOW2_EXT_MAGIC_END 0
72 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
73 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
74 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
75 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
77 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
79 const QCowHeader
*cow_header
= (const void *)buf
;
81 if (buf_size
>= sizeof(QCowHeader
) &&
82 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
83 be32_to_cpu(cow_header
->version
) >= 2)
90 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
91 uint8_t *buf
, size_t buflen
,
92 void *opaque
, Error
**errp
)
94 BlockDriverState
*bs
= opaque
;
95 BDRVQcow2State
*s
= bs
->opaque
;
98 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
99 error_setg(errp
, "Request for data outside of extension header");
103 ret
= bdrv_pread(bs
->file
,
104 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
106 error_setg_errno(errp
, -ret
, "Could not read encryption header");
113 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
114 void *opaque
, Error
**errp
)
116 BlockDriverState
*bs
= opaque
;
117 BDRVQcow2State
*s
= bs
->opaque
;
121 ret
= qcow2_alloc_clusters(bs
, headerlen
);
123 error_setg_errno(errp
, -ret
,
124 "Cannot allocate cluster for LUKS header size %zu",
129 s
->crypto_header
.length
= headerlen
;
130 s
->crypto_header
.offset
= ret
;
132 /* Zero fill remaining space in cluster so it has predictable
133 * content in case of future spec changes */
134 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
135 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
) == 0);
136 ret
= bdrv_pwrite_zeroes(bs
->file
,
138 clusterlen
- headerlen
, 0);
140 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
148 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
149 const uint8_t *buf
, size_t buflen
,
150 void *opaque
, Error
**errp
)
152 BlockDriverState
*bs
= opaque
;
153 BDRVQcow2State
*s
= bs
->opaque
;
156 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
157 error_setg(errp
, "Request for data outside of extension header");
161 ret
= bdrv_pwrite(bs
->file
,
162 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
164 error_setg_errno(errp
, -ret
, "Could not read encryption header");
172 * read qcow2 extension and fill bs
173 * start reading from start_offset
174 * finish reading upon magic of value 0 or when end_offset reached
175 * unknown magic is skipped (future extension this version knows nothing about)
176 * return 0 upon success, non-0 otherwise
178 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
179 uint64_t end_offset
, void **p_feature_table
,
180 int flags
, bool *need_update_header
,
183 BDRVQcow2State
*s
= bs
->opaque
;
187 Qcow2BitmapHeaderExt bitmaps_ext
;
189 if (need_update_header
!= NULL
) {
190 *need_update_header
= false;
194 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
196 offset
= start_offset
;
197 while (offset
< end_offset
) {
201 if (offset
> s
->cluster_size
)
202 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
204 printf("attempting to read extended header in offset %lu\n", offset
);
207 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
209 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
210 "pread fail from offset %" PRIu64
, offset
);
213 be32_to_cpus(&ext
.magic
);
214 be32_to_cpus(&ext
.len
);
215 offset
+= sizeof(ext
);
217 printf("ext.magic = 0x%x\n", ext
.magic
);
219 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
220 error_setg(errp
, "Header extension too large");
225 case QCOW2_EXT_MAGIC_END
:
228 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
229 if (ext
.len
>= sizeof(bs
->backing_format
)) {
230 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
231 " too large (>=%zu)", ext
.len
,
232 sizeof(bs
->backing_format
));
235 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
237 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
238 "Could not read format name");
241 bs
->backing_format
[ext
.len
] = '\0';
242 s
->image_backing_format
= g_strdup(bs
->backing_format
);
244 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
248 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
249 if (p_feature_table
!= NULL
) {
250 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
251 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
253 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
254 "Could not read table");
258 *p_feature_table
= feature_table
;
262 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
263 unsigned int cflags
= 0;
264 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
265 error_setg(errp
, "CRYPTO header extension only "
266 "expected with LUKS encryption method");
269 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
270 error_setg(errp
, "CRYPTO header extension size %u, "
271 "but expected size %zu", ext
.len
,
272 sizeof(Qcow2CryptoHeaderExtension
));
276 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
278 error_setg_errno(errp
, -ret
,
279 "Unable to read CRYPTO header extension");
282 be64_to_cpus(&s
->crypto_header
.offset
);
283 be64_to_cpus(&s
->crypto_header
.length
);
285 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
286 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
287 "not a multiple of cluster size '%u'",
288 s
->crypto_header
.offset
, s
->cluster_size
);
292 if (flags
& BDRV_O_NO_IO
) {
293 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
295 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
296 qcow2_crypto_hdr_read_func
,
303 case QCOW2_EXT_MAGIC_BITMAPS
:
304 if (ext
.len
!= sizeof(bitmaps_ext
)) {
305 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
306 "Invalid extension length");
310 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
311 if (s
->qcow_version
< 3) {
312 /* Let's be a bit more specific */
313 warn_report("This qcow2 v2 image contains bitmaps, but "
314 "they may have been modified by a program "
315 "without persistent bitmap support; so now "
316 "they must all be considered inconsistent");
318 warn_report("a program lacking bitmap support "
319 "modified this file, so all bitmaps are now "
320 "considered inconsistent");
322 error_printf("Some clusters may be leaked, "
323 "run 'qemu-img check -r' on the image "
325 if (need_update_header
!= NULL
) {
326 /* Updating is needed to drop invalid bitmap extension. */
327 *need_update_header
= true;
332 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
334 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
335 "Could not read ext header");
339 if (bitmaps_ext
.reserved32
!= 0) {
340 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
341 "Reserved field is not zero");
345 be32_to_cpus(&bitmaps_ext
.nb_bitmaps
);
346 be64_to_cpus(&bitmaps_ext
.bitmap_directory_size
);
347 be64_to_cpus(&bitmaps_ext
.bitmap_directory_offset
);
349 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
351 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
352 "exceeding the QEMU supported maximum of %d",
353 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
357 if (bitmaps_ext
.nb_bitmaps
== 0) {
358 error_setg(errp
, "found bitmaps extension with zero bitmaps");
362 if (bitmaps_ext
.bitmap_directory_offset
& (s
->cluster_size
- 1)) {
363 error_setg(errp
, "bitmaps_ext: "
364 "invalid bitmap directory offset");
368 if (bitmaps_ext
.bitmap_directory_size
>
369 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
370 error_setg(errp
, "bitmaps_ext: "
371 "bitmap directory size (%" PRIu64
") exceeds "
372 "the maximum supported size (%d)",
373 bitmaps_ext
.bitmap_directory_size
,
374 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
378 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
379 s
->bitmap_directory_offset
=
380 bitmaps_ext
.bitmap_directory_offset
;
381 s
->bitmap_directory_size
=
382 bitmaps_ext
.bitmap_directory_size
;
385 printf("Qcow2: Got bitmaps extension: "
386 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
387 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
392 /* unknown magic - save it in case we need to rewrite the header */
393 /* If you add a new feature, make sure to also update the fast
394 * path of qcow2_make_empty() to deal with it. */
396 Qcow2UnknownHeaderExtension
*uext
;
398 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
399 uext
->magic
= ext
.magic
;
401 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
403 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
405 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
406 "Could not read data");
413 offset
+= ((ext
.len
+ 7) & ~7);
419 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
421 BDRVQcow2State
*s
= bs
->opaque
;
422 Qcow2UnknownHeaderExtension
*uext
, *next
;
424 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
425 QLIST_REMOVE(uext
, next
);
430 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
433 char *features
= g_strdup("");
436 while (table
&& table
->name
[0] != '\0') {
437 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
438 if (mask
& (1ULL << table
->bit
)) {
440 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
443 mask
&= ~(1ULL << table
->bit
);
451 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
452 old
, *old
? ", " : "", mask
);
456 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
461 * Sets the dirty bit and flushes afterwards if necessary.
463 * The incompatible_features bit is only set if the image file header was
464 * updated successfully. Therefore it is not required to check the return
465 * value of this function.
467 int qcow2_mark_dirty(BlockDriverState
*bs
)
469 BDRVQcow2State
*s
= bs
->opaque
;
473 assert(s
->qcow_version
>= 3);
475 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
476 return 0; /* already dirty */
479 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
480 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
485 ret
= bdrv_flush(bs
->file
->bs
);
490 /* Only treat image as dirty if the header was updated successfully */
491 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
496 * Clears the dirty bit and flushes before if necessary. Only call this
497 * function when there are no pending requests, it does not guard against
498 * concurrent requests dirtying the image.
500 static int qcow2_mark_clean(BlockDriverState
*bs
)
502 BDRVQcow2State
*s
= bs
->opaque
;
504 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
507 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
509 ret
= qcow2_flush_caches(bs
);
514 return qcow2_update_header(bs
);
520 * Marks the image as corrupt.
522 int qcow2_mark_corrupt(BlockDriverState
*bs
)
524 BDRVQcow2State
*s
= bs
->opaque
;
526 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
527 return qcow2_update_header(bs
);
531 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
532 * before if necessary.
534 int qcow2_mark_consistent(BlockDriverState
*bs
)
536 BDRVQcow2State
*s
= bs
->opaque
;
538 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
539 int ret
= qcow2_flush_caches(bs
);
544 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
545 return qcow2_update_header(bs
);
550 static int coroutine_fn
qcow2_co_check_locked(BlockDriverState
*bs
,
551 BdrvCheckResult
*result
,
554 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
559 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
560 ret
= qcow2_mark_clean(bs
);
564 return qcow2_mark_consistent(bs
);
569 static int coroutine_fn
qcow2_co_check(BlockDriverState
*bs
,
570 BdrvCheckResult
*result
,
573 BDRVQcow2State
*s
= bs
->opaque
;
576 qemu_co_mutex_lock(&s
->lock
);
577 ret
= qcow2_co_check_locked(bs
, result
, fix
);
578 qemu_co_mutex_unlock(&s
->lock
);
582 int qcow2_validate_table(BlockDriverState
*bs
, uint64_t offset
,
583 uint64_t entries
, size_t entry_len
,
584 int64_t max_size_bytes
, const char *table_name
,
587 BDRVQcow2State
*s
= bs
->opaque
;
589 if (entries
> max_size_bytes
/ entry_len
) {
590 error_setg(errp
, "%s too large", table_name
);
594 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
595 * because values will be passed to qemu functions taking int64_t. */
596 if ((INT64_MAX
- entries
* entry_len
< offset
) ||
597 (offset_into_cluster(s
, offset
) != 0)) {
598 error_setg(errp
, "%s offset invalid", table_name
);
605 static QemuOptsList qcow2_runtime_opts
= {
607 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
610 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
611 .type
= QEMU_OPT_BOOL
,
612 .help
= "Postpone refcount updates",
615 .name
= QCOW2_OPT_DISCARD_REQUEST
,
616 .type
= QEMU_OPT_BOOL
,
617 .help
= "Pass guest discard requests to the layer below",
620 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
621 .type
= QEMU_OPT_BOOL
,
622 .help
= "Generate discard requests when snapshot related space "
626 .name
= QCOW2_OPT_DISCARD_OTHER
,
627 .type
= QEMU_OPT_BOOL
,
628 .help
= "Generate discard requests when other clusters are freed",
631 .name
= QCOW2_OPT_OVERLAP
,
632 .type
= QEMU_OPT_STRING
,
633 .help
= "Selects which overlap checks to perform from a range of "
634 "templates (none, constant, cached, all)",
637 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
638 .type
= QEMU_OPT_STRING
,
639 .help
= "Selects which overlap checks to perform from a range of "
640 "templates (none, constant, cached, all)",
643 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
644 .type
= QEMU_OPT_BOOL
,
645 .help
= "Check for unintended writes into the main qcow2 header",
648 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
649 .type
= QEMU_OPT_BOOL
,
650 .help
= "Check for unintended writes into the active L1 table",
653 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
654 .type
= QEMU_OPT_BOOL
,
655 .help
= "Check for unintended writes into an active L2 table",
658 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
659 .type
= QEMU_OPT_BOOL
,
660 .help
= "Check for unintended writes into the refcount table",
663 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
664 .type
= QEMU_OPT_BOOL
,
665 .help
= "Check for unintended writes into a refcount block",
668 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
669 .type
= QEMU_OPT_BOOL
,
670 .help
= "Check for unintended writes into the snapshot table",
673 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
674 .type
= QEMU_OPT_BOOL
,
675 .help
= "Check for unintended writes into an inactive L1 table",
678 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
679 .type
= QEMU_OPT_BOOL
,
680 .help
= "Check for unintended writes into an inactive L2 table",
683 .name
= QCOW2_OPT_CACHE_SIZE
,
684 .type
= QEMU_OPT_SIZE
,
685 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
689 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
690 .type
= QEMU_OPT_SIZE
,
691 .help
= "Maximum L2 table cache size",
694 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
695 .type
= QEMU_OPT_SIZE
,
696 .help
= "Size of each entry in the L2 cache",
699 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
700 .type
= QEMU_OPT_SIZE
,
701 .help
= "Maximum refcount block cache size",
704 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
705 .type
= QEMU_OPT_NUMBER
,
706 .help
= "Clean unused cache entries after this time (in seconds)",
708 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
709 "ID of secret providing qcow2 AES key or LUKS passphrase"),
710 { /* end of list */ }
714 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
715 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
716 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
717 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
718 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
719 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
720 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
721 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
722 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
725 static void cache_clean_timer_cb(void *opaque
)
727 BlockDriverState
*bs
= opaque
;
728 BDRVQcow2State
*s
= bs
->opaque
;
729 qcow2_cache_clean_unused(s
->l2_table_cache
);
730 qcow2_cache_clean_unused(s
->refcount_block_cache
);
731 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
732 (int64_t) s
->cache_clean_interval
* 1000);
735 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
737 BDRVQcow2State
*s
= bs
->opaque
;
738 if (s
->cache_clean_interval
> 0) {
739 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
740 SCALE_MS
, cache_clean_timer_cb
,
742 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
743 (int64_t) s
->cache_clean_interval
* 1000);
747 static void cache_clean_timer_del(BlockDriverState
*bs
)
749 BDRVQcow2State
*s
= bs
->opaque
;
750 if (s
->cache_clean_timer
) {
751 timer_del(s
->cache_clean_timer
);
752 timer_free(s
->cache_clean_timer
);
753 s
->cache_clean_timer
= NULL
;
757 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
759 cache_clean_timer_del(bs
);
762 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
763 AioContext
*new_context
)
765 cache_clean_timer_init(bs
, new_context
);
768 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
769 uint64_t *l2_cache_size
,
770 uint64_t *l2_cache_entry_size
,
771 uint64_t *refcount_cache_size
, Error
**errp
)
773 BDRVQcow2State
*s
= bs
->opaque
;
774 uint64_t combined_cache_size
;
775 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
776 int min_refcount_cache
= MIN_REFCOUNT_CACHE_SIZE
* s
->cluster_size
;
778 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
779 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
780 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
782 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
783 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
784 *refcount_cache_size
= qemu_opt_get_size(opts
,
785 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
787 *l2_cache_entry_size
= qemu_opt_get_size(
788 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
790 if (combined_cache_size_set
) {
791 if (l2_cache_size_set
&& refcount_cache_size_set
) {
792 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
793 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
796 } else if (*l2_cache_size
> combined_cache_size
) {
797 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
798 QCOW2_OPT_CACHE_SIZE
);
800 } else if (*refcount_cache_size
> combined_cache_size
) {
801 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
802 QCOW2_OPT_CACHE_SIZE
);
806 if (l2_cache_size_set
) {
807 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
808 } else if (refcount_cache_size_set
) {
809 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
811 uint64_t virtual_disk_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
812 uint64_t max_l2_cache
= virtual_disk_size
/ (s
->cluster_size
/ 8);
814 /* Assign as much memory as possible to the L2 cache, and
815 * use the remainder for the refcount cache */
816 if (combined_cache_size
>= max_l2_cache
+ min_refcount_cache
) {
817 *l2_cache_size
= max_l2_cache
;
818 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
820 *refcount_cache_size
=
821 MIN(combined_cache_size
, min_refcount_cache
);
822 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
826 if (!l2_cache_size_set
) {
827 *l2_cache_size
= MAX(DEFAULT_L2_CACHE_BYTE_SIZE
,
828 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
831 if (!refcount_cache_size_set
) {
832 *refcount_cache_size
= min_refcount_cache
;
836 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
837 *l2_cache_entry_size
> s
->cluster_size
||
838 !is_power_of_2(*l2_cache_entry_size
)) {
839 error_setg(errp
, "L2 cache entry size must be a power of two "
840 "between %d and the cluster size (%d)",
841 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
846 typedef struct Qcow2ReopenState
{
847 Qcow2Cache
*l2_table_cache
;
848 Qcow2Cache
*refcount_block_cache
;
849 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
850 bool use_lazy_refcounts
;
852 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
853 uint64_t cache_clean_interval
;
854 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
857 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
859 QDict
*options
, int flags
,
862 BDRVQcow2State
*s
= bs
->opaque
;
863 QemuOpts
*opts
= NULL
;
864 const char *opt_overlap_check
, *opt_overlap_check_template
;
865 int overlap_check_template
= 0;
866 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
868 const char *encryptfmt
;
869 QDict
*encryptopts
= NULL
;
870 Error
*local_err
= NULL
;
873 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
874 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
876 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
877 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
879 error_propagate(errp
, local_err
);
884 /* get L2 table/refcount block cache size from command line options */
885 read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
886 &refcount_cache_size
, &local_err
);
888 error_propagate(errp
, local_err
);
893 l2_cache_size
/= l2_cache_entry_size
;
894 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
895 l2_cache_size
= MIN_L2_CACHE_SIZE
;
897 if (l2_cache_size
> INT_MAX
) {
898 error_setg(errp
, "L2 cache size too big");
903 refcount_cache_size
/= s
->cluster_size
;
904 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
905 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
907 if (refcount_cache_size
> INT_MAX
) {
908 error_setg(errp
, "Refcount cache size too big");
913 /* alloc new L2 table/refcount block cache, flush old one */
914 if (s
->l2_table_cache
) {
915 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
917 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
922 if (s
->refcount_block_cache
) {
923 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
925 error_setg_errno(errp
, -ret
,
926 "Failed to flush the refcount block cache");
931 r
->l2_slice_size
= l2_cache_entry_size
/ sizeof(uint64_t);
932 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
933 l2_cache_entry_size
);
934 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
936 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
937 error_setg(errp
, "Could not allocate metadata caches");
942 /* New interval for cache cleanup timer */
943 r
->cache_clean_interval
=
944 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
945 s
->cache_clean_interval
);
947 if (r
->cache_clean_interval
!= 0) {
948 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
949 " not supported on this host");
954 if (r
->cache_clean_interval
> UINT_MAX
) {
955 error_setg(errp
, "Cache clean interval too big");
960 /* lazy-refcounts; flush if going from enabled to disabled */
961 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
962 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
963 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
964 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
965 "qemu 1.1 compatibility level");
970 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
971 ret
= qcow2_mark_clean(bs
);
973 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
978 /* Overlap check options */
979 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
980 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
981 if (opt_overlap_check_template
&& opt_overlap_check
&&
982 strcmp(opt_overlap_check_template
, opt_overlap_check
))
984 error_setg(errp
, "Conflicting values for qcow2 options '"
985 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
986 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
990 if (!opt_overlap_check
) {
991 opt_overlap_check
= opt_overlap_check_template
?: "cached";
994 if (!strcmp(opt_overlap_check
, "none")) {
995 overlap_check_template
= 0;
996 } else if (!strcmp(opt_overlap_check
, "constant")) {
997 overlap_check_template
= QCOW2_OL_CONSTANT
;
998 } else if (!strcmp(opt_overlap_check
, "cached")) {
999 overlap_check_template
= QCOW2_OL_CACHED
;
1000 } else if (!strcmp(opt_overlap_check
, "all")) {
1001 overlap_check_template
= QCOW2_OL_ALL
;
1003 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
1004 "'overlap-check'. Allowed are any of the following: "
1005 "none, constant, cached, all", opt_overlap_check
);
1010 r
->overlap_check
= 0;
1011 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
1012 /* overlap-check defines a template bitmask, but every flag may be
1013 * overwritten through the associated boolean option */
1015 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
1016 overlap_check_template
& (1 << i
)) << i
;
1019 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
1020 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
1021 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
1022 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1023 flags
& BDRV_O_UNMAP
);
1024 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1025 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1026 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1027 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1029 switch (s
->crypt_method_header
) {
1030 case QCOW_CRYPT_NONE
:
1032 error_setg(errp
, "No encryption in image header, but options "
1033 "specified format '%s'", encryptfmt
);
1039 case QCOW_CRYPT_AES
:
1040 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1042 "Header reported 'aes' encryption format but "
1043 "options specify '%s'", encryptfmt
);
1047 qdict_put_str(encryptopts
, "format", "qcow");
1048 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1051 case QCOW_CRYPT_LUKS
:
1052 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1054 "Header reported 'luks' encryption format but "
1055 "options specify '%s'", encryptfmt
);
1059 qdict_put_str(encryptopts
, "format", "luks");
1060 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1064 error_setg(errp
, "Unsupported encryption method %d",
1065 s
->crypt_method_header
);
1068 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1075 qobject_unref(encryptopts
);
1076 qemu_opts_del(opts
);
1081 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1082 Qcow2ReopenState
*r
)
1084 BDRVQcow2State
*s
= bs
->opaque
;
1087 if (s
->l2_table_cache
) {
1088 qcow2_cache_destroy(s
->l2_table_cache
);
1090 if (s
->refcount_block_cache
) {
1091 qcow2_cache_destroy(s
->refcount_block_cache
);
1093 s
->l2_table_cache
= r
->l2_table_cache
;
1094 s
->refcount_block_cache
= r
->refcount_block_cache
;
1095 s
->l2_slice_size
= r
->l2_slice_size
;
1097 s
->overlap_check
= r
->overlap_check
;
1098 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1100 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1101 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1104 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1105 cache_clean_timer_del(bs
);
1106 s
->cache_clean_interval
= r
->cache_clean_interval
;
1107 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1110 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1111 s
->crypto_opts
= r
->crypto_opts
;
1114 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1115 Qcow2ReopenState
*r
)
1117 if (r
->l2_table_cache
) {
1118 qcow2_cache_destroy(r
->l2_table_cache
);
1120 if (r
->refcount_block_cache
) {
1121 qcow2_cache_destroy(r
->refcount_block_cache
);
1123 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1126 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1127 int flags
, Error
**errp
)
1129 Qcow2ReopenState r
= {};
1132 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1134 qcow2_update_options_commit(bs
, &r
);
1136 qcow2_update_options_abort(bs
, &r
);
1142 /* Called with s->lock held. */
1143 static int coroutine_fn
qcow2_do_open(BlockDriverState
*bs
, QDict
*options
,
1144 int flags
, Error
**errp
)
1146 BDRVQcow2State
*s
= bs
->opaque
;
1147 unsigned int len
, i
;
1150 Error
*local_err
= NULL
;
1152 uint64_t l1_vm_state_index
;
1153 bool update_header
= false;
1154 bool header_updated
= false;
1156 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1158 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1161 be32_to_cpus(&header
.magic
);
1162 be32_to_cpus(&header
.version
);
1163 be64_to_cpus(&header
.backing_file_offset
);
1164 be32_to_cpus(&header
.backing_file_size
);
1165 be64_to_cpus(&header
.size
);
1166 be32_to_cpus(&header
.cluster_bits
);
1167 be32_to_cpus(&header
.crypt_method
);
1168 be64_to_cpus(&header
.l1_table_offset
);
1169 be32_to_cpus(&header
.l1_size
);
1170 be64_to_cpus(&header
.refcount_table_offset
);
1171 be32_to_cpus(&header
.refcount_table_clusters
);
1172 be64_to_cpus(&header
.snapshots_offset
);
1173 be32_to_cpus(&header
.nb_snapshots
);
1175 if (header
.magic
!= QCOW_MAGIC
) {
1176 error_setg(errp
, "Image is not in qcow2 format");
1180 if (header
.version
< 2 || header
.version
> 3) {
1181 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1186 s
->qcow_version
= header
.version
;
1188 /* Initialise cluster size */
1189 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1190 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1191 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1192 header
.cluster_bits
);
1197 s
->cluster_bits
= header
.cluster_bits
;
1198 s
->cluster_size
= 1 << s
->cluster_bits
;
1199 s
->cluster_sectors
= 1 << (s
->cluster_bits
- BDRV_SECTOR_BITS
);
1201 /* Initialise version 3 header fields */
1202 if (header
.version
== 2) {
1203 header
.incompatible_features
= 0;
1204 header
.compatible_features
= 0;
1205 header
.autoclear_features
= 0;
1206 header
.refcount_order
= 4;
1207 header
.header_length
= 72;
1209 be64_to_cpus(&header
.incompatible_features
);
1210 be64_to_cpus(&header
.compatible_features
);
1211 be64_to_cpus(&header
.autoclear_features
);
1212 be32_to_cpus(&header
.refcount_order
);
1213 be32_to_cpus(&header
.header_length
);
1215 if (header
.header_length
< 104) {
1216 error_setg(errp
, "qcow2 header too short");
1222 if (header
.header_length
> s
->cluster_size
) {
1223 error_setg(errp
, "qcow2 header exceeds cluster size");
1228 if (header
.header_length
> sizeof(header
)) {
1229 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1230 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1231 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1232 s
->unknown_header_fields_size
);
1234 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1240 if (header
.backing_file_offset
> s
->cluster_size
) {
1241 error_setg(errp
, "Invalid backing file offset");
1246 if (header
.backing_file_offset
) {
1247 ext_end
= header
.backing_file_offset
;
1249 ext_end
= 1 << header
.cluster_bits
;
1252 /* Handle feature bits */
1253 s
->incompatible_features
= header
.incompatible_features
;
1254 s
->compatible_features
= header
.compatible_features
;
1255 s
->autoclear_features
= header
.autoclear_features
;
1257 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1258 void *feature_table
= NULL
;
1259 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1260 &feature_table
, flags
, NULL
, NULL
);
1261 report_unsupported_feature(errp
, feature_table
,
1262 s
->incompatible_features
&
1263 ~QCOW2_INCOMPAT_MASK
);
1265 g_free(feature_table
);
1269 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1270 /* Corrupt images may not be written to unless they are being repaired
1272 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1273 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1280 /* Check support for various header values */
1281 if (header
.refcount_order
> 6) {
1282 error_setg(errp
, "Reference count entry width too large; may not "
1287 s
->refcount_order
= header
.refcount_order
;
1288 s
->refcount_bits
= 1 << s
->refcount_order
;
1289 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1290 s
->refcount_max
+= s
->refcount_max
- 1;
1292 s
->crypt_method_header
= header
.crypt_method
;
1293 if (s
->crypt_method_header
) {
1294 if (bdrv_uses_whitelist() &&
1295 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1297 "Use of AES-CBC encrypted qcow2 images is no longer "
1298 "supported in system emulators");
1299 error_append_hint(errp
,
1300 "You can use 'qemu-img convert' to convert your "
1301 "image to an alternative supported format, such "
1302 "as unencrypted qcow2, or raw with the LUKS "
1303 "format instead.\n");
1308 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1309 s
->crypt_physical_offset
= false;
1311 /* Assuming LUKS and any future crypt methods we
1312 * add will all use physical offsets, due to the
1313 * fact that the alternative is insecure... */
1314 s
->crypt_physical_offset
= true;
1317 bs
->encrypted
= true;
1320 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
1321 s
->l2_size
= 1 << s
->l2_bits
;
1322 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1323 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1324 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1325 bs
->total_sectors
= header
.size
/ 512;
1326 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1327 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1328 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1330 s
->refcount_table_offset
= header
.refcount_table_offset
;
1331 s
->refcount_table_size
=
1332 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1334 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1335 error_setg(errp
, "Image does not contain a reference count table");
1340 ret
= qcow2_validate_table(bs
, s
->refcount_table_offset
,
1341 header
.refcount_table_clusters
,
1342 s
->cluster_size
, QCOW_MAX_REFTABLE_SIZE
,
1343 "Reference count table", errp
);
1348 /* The total size in bytes of the snapshot table is checked in
1349 * qcow2_read_snapshots() because the size of each snapshot is
1350 * variable and we don't know it yet.
1351 * Here we only check the offset and number of snapshots. */
1352 ret
= qcow2_validate_table(bs
, header
.snapshots_offset
,
1353 header
.nb_snapshots
,
1354 sizeof(QCowSnapshotHeader
),
1355 sizeof(QCowSnapshotHeader
) * QCOW_MAX_SNAPSHOTS
,
1356 "Snapshot table", errp
);
1361 /* read the level 1 table */
1362 ret
= qcow2_validate_table(bs
, header
.l1_table_offset
,
1363 header
.l1_size
, sizeof(uint64_t),
1364 QCOW_MAX_L1_SIZE
, "Active L1 table", errp
);
1368 s
->l1_size
= header
.l1_size
;
1369 s
->l1_table_offset
= header
.l1_table_offset
;
1371 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1372 if (l1_vm_state_index
> INT_MAX
) {
1373 error_setg(errp
, "Image is too big");
1377 s
->l1_vm_state_index
= l1_vm_state_index
;
1379 /* the L1 table must contain at least enough entries to put
1380 header.size bytes */
1381 if (s
->l1_size
< s
->l1_vm_state_index
) {
1382 error_setg(errp
, "L1 table is too small");
1387 if (s
->l1_size
> 0) {
1388 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1389 ROUND_UP(s
->l1_size
* sizeof(uint64_t), 512));
1390 if (s
->l1_table
== NULL
) {
1391 error_setg(errp
, "Could not allocate L1 table");
1395 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1396 s
->l1_size
* sizeof(uint64_t));
1398 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1401 for(i
= 0;i
< s
->l1_size
; i
++) {
1402 be64_to_cpus(&s
->l1_table
[i
]);
1406 /* Parse driver-specific options */
1407 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1412 s
->cluster_cache_offset
= -1;
1415 ret
= qcow2_refcount_init(bs
);
1417 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1421 QLIST_INIT(&s
->cluster_allocs
);
1422 QTAILQ_INIT(&s
->discards
);
1424 /* read qcow2 extensions */
1425 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1426 flags
, &update_header
, &local_err
)) {
1427 error_propagate(errp
, local_err
);
1432 /* qcow2_read_extension may have set up the crypto context
1433 * if the crypt method needs a header region, some methods
1434 * don't need header extensions, so must check here
1436 if (s
->crypt_method_header
&& !s
->crypto
) {
1437 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1438 unsigned int cflags
= 0;
1439 if (flags
& BDRV_O_NO_IO
) {
1440 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1442 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1443 NULL
, NULL
, cflags
, errp
);
1448 } else if (!(flags
& BDRV_O_NO_IO
)) {
1449 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1450 s
->crypt_method_header
);
1456 /* read the backing file name */
1457 if (header
.backing_file_offset
!= 0) {
1458 len
= header
.backing_file_size
;
1459 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1460 len
>= sizeof(bs
->backing_file
)) {
1461 error_setg(errp
, "Backing file name too long");
1465 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1466 bs
->backing_file
, len
);
1468 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1471 bs
->backing_file
[len
] = '\0';
1472 s
->image_backing_file
= g_strdup(bs
->backing_file
);
1475 /* Internal snapshots */
1476 s
->snapshots_offset
= header
.snapshots_offset
;
1477 s
->nb_snapshots
= header
.nb_snapshots
;
1479 ret
= qcow2_read_snapshots(bs
);
1481 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1485 /* Clear unknown autoclear feature bits */
1486 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1488 update_header
&& !bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
);
1489 if (update_header
) {
1490 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1493 if (s
->dirty_bitmaps_loaded
) {
1494 /* It's some kind of reopen. There are no known cases where we need to
1495 * reload bitmaps in such a situation, so it's safer to skip them.
1497 * Moreover, if we have some readonly bitmaps and we are reopening for
1498 * rw we should reopen bitmaps correspondingly.
1500 if (bdrv_has_readonly_bitmaps(bs
) &&
1501 !bdrv_is_read_only(bs
) && !(bdrv_get_flags(bs
) & BDRV_O_INACTIVE
))
1503 qcow2_reopen_bitmaps_rw_hint(bs
, &header_updated
, &local_err
);
1506 header_updated
= qcow2_load_dirty_bitmaps(bs
, &local_err
);
1507 s
->dirty_bitmaps_loaded
= true;
1509 update_header
= update_header
&& !header_updated
;
1510 if (local_err
!= NULL
) {
1511 error_propagate(errp
, local_err
);
1516 if (update_header
) {
1517 ret
= qcow2_update_header(bs
);
1519 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1524 bs
->supported_zero_flags
= header
.version
>= 3 ? BDRV_REQ_MAY_UNMAP
: 0;
1526 /* Repair image if dirty */
1527 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1528 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1529 BdrvCheckResult result
= {0};
1531 ret
= qcow2_co_check_locked(bs
, &result
,
1532 BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1533 if (ret
< 0 || result
.check_errors
) {
1537 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1544 BdrvCheckResult result
= {0};
1545 qcow2_check_refcounts(bs
, &result
, 0);
1549 qemu_co_queue_init(&s
->compress_wait_queue
);
1554 g_free(s
->unknown_header_fields
);
1555 cleanup_unknown_header_ext(bs
);
1556 qcow2_free_snapshots(bs
);
1557 qcow2_refcount_close(bs
);
1558 qemu_vfree(s
->l1_table
);
1559 /* else pre-write overlap checks in cache_destroy may crash */
1561 cache_clean_timer_del(bs
);
1562 if (s
->l2_table_cache
) {
1563 qcow2_cache_destroy(s
->l2_table_cache
);
1565 if (s
->refcount_block_cache
) {
1566 qcow2_cache_destroy(s
->refcount_block_cache
);
1568 qcrypto_block_free(s
->crypto
);
1569 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1573 typedef struct QCow2OpenCo
{
1574 BlockDriverState
*bs
;
1581 static void coroutine_fn
qcow2_open_entry(void *opaque
)
1583 QCow2OpenCo
*qoc
= opaque
;
1584 BDRVQcow2State
*s
= qoc
->bs
->opaque
;
1586 qemu_co_mutex_lock(&s
->lock
);
1587 qoc
->ret
= qcow2_do_open(qoc
->bs
, qoc
->options
, qoc
->flags
, qoc
->errp
);
1588 qemu_co_mutex_unlock(&s
->lock
);
1591 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1594 BDRVQcow2State
*s
= bs
->opaque
;
1603 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1609 /* Initialise locks */
1610 qemu_co_mutex_init(&s
->lock
);
1612 if (qemu_in_coroutine()) {
1613 /* From bdrv_co_create. */
1614 qcow2_open_entry(&qoc
);
1616 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry
, &qoc
));
1617 BDRV_POLL_WHILE(bs
, qoc
.ret
== -EINPROGRESS
);
1622 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1624 BDRVQcow2State
*s
= bs
->opaque
;
1626 if (bs
->encrypted
) {
1627 /* Encryption works on a sector granularity */
1628 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1630 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1631 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1634 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1635 BlockReopenQueue
*queue
, Error
**errp
)
1637 Qcow2ReopenState
*r
;
1640 r
= g_new0(Qcow2ReopenState
, 1);
1643 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1644 state
->flags
, errp
);
1649 /* We need to write out any unwritten data if we reopen read-only. */
1650 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1651 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1656 ret
= bdrv_flush(state
->bs
);
1661 ret
= qcow2_mark_clean(state
->bs
);
1670 qcow2_update_options_abort(state
->bs
, r
);
1675 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1677 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1678 g_free(state
->opaque
);
1681 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1683 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1684 g_free(state
->opaque
);
1687 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1689 bool has_new_overlap_template
=
1690 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1691 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1692 bool has_new_total_cache_size
=
1693 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1694 bool has_all_cache_options
;
1696 /* New overlap template overrides all old overlap options */
1697 if (has_new_overlap_template
) {
1698 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1699 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1700 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1701 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1702 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1703 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1704 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1705 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1706 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1707 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1710 /* New total cache size overrides all old options */
1711 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1712 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1713 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1716 qdict_join(options
, old_options
, false);
1719 * If after merging all cache size options are set, an old total size is
1720 * overwritten. Do keep all options, however, if all three are new. The
1721 * resulting error message is what we want to happen.
1723 has_all_cache_options
=
1724 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1725 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1726 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1728 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1729 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1733 static int coroutine_fn
qcow2_co_block_status(BlockDriverState
*bs
,
1735 int64_t offset
, int64_t count
,
1736 int64_t *pnum
, int64_t *map
,
1737 BlockDriverState
**file
)
1739 BDRVQcow2State
*s
= bs
->opaque
;
1740 uint64_t cluster_offset
;
1741 int index_in_cluster
, ret
;
1745 bytes
= MIN(INT_MAX
, count
);
1746 qemu_co_mutex_lock(&s
->lock
);
1747 ret
= qcow2_get_cluster_offset(bs
, offset
, &bytes
, &cluster_offset
);
1748 qemu_co_mutex_unlock(&s
->lock
);
1755 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1757 index_in_cluster
= offset
& (s
->cluster_size
- 1);
1758 *map
= cluster_offset
| index_in_cluster
;
1759 *file
= bs
->file
->bs
;
1760 status
|= BDRV_BLOCK_OFFSET_VALID
;
1762 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1763 status
|= BDRV_BLOCK_ZERO
;
1764 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1765 status
|= BDRV_BLOCK_DATA
;
1770 static coroutine_fn
int qcow2_handle_l2meta(BlockDriverState
*bs
,
1771 QCowL2Meta
**pl2meta
,
1775 QCowL2Meta
*l2meta
= *pl2meta
;
1777 while (l2meta
!= NULL
) {
1781 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1786 qcow2_alloc_cluster_abort(bs
, l2meta
);
1789 /* Take the request off the list of running requests */
1790 if (l2meta
->nb_clusters
!= 0) {
1791 QLIST_REMOVE(l2meta
, next_in_flight
);
1794 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1796 next
= l2meta
->next
;
1805 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1806 uint64_t bytes
, QEMUIOVector
*qiov
,
1809 BDRVQcow2State
*s
= bs
->opaque
;
1810 int offset_in_cluster
;
1812 unsigned int cur_bytes
; /* number of bytes in current iteration */
1813 uint64_t cluster_offset
= 0;
1814 uint64_t bytes_done
= 0;
1815 QEMUIOVector hd_qiov
;
1816 uint8_t *cluster_data
= NULL
;
1818 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1820 qemu_co_mutex_lock(&s
->lock
);
1822 while (bytes
!= 0) {
1824 /* prepare next request */
1825 cur_bytes
= MIN(bytes
, INT_MAX
);
1827 cur_bytes
= MIN(cur_bytes
,
1828 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1831 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1836 offset_in_cluster
= offset_into_cluster(s
, offset
);
1838 qemu_iovec_reset(&hd_qiov
);
1839 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1842 case QCOW2_CLUSTER_UNALLOCATED
:
1845 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1846 qemu_co_mutex_unlock(&s
->lock
);
1847 ret
= bdrv_co_preadv(bs
->backing
, offset
, cur_bytes
,
1849 qemu_co_mutex_lock(&s
->lock
);
1854 /* Note: in this case, no need to wait */
1855 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1859 case QCOW2_CLUSTER_ZERO_PLAIN
:
1860 case QCOW2_CLUSTER_ZERO_ALLOC
:
1861 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1864 case QCOW2_CLUSTER_COMPRESSED
:
1865 /* add AIO support for compressed blocks ? */
1866 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1871 qemu_iovec_from_buf(&hd_qiov
, 0,
1872 s
->cluster_cache
+ offset_in_cluster
,
1876 case QCOW2_CLUSTER_NORMAL
:
1877 if ((cluster_offset
& 511) != 0) {
1882 if (bs
->encrypted
) {
1886 * For encrypted images, read everything into a temporary
1887 * contiguous buffer on which the AES functions can work.
1889 if (!cluster_data
) {
1891 qemu_try_blockalign(bs
->file
->bs
,
1892 QCOW_MAX_CRYPT_CLUSTERS
1894 if (cluster_data
== NULL
) {
1900 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1901 qemu_iovec_reset(&hd_qiov
);
1902 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1905 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1906 qemu_co_mutex_unlock(&s
->lock
);
1907 ret
= bdrv_co_preadv(bs
->file
,
1908 cluster_offset
+ offset_in_cluster
,
1909 cur_bytes
, &hd_qiov
, 0);
1910 qemu_co_mutex_lock(&s
->lock
);
1914 if (bs
->encrypted
) {
1916 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1917 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1918 if (qcrypto_block_decrypt(s
->crypto
,
1919 (s
->crypt_physical_offset
?
1920 cluster_offset
+ offset_in_cluster
:
1928 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1933 g_assert_not_reached();
1939 offset
+= cur_bytes
;
1940 bytes_done
+= cur_bytes
;
1945 qemu_co_mutex_unlock(&s
->lock
);
1947 qemu_iovec_destroy(&hd_qiov
);
1948 qemu_vfree(cluster_data
);
1953 /* Check if it's possible to merge a write request with the writing of
1954 * the data from the COW regions */
1955 static bool merge_cow(uint64_t offset
, unsigned bytes
,
1956 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
1960 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
1961 /* If both COW regions are empty then there's nothing to merge */
1962 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
1966 /* The data (middle) region must be immediately after the
1968 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
1972 /* The end region must be immediately after the data (middle)
1974 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
1978 /* Make sure that adding both COW regions to the QEMUIOVector
1979 * does not exceed IOV_MAX */
1980 if (hd_qiov
->niov
> IOV_MAX
- 2) {
1984 m
->data_qiov
= hd_qiov
;
1991 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1992 uint64_t bytes
, QEMUIOVector
*qiov
,
1995 BDRVQcow2State
*s
= bs
->opaque
;
1996 int offset_in_cluster
;
1998 unsigned int cur_bytes
; /* number of sectors in current iteration */
1999 uint64_t cluster_offset
;
2000 QEMUIOVector hd_qiov
;
2001 uint64_t bytes_done
= 0;
2002 uint8_t *cluster_data
= NULL
;
2003 QCowL2Meta
*l2meta
= NULL
;
2005 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
2007 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
2009 s
->cluster_cache_offset
= -1; /* disable compressed cache */
2011 qemu_co_mutex_lock(&s
->lock
);
2013 while (bytes
!= 0) {
2017 trace_qcow2_writev_start_part(qemu_coroutine_self());
2018 offset_in_cluster
= offset_into_cluster(s
, offset
);
2019 cur_bytes
= MIN(bytes
, INT_MAX
);
2020 if (bs
->encrypted
) {
2021 cur_bytes
= MIN(cur_bytes
,
2022 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
2023 - offset_in_cluster
);
2026 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2027 &cluster_offset
, &l2meta
);
2032 assert((cluster_offset
& 511) == 0);
2034 qemu_iovec_reset(&hd_qiov
);
2035 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
2037 if (bs
->encrypted
) {
2039 if (!cluster_data
) {
2040 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
2041 QCOW_MAX_CRYPT_CLUSTERS
2043 if (cluster_data
== NULL
) {
2049 assert(hd_qiov
.size
<=
2050 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2051 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
2053 if (qcrypto_block_encrypt(s
->crypto
,
2054 (s
->crypt_physical_offset
?
2055 cluster_offset
+ offset_in_cluster
:
2058 cur_bytes
, NULL
) < 0) {
2063 qemu_iovec_reset(&hd_qiov
);
2064 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
2067 ret
= qcow2_pre_write_overlap_check(bs
, 0,
2068 cluster_offset
+ offset_in_cluster
, cur_bytes
);
2073 /* If we need to do COW, check if it's possible to merge the
2074 * writing of the guest data together with that of the COW regions.
2075 * If it's not possible (or not necessary) then write the
2076 * guest data now. */
2077 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
2078 qemu_co_mutex_unlock(&s
->lock
);
2079 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
2080 trace_qcow2_writev_data(qemu_coroutine_self(),
2081 cluster_offset
+ offset_in_cluster
);
2082 ret
= bdrv_co_pwritev(bs
->file
,
2083 cluster_offset
+ offset_in_cluster
,
2084 cur_bytes
, &hd_qiov
, 0);
2085 qemu_co_mutex_lock(&s
->lock
);
2091 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
2097 offset
+= cur_bytes
;
2098 bytes_done
+= cur_bytes
;
2099 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2104 qcow2_handle_l2meta(bs
, &l2meta
, false);
2106 qemu_co_mutex_unlock(&s
->lock
);
2108 qemu_iovec_destroy(&hd_qiov
);
2109 qemu_vfree(cluster_data
);
2110 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2115 static int qcow2_inactivate(BlockDriverState
*bs
)
2117 BDRVQcow2State
*s
= bs
->opaque
;
2118 int ret
, result
= 0;
2119 Error
*local_err
= NULL
;
2121 qcow2_store_persistent_dirty_bitmaps(bs
, &local_err
);
2122 if (local_err
!= NULL
) {
2124 error_report_err(local_err
);
2125 error_report("Persistent bitmaps are lost for node '%s'",
2126 bdrv_get_device_or_node_name(bs
));
2129 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2132 error_report("Failed to flush the L2 table cache: %s",
2136 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2139 error_report("Failed to flush the refcount block cache: %s",
2144 qcow2_mark_clean(bs
);
2150 static void qcow2_close(BlockDriverState
*bs
)
2152 BDRVQcow2State
*s
= bs
->opaque
;
2153 qemu_vfree(s
->l1_table
);
2154 /* else pre-write overlap checks in cache_destroy may crash */
2157 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2158 qcow2_inactivate(bs
);
2161 cache_clean_timer_del(bs
);
2162 qcow2_cache_destroy(s
->l2_table_cache
);
2163 qcow2_cache_destroy(s
->refcount_block_cache
);
2165 qcrypto_block_free(s
->crypto
);
2168 g_free(s
->unknown_header_fields
);
2169 cleanup_unknown_header_ext(bs
);
2171 g_free(s
->image_backing_file
);
2172 g_free(s
->image_backing_format
);
2174 g_free(s
->cluster_cache
);
2175 qemu_vfree(s
->cluster_data
);
2176 qcow2_refcount_close(bs
);
2177 qcow2_free_snapshots(bs
);
2180 static void coroutine_fn
qcow2_co_invalidate_cache(BlockDriverState
*bs
,
2183 BDRVQcow2State
*s
= bs
->opaque
;
2184 int flags
= s
->flags
;
2185 QCryptoBlock
*crypto
= NULL
;
2187 Error
*local_err
= NULL
;
2191 * Backing files are read-only which makes all of their metadata immutable,
2192 * that means we don't have to worry about reopening them here.
2200 memset(s
, 0, sizeof(BDRVQcow2State
));
2201 options
= qdict_clone_shallow(bs
->options
);
2203 flags
&= ~BDRV_O_INACTIVE
;
2204 qemu_co_mutex_lock(&s
->lock
);
2205 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2206 qemu_co_mutex_unlock(&s
->lock
);
2207 qobject_unref(options
);
2209 error_propagate(errp
, local_err
);
2210 error_prepend(errp
, "Could not reopen qcow2 layer: ");
2213 } else if (ret
< 0) {
2214 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2222 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2223 size_t len
, size_t buflen
)
2225 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2226 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2228 if (buflen
< ext_len
) {
2232 *ext_backing_fmt
= (QCowExtension
) {
2233 .magic
= cpu_to_be32(magic
),
2234 .len
= cpu_to_be32(len
),
2238 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2245 * Updates the qcow2 header, including the variable length parts of it, i.e.
2246 * the backing file name and all extensions. qcow2 was not designed to allow
2247 * such changes, so if we run out of space (we can only use the first cluster)
2248 * this function may fail.
2250 * Returns 0 on success, -errno in error cases.
2252 int qcow2_update_header(BlockDriverState
*bs
)
2254 BDRVQcow2State
*s
= bs
->opaque
;
2257 size_t buflen
= s
->cluster_size
;
2259 uint64_t total_size
;
2260 uint32_t refcount_table_clusters
;
2261 size_t header_length
;
2262 Qcow2UnknownHeaderExtension
*uext
;
2264 buf
= qemu_blockalign(bs
, buflen
);
2266 /* Header structure */
2267 header
= (QCowHeader
*) buf
;
2269 if (buflen
< sizeof(*header
)) {
2274 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2275 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2276 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2278 *header
= (QCowHeader
) {
2279 /* Version 2 fields */
2280 .magic
= cpu_to_be32(QCOW_MAGIC
),
2281 .version
= cpu_to_be32(s
->qcow_version
),
2282 .backing_file_offset
= 0,
2283 .backing_file_size
= 0,
2284 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2285 .size
= cpu_to_be64(total_size
),
2286 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2287 .l1_size
= cpu_to_be32(s
->l1_size
),
2288 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2289 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2290 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2291 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2292 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2294 /* Version 3 fields */
2295 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2296 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2297 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2298 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2299 .header_length
= cpu_to_be32(header_length
),
2302 /* For older versions, write a shorter header */
2303 switch (s
->qcow_version
) {
2305 ret
= offsetof(QCowHeader
, incompatible_features
);
2308 ret
= sizeof(*header
);
2317 memset(buf
, 0, buflen
);
2319 /* Preserve any unknown field in the header */
2320 if (s
->unknown_header_fields_size
) {
2321 if (buflen
< s
->unknown_header_fields_size
) {
2326 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2327 buf
+= s
->unknown_header_fields_size
;
2328 buflen
-= s
->unknown_header_fields_size
;
2331 /* Backing file format header extension */
2332 if (s
->image_backing_format
) {
2333 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2334 s
->image_backing_format
,
2335 strlen(s
->image_backing_format
),
2345 /* Full disk encryption header pointer extension */
2346 if (s
->crypto_header
.offset
!= 0) {
2347 cpu_to_be64s(&s
->crypto_header
.offset
);
2348 cpu_to_be64s(&s
->crypto_header
.length
);
2349 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2350 &s
->crypto_header
, sizeof(s
->crypto_header
),
2352 be64_to_cpus(&s
->crypto_header
.offset
);
2353 be64_to_cpus(&s
->crypto_header
.length
);
2362 if (s
->qcow_version
>= 3) {
2363 Qcow2Feature features
[] = {
2365 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2366 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2367 .name
= "dirty bit",
2370 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2371 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2372 .name
= "corrupt bit",
2375 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2376 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2377 .name
= "lazy refcounts",
2381 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2382 features
, sizeof(features
), buflen
);
2390 /* Bitmap extension */
2391 if (s
->nb_bitmaps
> 0) {
2392 Qcow2BitmapHeaderExt bitmaps_header
= {
2393 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2394 .bitmap_directory_size
=
2395 cpu_to_be64(s
->bitmap_directory_size
),
2396 .bitmap_directory_offset
=
2397 cpu_to_be64(s
->bitmap_directory_offset
)
2399 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2400 &bitmaps_header
, sizeof(bitmaps_header
),
2409 /* Keep unknown header extensions */
2410 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2411 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2420 /* End of header extensions */
2421 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2429 /* Backing file name */
2430 if (s
->image_backing_file
) {
2431 size_t backing_file_len
= strlen(s
->image_backing_file
);
2433 if (buflen
< backing_file_len
) {
2438 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2439 strncpy(buf
, s
->image_backing_file
, buflen
);
2441 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2442 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2445 /* Write the new header */
2446 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2457 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2458 const char *backing_file
, const char *backing_fmt
)
2460 BDRVQcow2State
*s
= bs
->opaque
;
2462 if (backing_file
&& strlen(backing_file
) > 1023) {
2466 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2467 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2469 g_free(s
->image_backing_file
);
2470 g_free(s
->image_backing_format
);
2472 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2473 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2475 return qcow2_update_header(bs
);
2478 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2480 if (g_str_equal(encryptfmt
, "luks")) {
2481 return QCOW_CRYPT_LUKS
;
2482 } else if (g_str_equal(encryptfmt
, "aes")) {
2483 return QCOW_CRYPT_AES
;
2489 static int qcow2_set_up_encryption(BlockDriverState
*bs
,
2490 QCryptoBlockCreateOptions
*cryptoopts
,
2493 BDRVQcow2State
*s
= bs
->opaque
;
2494 QCryptoBlock
*crypto
= NULL
;
2497 switch (cryptoopts
->format
) {
2498 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
2499 fmt
= QCOW_CRYPT_LUKS
;
2501 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
2502 fmt
= QCOW_CRYPT_AES
;
2505 error_setg(errp
, "Crypto format not supported in qcow2");
2509 s
->crypt_method_header
= fmt
;
2511 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2512 qcow2_crypto_hdr_init_func
,
2513 qcow2_crypto_hdr_write_func
,
2519 ret
= qcow2_update_header(bs
);
2521 error_setg_errno(errp
, -ret
, "Could not write encryption header");
2527 qcrypto_block_free(crypto
);
2532 * Preallocates metadata structures for data clusters between @offset (in the
2533 * guest disk) and @new_length (which is thus generally the new guest disk
2536 * Returns: 0 on success, -errno on failure.
2538 static int coroutine_fn
preallocate_co(BlockDriverState
*bs
, uint64_t offset
,
2539 uint64_t new_length
)
2542 uint64_t host_offset
= 0;
2543 unsigned int cur_bytes
;
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 /* qcow2_refcount_metadata_size:
2600 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2601 * @cluster_size: size of a cluster, in bytes
2602 * @refcount_order: refcount bits power-of-2 exponent
2603 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2606 * Returns: Number of bytes required for refcount blocks and table metadata.
2608 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
2609 int refcount_order
, bool generous_increase
,
2610 uint64_t *refblock_count
)
2613 * Every host cluster is reference-counted, including metadata (even
2614 * refcount metadata is recursively included).
2616 * An accurate formula for the size of refcount metadata size is difficult
2617 * to derive. An easier method of calculation is finding the fixed point
2618 * where no further refcount blocks or table clusters are required to
2619 * reference count every cluster.
2621 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
2622 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
2623 int64_t table
= 0; /* number of refcount table clusters */
2624 int64_t blocks
= 0; /* number of refcount block clusters */
2630 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
2631 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
2632 n
= clusters
+ blocks
+ table
;
2634 if (n
== last
&& generous_increase
) {
2635 clusters
+= DIV_ROUND_UP(table
, 2);
2636 n
= 0; /* force another loop */
2637 generous_increase
= false;
2639 } while (n
!= last
);
2641 if (refblock_count
) {
2642 *refblock_count
= blocks
;
2645 return (blocks
+ table
) * cluster_size
;
2649 * qcow2_calc_prealloc_size:
2650 * @total_size: virtual disk size in bytes
2651 * @cluster_size: cluster size in bytes
2652 * @refcount_order: refcount bits power-of-2 exponent
2654 * Returns: Total number of bytes required for the fully allocated image
2655 * (including metadata).
2657 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
2658 size_t cluster_size
,
2661 int64_t meta_size
= 0;
2662 uint64_t nl1e
, nl2e
;
2663 int64_t aligned_total_size
= ROUND_UP(total_size
, cluster_size
);
2665 /* header: 1 cluster */
2666 meta_size
+= cluster_size
;
2668 /* total size of L2 tables */
2669 nl2e
= aligned_total_size
/ cluster_size
;
2670 nl2e
= ROUND_UP(nl2e
, cluster_size
/ sizeof(uint64_t));
2671 meta_size
+= nl2e
* sizeof(uint64_t);
2673 /* total size of L1 tables */
2674 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2675 nl1e
= ROUND_UP(nl1e
, cluster_size
/ sizeof(uint64_t));
2676 meta_size
+= nl1e
* sizeof(uint64_t);
2678 /* total size of refcount table and blocks */
2679 meta_size
+= qcow2_refcount_metadata_size(
2680 (meta_size
+ aligned_total_size
) / cluster_size
,
2681 cluster_size
, refcount_order
, false, NULL
);
2683 return meta_size
+ aligned_total_size
;
2686 static bool validate_cluster_size(size_t cluster_size
, Error
**errp
)
2688 int cluster_bits
= ctz32(cluster_size
);
2689 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2690 (1 << cluster_bits
) != cluster_size
)
2692 error_setg(errp
, "Cluster size must be a power of two between %d and "
2693 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2699 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
2701 size_t cluster_size
;
2703 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2704 DEFAULT_CLUSTER_SIZE
);
2705 if (!validate_cluster_size(cluster_size
, errp
)) {
2708 return cluster_size
;
2711 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
2716 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2718 ret
= 3; /* default */
2719 } else if (!strcmp(buf
, "0.10")) {
2721 } else if (!strcmp(buf
, "1.1")) {
2724 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2731 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
2734 uint64_t refcount_bits
;
2736 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
2737 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2738 error_setg(errp
, "Refcount width must be a power of two and may not "
2743 if (version
< 3 && refcount_bits
!= 16) {
2744 error_setg(errp
, "Different refcount widths than 16 bits require "
2745 "compatibility level 1.1 or above (use compat=1.1 or "
2750 return refcount_bits
;
2753 static int coroutine_fn
2754 qcow2_co_create(BlockdevCreateOptions
*create_options
, Error
**errp
)
2756 BlockdevCreateOptionsQcow2
*qcow2_opts
;
2760 * Open the image file and write a minimal qcow2 header.
2762 * We keep things simple and start with a zero-sized image. We also
2763 * do without refcount blocks or a L1 table for now. We'll fix the
2764 * inconsistency later.
2766 * We do need a refcount table because growing the refcount table means
2767 * allocating two new refcount blocks - the seconds of which would be at
2768 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2769 * size for any qcow2 image.
2771 BlockBackend
*blk
= NULL
;
2772 BlockDriverState
*bs
= NULL
;
2774 size_t cluster_size
;
2777 uint64_t* refcount_table
;
2778 Error
*local_err
= NULL
;
2781 assert(create_options
->driver
== BLOCKDEV_DRIVER_QCOW2
);
2782 qcow2_opts
= &create_options
->u
.qcow2
;
2784 bs
= bdrv_open_blockdev_ref(qcow2_opts
->file
, errp
);
2789 /* Validate options and set default values */
2790 if (!QEMU_IS_ALIGNED(qcow2_opts
->size
, BDRV_SECTOR_SIZE
)) {
2791 error_setg(errp
, "Image size must be a multiple of 512 bytes");
2796 if (qcow2_opts
->has_version
) {
2797 switch (qcow2_opts
->version
) {
2798 case BLOCKDEV_QCOW2_VERSION_V2
:
2801 case BLOCKDEV_QCOW2_VERSION_V3
:
2805 g_assert_not_reached();
2811 if (qcow2_opts
->has_cluster_size
) {
2812 cluster_size
= qcow2_opts
->cluster_size
;
2814 cluster_size
= DEFAULT_CLUSTER_SIZE
;
2817 if (!validate_cluster_size(cluster_size
, errp
)) {
2822 if (!qcow2_opts
->has_preallocation
) {
2823 qcow2_opts
->preallocation
= PREALLOC_MODE_OFF
;
2825 if (qcow2_opts
->has_backing_file
&&
2826 qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
)
2828 error_setg(errp
, "Backing file and preallocation cannot be used at "
2833 if (qcow2_opts
->has_backing_fmt
&& !qcow2_opts
->has_backing_file
) {
2834 error_setg(errp
, "Backing format cannot be used without backing file");
2839 if (!qcow2_opts
->has_lazy_refcounts
) {
2840 qcow2_opts
->lazy_refcounts
= false;
2842 if (version
< 3 && qcow2_opts
->lazy_refcounts
) {
2843 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2844 "level 1.1 and above (use version=v3 or greater)");
2849 if (!qcow2_opts
->has_refcount_bits
) {
2850 qcow2_opts
->refcount_bits
= 16;
2852 if (qcow2_opts
->refcount_bits
> 64 ||
2853 !is_power_of_2(qcow2_opts
->refcount_bits
))
2855 error_setg(errp
, "Refcount width must be a power of two and may not "
2860 if (version
< 3 && qcow2_opts
->refcount_bits
!= 16) {
2861 error_setg(errp
, "Different refcount widths than 16 bits require "
2862 "compatibility level 1.1 or above (use version=v3 or "
2867 refcount_order
= ctz32(qcow2_opts
->refcount_bits
);
2870 /* Create BlockBackend to write to the image */
2871 blk
= blk_new(BLK_PERM_WRITE
| BLK_PERM_RESIZE
, BLK_PERM_ALL
);
2872 ret
= blk_insert_bs(blk
, bs
, errp
);
2876 blk_set_allow_write_beyond_eof(blk
, true);
2878 /* Clear the protocol layer and preallocate it if necessary */
2879 ret
= blk_truncate(blk
, 0, PREALLOC_MODE_OFF
, errp
);
2884 if (qcow2_opts
->preallocation
== PREALLOC_MODE_FULL
||
2885 qcow2_opts
->preallocation
== PREALLOC_MODE_FALLOC
)
2887 int64_t prealloc_size
=
2888 qcow2_calc_prealloc_size(qcow2_opts
->size
, cluster_size
,
2891 ret
= blk_truncate(blk
, prealloc_size
, qcow2_opts
->preallocation
, errp
);
2897 /* Write the header */
2898 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2899 header
= g_malloc0(cluster_size
);
2900 *header
= (QCowHeader
) {
2901 .magic
= cpu_to_be32(QCOW_MAGIC
),
2902 .version
= cpu_to_be32(version
),
2903 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
2904 .size
= cpu_to_be64(0),
2905 .l1_table_offset
= cpu_to_be64(0),
2906 .l1_size
= cpu_to_be32(0),
2907 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2908 .refcount_table_clusters
= cpu_to_be32(1),
2909 .refcount_order
= cpu_to_be32(refcount_order
),
2910 .header_length
= cpu_to_be32(sizeof(*header
)),
2913 /* We'll update this to correct value later */
2914 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2916 if (qcow2_opts
->lazy_refcounts
) {
2917 header
->compatible_features
|=
2918 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2921 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2924 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2928 /* Write a refcount table with one refcount block */
2929 refcount_table
= g_malloc0(2 * cluster_size
);
2930 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2931 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2932 g_free(refcount_table
);
2935 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2943 * And now open the image and make it consistent first (i.e. increase the
2944 * refcount of the cluster that is occupied by the header and the refcount
2947 options
= qdict_new();
2948 qdict_put_str(options
, "driver", "qcow2");
2949 qdict_put_str(options
, "file", bs
->node_name
);
2950 blk
= blk_new_open(NULL
, NULL
, options
,
2951 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
2954 error_propagate(errp
, local_err
);
2959 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2961 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2962 "header and refcount table");
2965 } else if (ret
!= 0) {
2966 error_report("Huh, first cluster in empty image is already in use?");
2970 /* Create a full header (including things like feature table) */
2971 ret
= qcow2_update_header(blk_bs(blk
));
2973 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
2977 /* Okay, now that we have a valid image, let's give it the right size */
2978 ret
= blk_truncate(blk
, qcow2_opts
->size
, PREALLOC_MODE_OFF
, errp
);
2980 error_prepend(errp
, "Could not resize image: ");
2984 /* Want a backing file? There you go.*/
2985 if (qcow2_opts
->has_backing_file
) {
2986 const char *backing_format
= NULL
;
2988 if (qcow2_opts
->has_backing_fmt
) {
2989 backing_format
= BlockdevDriver_str(qcow2_opts
->backing_fmt
);
2992 ret
= bdrv_change_backing_file(blk_bs(blk
), qcow2_opts
->backing_file
,
2995 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
2996 "with format '%s'", qcow2_opts
->backing_file
,
3002 /* Want encryption? There you go. */
3003 if (qcow2_opts
->has_encrypt
) {
3004 ret
= qcow2_set_up_encryption(blk_bs(blk
), qcow2_opts
->encrypt
, errp
);
3010 /* And if we're supposed to preallocate metadata, do that now */
3011 if (qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
) {
3012 BDRVQcow2State
*s
= blk_bs(blk
)->opaque
;
3013 qemu_co_mutex_lock(&s
->lock
);
3014 ret
= preallocate_co(blk_bs(blk
), 0, qcow2_opts
->size
);
3015 qemu_co_mutex_unlock(&s
->lock
);
3018 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
3026 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3027 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3028 * have to setup decryption context. We're not doing any I/O on the top
3029 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3032 options
= qdict_new();
3033 qdict_put_str(options
, "driver", "qcow2");
3034 qdict_put_str(options
, "file", bs
->node_name
);
3035 blk
= blk_new_open(NULL
, NULL
, options
,
3036 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
3039 error_propagate(errp
, local_err
);
3051 static int coroutine_fn
qcow2_co_create_opts(const char *filename
, QemuOpts
*opts
,
3054 BlockdevCreateOptions
*create_options
= NULL
;
3057 BlockDriverState
*bs
= NULL
;
3058 Error
*local_err
= NULL
;
3062 /* Only the keyval visitor supports the dotted syntax needed for
3063 * encryption, so go through a QDict before getting a QAPI type. Ignore
3064 * options meant for the protocol layer so that the visitor doesn't
3066 qdict
= qemu_opts_to_qdict_filtered(opts
, NULL
, bdrv_qcow2
.create_opts
,
3069 /* Handle encryption options */
3070 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT
);
3071 if (val
&& !strcmp(val
, "on")) {
3072 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT
, "qcow");
3073 } else if (val
&& !strcmp(val
, "off")) {
3074 qdict_del(qdict
, BLOCK_OPT_ENCRYPT
);
3077 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
);
3078 if (val
&& !strcmp(val
, "aes")) {
3079 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
, "qcow");
3082 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3083 * version=v2/v3 below. */
3084 val
= qdict_get_try_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
);
3085 if (val
&& !strcmp(val
, "0.10")) {
3086 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v2");
3087 } else if (val
&& !strcmp(val
, "1.1")) {
3088 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v3");
3091 /* Change legacy command line options into QMP ones */
3092 static const QDictRenames opt_renames
[] = {
3093 { BLOCK_OPT_BACKING_FILE
, "backing-file" },
3094 { BLOCK_OPT_BACKING_FMT
, "backing-fmt" },
3095 { BLOCK_OPT_CLUSTER_SIZE
, "cluster-size" },
3096 { BLOCK_OPT_LAZY_REFCOUNTS
, "lazy-refcounts" },
3097 { BLOCK_OPT_REFCOUNT_BITS
, "refcount-bits" },
3098 { BLOCK_OPT_ENCRYPT
, BLOCK_OPT_ENCRYPT_FORMAT
},
3099 { BLOCK_OPT_COMPAT_LEVEL
, "version" },
3103 if (!qdict_rename_keys(qdict
, opt_renames
, errp
)) {
3108 /* Create and open the file (protocol layer) */
3109 ret
= bdrv_create_file(filename
, opts
, errp
);
3114 bs
= bdrv_open(filename
, NULL
, NULL
,
3115 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
, errp
);
3121 /* Set 'driver' and 'node' options */
3122 qdict_put_str(qdict
, "driver", "qcow2");
3123 qdict_put_str(qdict
, "file", bs
->node_name
);
3125 /* Now get the QAPI type BlockdevCreateOptions */
3126 v
= qobject_input_visitor_new_flat_confused(qdict
, errp
);
3132 visit_type_BlockdevCreateOptions(v
, NULL
, &create_options
, &local_err
);
3136 error_propagate(errp
, local_err
);
3141 /* Silently round up size */
3142 create_options
->u
.qcow2
.size
= ROUND_UP(create_options
->u
.qcow2
.size
,
3145 /* Create the qcow2 image (format layer) */
3146 ret
= qcow2_co_create(create_options
, errp
);
3153 qobject_unref(qdict
);
3155 qapi_free_BlockdevCreateOptions(create_options
);
3160 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3165 /* Clamp to image length, before checking status of underlying sectors */
3166 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3167 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3173 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3174 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3177 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3178 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3181 BDRVQcow2State
*s
= bs
->opaque
;
3183 uint32_t head
= offset
% s
->cluster_size
;
3184 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3186 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3187 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3195 assert(head
+ bytes
<= s
->cluster_size
);
3197 /* check whether remainder of cluster already reads as zero */
3198 if (!(is_zero(bs
, offset
- head
, head
) &&
3199 is_zero(bs
, offset
+ bytes
,
3200 tail
? s
->cluster_size
- tail
: 0))) {
3204 qemu_co_mutex_lock(&s
->lock
);
3205 /* We can have new write after previous check */
3206 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3207 bytes
= s
->cluster_size
;
3208 nr
= s
->cluster_size
;
3209 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3210 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3211 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3212 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3213 qemu_co_mutex_unlock(&s
->lock
);
3217 qemu_co_mutex_lock(&s
->lock
);
3220 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3222 /* Whatever is left can use real zero clusters */
3223 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3224 qemu_co_mutex_unlock(&s
->lock
);
3229 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3230 int64_t offset
, int bytes
)
3233 BDRVQcow2State
*s
= bs
->opaque
;
3235 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3236 assert(bytes
< s
->cluster_size
);
3237 /* Ignore partial clusters, except for the special case of the
3238 * complete partial cluster at the end of an unaligned file */
3239 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3240 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3245 qemu_co_mutex_lock(&s
->lock
);
3246 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3248 qemu_co_mutex_unlock(&s
->lock
);
3252 static int coroutine_fn
3253 qcow2_co_copy_range_from(BlockDriverState
*bs
,
3254 BdrvChild
*src
, uint64_t src_offset
,
3255 BdrvChild
*dst
, uint64_t dst_offset
,
3256 uint64_t bytes
, BdrvRequestFlags read_flags
,
3257 BdrvRequestFlags write_flags
)
3259 BDRVQcow2State
*s
= bs
->opaque
;
3261 unsigned int cur_bytes
; /* number of bytes in current iteration */
3262 BdrvChild
*child
= NULL
;
3263 BdrvRequestFlags cur_write_flags
;
3265 assert(!bs
->encrypted
);
3266 qemu_co_mutex_lock(&s
->lock
);
3268 while (bytes
!= 0) {
3269 uint64_t copy_offset
= 0;
3270 /* prepare next request */
3271 cur_bytes
= MIN(bytes
, INT_MAX
);
3272 cur_write_flags
= write_flags
;
3274 ret
= qcow2_get_cluster_offset(bs
, src_offset
, &cur_bytes
, ©_offset
);
3280 case QCOW2_CLUSTER_UNALLOCATED
:
3281 if (bs
->backing
&& bs
->backing
->bs
) {
3282 int64_t backing_length
= bdrv_getlength(bs
->backing
->bs
);
3283 if (src_offset
>= backing_length
) {
3284 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3286 child
= bs
->backing
;
3287 cur_bytes
= MIN(cur_bytes
, backing_length
- src_offset
);
3288 copy_offset
= src_offset
;
3291 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3295 case QCOW2_CLUSTER_ZERO_PLAIN
:
3296 case QCOW2_CLUSTER_ZERO_ALLOC
:
3297 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3300 case QCOW2_CLUSTER_COMPRESSED
:
3305 case QCOW2_CLUSTER_NORMAL
:
3307 copy_offset
+= offset_into_cluster(s
, src_offset
);
3308 if ((copy_offset
& 511) != 0) {
3317 qemu_co_mutex_unlock(&s
->lock
);
3318 ret
= bdrv_co_copy_range_from(child
,
3321 cur_bytes
, read_flags
, cur_write_flags
);
3322 qemu_co_mutex_lock(&s
->lock
);
3328 src_offset
+= cur_bytes
;
3329 dst_offset
+= cur_bytes
;
3334 qemu_co_mutex_unlock(&s
->lock
);
3338 static int coroutine_fn
3339 qcow2_co_copy_range_to(BlockDriverState
*bs
,
3340 BdrvChild
*src
, uint64_t src_offset
,
3341 BdrvChild
*dst
, uint64_t dst_offset
,
3342 uint64_t bytes
, BdrvRequestFlags read_flags
,
3343 BdrvRequestFlags write_flags
)
3345 BDRVQcow2State
*s
= bs
->opaque
;
3346 int offset_in_cluster
;
3348 unsigned int cur_bytes
; /* number of sectors in current iteration */
3349 uint64_t cluster_offset
;
3350 uint8_t *cluster_data
= NULL
;
3351 QCowL2Meta
*l2meta
= NULL
;
3353 assert(!bs
->encrypted
);
3354 s
->cluster_cache_offset
= -1; /* disable compressed cache */
3356 qemu_co_mutex_lock(&s
->lock
);
3358 while (bytes
!= 0) {
3362 offset_in_cluster
= offset_into_cluster(s
, dst_offset
);
3363 cur_bytes
= MIN(bytes
, INT_MAX
);
3366 * If src->bs == dst->bs, we could simply copy by incrementing
3367 * the refcnt, without copying user data.
3368 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3369 ret
= qcow2_alloc_cluster_offset(bs
, dst_offset
, &cur_bytes
,
3370 &cluster_offset
, &l2meta
);
3375 assert((cluster_offset
& 511) == 0);
3377 ret
= qcow2_pre_write_overlap_check(bs
, 0,
3378 cluster_offset
+ offset_in_cluster
, cur_bytes
);
3383 qemu_co_mutex_unlock(&s
->lock
);
3384 ret
= bdrv_co_copy_range_to(src
, src_offset
,
3386 cluster_offset
+ offset_in_cluster
,
3387 cur_bytes
, read_flags
, write_flags
);
3388 qemu_co_mutex_lock(&s
->lock
);
3393 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
3399 src_offset
+= cur_bytes
;
3400 dst_offset
+= cur_bytes
;
3405 qcow2_handle_l2meta(bs
, &l2meta
, false);
3407 qemu_co_mutex_unlock(&s
->lock
);
3409 qemu_vfree(cluster_data
);
3410 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
3415 static int coroutine_fn
qcow2_co_truncate(BlockDriverState
*bs
, int64_t offset
,
3416 PreallocMode prealloc
, Error
**errp
)
3418 BDRVQcow2State
*s
= bs
->opaque
;
3419 uint64_t old_length
;
3420 int64_t new_l1_size
;
3423 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3424 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3426 error_setg(errp
, "Unsupported preallocation mode '%s'",
3427 PreallocMode_str(prealloc
));
3432 error_setg(errp
, "The new size must be a multiple of 512");
3436 qemu_co_mutex_lock(&s
->lock
);
3438 /* cannot proceed if image has snapshots */
3439 if (s
->nb_snapshots
) {
3440 error_setg(errp
, "Can't resize an image which has snapshots");
3445 /* cannot proceed if image has bitmaps */
3446 if (s
->nb_bitmaps
) {
3447 /* TODO: resize bitmaps in the image */
3448 error_setg(errp
, "Can't resize an image which has bitmaps");
3453 old_length
= bs
->total_sectors
* 512;
3454 new_l1_size
= size_to_l1(s
, offset
);
3456 if (offset
< old_length
) {
3457 int64_t last_cluster
, old_file_size
;
3458 if (prealloc
!= PREALLOC_MODE_OFF
) {
3460 "Preallocation can't be used for shrinking an image");
3465 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3466 old_length
- ROUND_UP(offset
,
3468 QCOW2_DISCARD_ALWAYS
, true);
3470 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3474 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
3476 error_setg_errno(errp
, -ret
,
3477 "Failed to reduce the number of L2 tables");
3481 ret
= qcow2_shrink_reftable(bs
);
3483 error_setg_errno(errp
, -ret
,
3484 "Failed to discard unused refblocks");
3488 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3489 if (old_file_size
< 0) {
3490 error_setg_errno(errp
, -old_file_size
,
3491 "Failed to inquire current file length");
3492 ret
= old_file_size
;
3495 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
3496 if (last_cluster
< 0) {
3497 error_setg_errno(errp
, -last_cluster
,
3498 "Failed to find the last cluster");
3502 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
3503 Error
*local_err
= NULL
;
3505 bdrv_co_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
3506 PREALLOC_MODE_OFF
, &local_err
);
3508 warn_reportf_err(local_err
,
3509 "Failed to truncate the tail of the image: ");
3513 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
3515 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
3521 case PREALLOC_MODE_OFF
:
3524 case PREALLOC_MODE_METADATA
:
3525 ret
= preallocate_co(bs
, old_length
, offset
);
3527 error_setg_errno(errp
, -ret
, "Preallocation failed");
3532 case PREALLOC_MODE_FALLOC
:
3533 case PREALLOC_MODE_FULL
:
3535 int64_t allocation_start
, host_offset
, guest_offset
;
3536 int64_t clusters_allocated
;
3537 int64_t old_file_size
, new_file_size
;
3538 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
3540 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3541 if (old_file_size
< 0) {
3542 error_setg_errno(errp
, -old_file_size
,
3543 "Failed to inquire current file length");
3544 ret
= old_file_size
;
3547 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
3549 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
3552 /* This is an overestimation; we will not actually allocate space for
3553 * these in the file but just make sure the new refcount structures are
3554 * able to cover them so we will not have to allocate new refblocks
3555 * while entering the data blocks in the potentially new L2 tables.
3556 * (We do not actually care where the L2 tables are placed. Maybe they
3557 * are already allocated or they can be placed somewhere before
3558 * @old_file_size. It does not matter because they will be fully
3559 * allocated automatically, so they do not need to be covered by the
3560 * preallocation. All that matters is that we will not have to allocate
3561 * new refcount structures for them.) */
3562 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
3563 s
->cluster_size
/ sizeof(uint64_t));
3564 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3565 * table for a potential head/tail */
3568 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
3569 nb_new_data_clusters
+
3572 if (allocation_start
< 0) {
3573 error_setg_errno(errp
, -allocation_start
,
3574 "Failed to resize refcount structures");
3575 ret
= allocation_start
;
3579 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
3580 nb_new_data_clusters
);
3581 if (clusters_allocated
< 0) {
3582 error_setg_errno(errp
, -clusters_allocated
,
3583 "Failed to allocate data clusters");
3584 ret
= clusters_allocated
;
3588 assert(clusters_allocated
== nb_new_data_clusters
);
3590 /* Allocate the data area */
3591 new_file_size
= allocation_start
+
3592 nb_new_data_clusters
* s
->cluster_size
;
3593 ret
= bdrv_co_truncate(bs
->file
, new_file_size
, prealloc
, errp
);
3595 error_prepend(errp
, "Failed to resize underlying file: ");
3596 qcow2_free_clusters(bs
, allocation_start
,
3597 nb_new_data_clusters
* s
->cluster_size
,
3598 QCOW2_DISCARD_OTHER
);
3602 /* Create the necessary L2 entries */
3603 host_offset
= allocation_start
;
3604 guest_offset
= old_length
;
3605 while (nb_new_data_clusters
) {
3606 int64_t nb_clusters
= MIN(
3607 nb_new_data_clusters
,
3608 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
3609 QCowL2Meta allocation
= {
3610 .offset
= guest_offset
,
3611 .alloc_offset
= host_offset
,
3612 .nb_clusters
= nb_clusters
,
3614 qemu_co_queue_init(&allocation
.dependent_requests
);
3616 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
3618 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
3619 qcow2_free_clusters(bs
, host_offset
,
3620 nb_new_data_clusters
* s
->cluster_size
,
3621 QCOW2_DISCARD_OTHER
);
3625 guest_offset
+= nb_clusters
* s
->cluster_size
;
3626 host_offset
+= nb_clusters
* s
->cluster_size
;
3627 nb_new_data_clusters
-= nb_clusters
;
3633 g_assert_not_reached();
3636 if (prealloc
!= PREALLOC_MODE_OFF
) {
3637 /* Flush metadata before actually changing the image size */
3638 ret
= qcow2_write_caches(bs
);
3640 error_setg_errno(errp
, -ret
,
3641 "Failed to flush the preallocated area to disk");
3646 /* write updated header.size */
3647 offset
= cpu_to_be64(offset
);
3648 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
3649 &offset
, sizeof(uint64_t));
3651 error_setg_errno(errp
, -ret
, "Failed to update the image size");
3655 s
->l1_vm_state_index
= new_l1_size
;
3658 qemu_co_mutex_unlock(&s
->lock
);
3665 * @dest - destination buffer, at least of @size-1 bytes
3666 * @src - source buffer, @size bytes
3668 * Returns: compressed size on success
3669 * -1 if compression is inefficient
3670 * -2 on any other error
3672 static ssize_t
qcow2_compress(void *dest
, const void *src
, size_t size
)
3677 /* best compression, small window, no zlib header */
3678 memset(&strm
, 0, sizeof(strm
));
3679 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
, Z_DEFLATED
,
3680 -12, 9, Z_DEFAULT_STRATEGY
);
3685 /* strm.next_in is not const in old zlib versions, such as those used on
3686 * OpenBSD/NetBSD, so cast the const away */
3687 strm
.avail_in
= size
;
3688 strm
.next_in
= (void *) src
;
3689 strm
.avail_out
= size
- 1;
3690 strm
.next_out
= dest
;
3692 ret
= deflate(&strm
, Z_FINISH
);
3693 if (ret
== Z_STREAM_END
) {
3694 ret
= size
- 1 - strm
.avail_out
;
3696 ret
= (ret
== Z_OK
? -1 : -2);
3704 #define MAX_COMPRESS_THREADS 4
3706 typedef struct Qcow2CompressData
{
3711 } Qcow2CompressData
;
3713 static int qcow2_compress_pool_func(void *opaque
)
3715 Qcow2CompressData
*data
= opaque
;
3717 data
->ret
= qcow2_compress(data
->dest
, data
->src
, data
->size
);
3722 static void qcow2_compress_complete(void *opaque
, int ret
)
3724 qemu_coroutine_enter(opaque
);
3727 /* See qcow2_compress definition for parameters description */
3728 static ssize_t
qcow2_co_compress(BlockDriverState
*bs
,
3729 void *dest
, const void *src
, size_t size
)
3731 BDRVQcow2State
*s
= bs
->opaque
;
3733 ThreadPool
*pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
3734 Qcow2CompressData arg
= {
3740 while (s
->nb_compress_threads
>= MAX_COMPRESS_THREADS
) {
3741 qemu_co_queue_wait(&s
->compress_wait_queue
, NULL
);
3744 s
->nb_compress_threads
++;
3745 acb
= thread_pool_submit_aio(pool
, qcow2_compress_pool_func
, &arg
,
3746 qcow2_compress_complete
,
3747 qemu_coroutine_self());
3750 s
->nb_compress_threads
--;
3753 qemu_coroutine_yield();
3754 s
->nb_compress_threads
--;
3755 qemu_co_queue_next(&s
->compress_wait_queue
);
3760 /* XXX: put compressed sectors first, then all the cluster aligned
3761 tables to avoid losing bytes in alignment */
3762 static coroutine_fn
int
3763 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
3764 uint64_t bytes
, QEMUIOVector
*qiov
)
3766 BDRVQcow2State
*s
= bs
->opaque
;
3767 QEMUIOVector hd_qiov
;
3771 uint8_t *buf
, *out_buf
;
3772 int64_t cluster_offset
;
3775 /* align end of file to a sector boundary to ease reading with
3776 sector based I/Os */
3777 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
3778 if (cluster_offset
< 0) {
3779 return cluster_offset
;
3781 return bdrv_co_truncate(bs
->file
, cluster_offset
, PREALLOC_MODE_OFF
,
3785 if (offset_into_cluster(s
, offset
)) {
3789 buf
= qemu_blockalign(bs
, s
->cluster_size
);
3790 if (bytes
!= s
->cluster_size
) {
3791 if (bytes
> s
->cluster_size
||
3792 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
3797 /* Zero-pad last write if image size is not cluster aligned */
3798 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
3800 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
3802 out_buf
= g_malloc(s
->cluster_size
);
3804 out_len
= qcow2_co_compress(bs
, out_buf
, buf
, s
->cluster_size
);
3805 if (out_len
== -2) {
3808 } else if (out_len
== -1) {
3809 /* could not compress: write normal cluster */
3810 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
3817 qemu_co_mutex_lock(&s
->lock
);
3819 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
3820 if (!cluster_offset
) {
3821 qemu_co_mutex_unlock(&s
->lock
);
3825 cluster_offset
&= s
->cluster_offset_mask
;
3827 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
3828 qemu_co_mutex_unlock(&s
->lock
);
3833 iov
= (struct iovec
) {
3834 .iov_base
= out_buf
,
3837 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
3839 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
3840 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
3852 static int make_completely_empty(BlockDriverState
*bs
)
3854 BDRVQcow2State
*s
= bs
->opaque
;
3855 Error
*local_err
= NULL
;
3856 int ret
, l1_clusters
;
3858 uint64_t *new_reftable
= NULL
;
3859 uint64_t rt_entry
, l1_size2
;
3862 uint64_t reftable_offset
;
3863 uint32_t reftable_clusters
;
3864 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
3866 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
3871 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
3876 /* Refcounts will be broken utterly */
3877 ret
= qcow2_mark_dirty(bs
);
3882 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3884 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3885 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
3887 /* After this call, neither the in-memory nor the on-disk refcount
3888 * information accurately describe the actual references */
3890 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
3891 l1_clusters
* s
->cluster_size
, 0);
3893 goto fail_broken_refcounts
;
3895 memset(s
->l1_table
, 0, l1_size2
);
3897 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
3899 /* Overwrite enough clusters at the beginning of the sectors to place
3900 * the refcount table, a refcount block and the L1 table in; this may
3901 * overwrite parts of the existing refcount and L1 table, which is not
3902 * an issue because the dirty flag is set, complete data loss is in fact
3903 * desired and partial data loss is consequently fine as well */
3904 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
3905 (2 + l1_clusters
) * s
->cluster_size
, 0);
3906 /* This call (even if it failed overall) may have overwritten on-disk
3907 * refcount structures; in that case, the in-memory refcount information
3908 * will probably differ from the on-disk information which makes the BDS
3911 goto fail_broken_refcounts
;
3914 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3915 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
3917 /* "Create" an empty reftable (one cluster) directly after the image
3918 * header and an empty L1 table three clusters after the image header;
3919 * the cluster between those two will be used as the first refblock */
3920 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
3921 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
3922 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
3923 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
3924 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
3926 goto fail_broken_refcounts
;
3929 s
->l1_table_offset
= 3 * s
->cluster_size
;
3931 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
3932 if (!new_reftable
) {
3934 goto fail_broken_refcounts
;
3937 s
->refcount_table_offset
= s
->cluster_size
;
3938 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
3939 s
->max_refcount_table_index
= 0;
3941 g_free(s
->refcount_table
);
3942 s
->refcount_table
= new_reftable
;
3943 new_reftable
= NULL
;
3945 /* Now the in-memory refcount information again corresponds to the on-disk
3946 * information (reftable is empty and no refblocks (the refblock cache is
3947 * empty)); however, this means some clusters (e.g. the image header) are
3948 * referenced, but not refcounted, but the normal qcow2 code assumes that
3949 * the in-memory information is always correct */
3951 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
3953 /* Enter the first refblock into the reftable */
3954 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
3955 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
3956 &rt_entry
, sizeof(rt_entry
));
3958 goto fail_broken_refcounts
;
3960 s
->refcount_table
[0] = 2 * s
->cluster_size
;
3962 s
->free_cluster_index
= 0;
3963 assert(3 + l1_clusters
<= s
->refcount_block_size
);
3964 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
3967 goto fail_broken_refcounts
;
3968 } else if (offset
> 0) {
3969 error_report("First cluster in emptied image is in use");
3973 /* Now finally the in-memory information corresponds to the on-disk
3974 * structures and is correct */
3975 ret
= qcow2_mark_clean(bs
);
3980 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
3981 PREALLOC_MODE_OFF
, &local_err
);
3983 error_report_err(local_err
);
3989 fail_broken_refcounts
:
3990 /* The BDS is unusable at this point. If we wanted to make it usable, we
3991 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3992 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3993 * again. However, because the functions which could have caused this error
3994 * path to be taken are used by those functions as well, it's very likely
3995 * that that sequence will fail as well. Therefore, just eject the BDS. */
3999 g_free(new_reftable
);
4003 static int qcow2_make_empty(BlockDriverState
*bs
)
4005 BDRVQcow2State
*s
= bs
->opaque
;
4006 uint64_t offset
, end_offset
;
4007 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
4008 int l1_clusters
, ret
= 0;
4010 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
4012 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
4013 3 + l1_clusters
<= s
->refcount_block_size
&&
4014 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
4015 /* The following function only works for qcow2 v3 images (it
4016 * requires the dirty flag) and only as long as there are no
4017 * features that reserve extra clusters (such as snapshots,
4018 * LUKS header, or persistent bitmaps), because it completely
4019 * empties the image. Furthermore, the L1 table and three
4020 * additional clusters (image header, refcount table, one
4021 * refcount block) have to fit inside one refcount block. */
4022 return make_completely_empty(bs
);
4025 /* This fallback code simply discards every active cluster; this is slow,
4026 * but works in all cases */
4027 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
4028 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
4029 /* As this function is generally used after committing an external
4030 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4031 * default action for this kind of discard is to pass the discard,
4032 * which will ideally result in an actually smaller image file, as
4033 * is probably desired. */
4034 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
4035 QCOW2_DISCARD_SNAPSHOT
, true);
4044 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
4046 BDRVQcow2State
*s
= bs
->opaque
;
4049 qemu_co_mutex_lock(&s
->lock
);
4050 ret
= qcow2_write_caches(bs
);
4051 qemu_co_mutex_unlock(&s
->lock
);
4056 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
4059 Error
*local_err
= NULL
;
4060 BlockMeasureInfo
*info
;
4061 uint64_t required
= 0; /* bytes that contribute to required size */
4062 uint64_t virtual_size
; /* disk size as seen by guest */
4063 uint64_t refcount_bits
;
4065 size_t cluster_size
;
4068 PreallocMode prealloc
;
4069 bool has_backing_file
;
4071 /* Parse image creation options */
4072 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
4077 version
= qcow2_opt_get_version_del(opts
, &local_err
);
4082 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
4087 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
4088 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
4089 PREALLOC_MODE_OFF
, &local_err
);
4095 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
4096 has_backing_file
= !!optstr
;
4099 virtual_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
4100 virtual_size
= ROUND_UP(virtual_size
, cluster_size
);
4102 /* Check that virtual disk size is valid */
4103 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
4104 cluster_size
/ sizeof(uint64_t));
4105 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
4106 error_setg(&local_err
, "The image size is too large "
4107 "(try using a larger cluster size)");
4111 /* Account for input image */
4113 int64_t ssize
= bdrv_getlength(in_bs
);
4115 error_setg_errno(&local_err
, -ssize
,
4116 "Unable to get image virtual_size");
4120 virtual_size
= ROUND_UP(ssize
, cluster_size
);
4122 if (has_backing_file
) {
4123 /* We don't how much of the backing chain is shared by the input
4124 * image and the new image file. In the worst case the new image's
4125 * backing file has nothing in common with the input image. Be
4126 * conservative and assume all clusters need to be written.
4128 required
= virtual_size
;
4133 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
4136 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
4137 ssize
- offset
, &pnum
, NULL
,
4140 error_setg_errno(&local_err
, -ret
,
4141 "Unable to get block status");
4145 if (ret
& BDRV_BLOCK_ZERO
) {
4146 /* Skip zero regions (safe with no backing file) */
4147 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
4148 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
4149 /* Extend pnum to end of cluster for next iteration */
4150 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
4152 /* Count clusters we've seen */
4153 required
+= offset
% cluster_size
+ pnum
;
4159 /* Take into account preallocation. Nothing special is needed for
4160 * PREALLOC_MODE_METADATA since metadata is always counted.
4162 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
4163 required
= virtual_size
;
4166 info
= g_new(BlockMeasureInfo
, 1);
4167 info
->fully_allocated
=
4168 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
4169 ctz32(refcount_bits
));
4171 /* Remove data clusters that are not required. This overestimates the
4172 * required size because metadata needed for the fully allocated file is
4175 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
4179 error_propagate(errp
, local_err
);
4183 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
4185 BDRVQcow2State
*s
= bs
->opaque
;
4186 bdi
->unallocated_blocks_are_zero
= true;
4187 bdi
->cluster_size
= s
->cluster_size
;
4188 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
4192 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
4194 BDRVQcow2State
*s
= bs
->opaque
;
4195 ImageInfoSpecific
*spec_info
;
4196 QCryptoBlockInfo
*encrypt_info
= NULL
;
4198 if (s
->crypto
!= NULL
) {
4199 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &error_abort
);
4202 spec_info
= g_new(ImageInfoSpecific
, 1);
4203 *spec_info
= (ImageInfoSpecific
){
4204 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
4205 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
4207 if (s
->qcow_version
== 2) {
4208 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4209 .compat
= g_strdup("0.10"),
4210 .refcount_bits
= s
->refcount_bits
,
4212 } else if (s
->qcow_version
== 3) {
4213 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4214 .compat
= g_strdup("1.1"),
4215 .lazy_refcounts
= s
->compatible_features
&
4216 QCOW2_COMPAT_LAZY_REFCOUNTS
,
4217 .has_lazy_refcounts
= true,
4218 .corrupt
= s
->incompatible_features
&
4219 QCOW2_INCOMPAT_CORRUPT
,
4220 .has_corrupt
= true,
4221 .refcount_bits
= s
->refcount_bits
,
4224 /* if this assertion fails, this probably means a new version was
4225 * added without having it covered here */
4230 ImageInfoSpecificQCow2Encryption
*qencrypt
=
4231 g_new(ImageInfoSpecificQCow2Encryption
, 1);
4232 switch (encrypt_info
->format
) {
4233 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
4234 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
4236 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
4237 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
4238 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
4243 /* Since we did shallow copy above, erase any pointers
4244 * in the original info */
4245 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
4246 qapi_free_QCryptoBlockInfo(encrypt_info
);
4248 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
4249 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
4255 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4258 BDRVQcow2State
*s
= bs
->opaque
;
4260 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
4261 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
4262 qiov
->size
, qiov
, 0);
4265 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4268 BDRVQcow2State
*s
= bs
->opaque
;
4270 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
4271 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
4272 qiov
->size
, qiov
, 0);
4276 * Downgrades an image's version. To achieve this, any incompatible features
4277 * have to be removed.
4279 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
4280 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
4283 BDRVQcow2State
*s
= bs
->opaque
;
4284 int current_version
= s
->qcow_version
;
4287 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4288 assert(target_version
< current_version
);
4290 /* There are no other versions (now) that you can downgrade to */
4291 assert(target_version
== 2);
4293 if (s
->refcount_order
!= 4) {
4294 error_setg(errp
, "compat=0.10 requires refcount_bits=16");
4298 /* clear incompatible features */
4299 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
4300 ret
= qcow2_mark_clean(bs
);
4302 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
4307 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4308 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4309 * best thing to do anyway */
4311 if (s
->incompatible_features
) {
4312 error_setg(errp
, "Cannot downgrade an image with incompatible features "
4313 "%#" PRIx64
" set", s
->incompatible_features
);
4317 /* since we can ignore compatible features, we can set them to 0 as well */
4318 s
->compatible_features
= 0;
4319 /* if lazy refcounts have been used, they have already been fixed through
4320 * clearing the dirty flag */
4322 /* clearing autoclear features is trivial */
4323 s
->autoclear_features
= 0;
4325 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
4327 error_setg_errno(errp
, -ret
, "Failed to turn zero into data clusters");
4331 s
->qcow_version
= target_version
;
4332 ret
= qcow2_update_header(bs
);
4334 s
->qcow_version
= current_version
;
4335 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4341 typedef enum Qcow2AmendOperation
{
4342 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4343 * statically initialized to so that the helper CB can discern the first
4344 * invocation from an operation change */
4345 QCOW2_NO_OPERATION
= 0,
4347 QCOW2_CHANGING_REFCOUNT_ORDER
,
4349 } Qcow2AmendOperation
;
4351 typedef struct Qcow2AmendHelperCBInfo
{
4352 /* The code coordinating the amend operations should only modify
4353 * these four fields; the rest will be managed by the CB */
4354 BlockDriverAmendStatusCB
*original_status_cb
;
4355 void *original_cb_opaque
;
4357 Qcow2AmendOperation current_operation
;
4359 /* Total number of operations to perform (only set once) */
4360 int total_operations
;
4362 /* The following fields are managed by the CB */
4364 /* Number of operations completed */
4365 int operations_completed
;
4367 /* Cumulative offset of all completed operations */
4368 int64_t offset_completed
;
4370 Qcow2AmendOperation last_operation
;
4371 int64_t last_work_size
;
4372 } Qcow2AmendHelperCBInfo
;
4374 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
4375 int64_t operation_offset
,
4376 int64_t operation_work_size
, void *opaque
)
4378 Qcow2AmendHelperCBInfo
*info
= opaque
;
4379 int64_t current_work_size
;
4380 int64_t projected_work_size
;
4382 if (info
->current_operation
!= info
->last_operation
) {
4383 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
4384 info
->offset_completed
+= info
->last_work_size
;
4385 info
->operations_completed
++;
4388 info
->last_operation
= info
->current_operation
;
4391 assert(info
->total_operations
> 0);
4392 assert(info
->operations_completed
< info
->total_operations
);
4394 info
->last_work_size
= operation_work_size
;
4396 current_work_size
= info
->offset_completed
+ operation_work_size
;
4398 /* current_work_size is the total work size for (operations_completed + 1)
4399 * operations (which includes this one), so multiply it by the number of
4400 * operations not covered and divide it by the number of operations
4401 * covered to get a projection for the operations not covered */
4402 projected_work_size
= current_work_size
* (info
->total_operations
-
4403 info
->operations_completed
- 1)
4404 / (info
->operations_completed
+ 1);
4406 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
4407 current_work_size
+ projected_work_size
,
4408 info
->original_cb_opaque
);
4411 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
4412 BlockDriverAmendStatusCB
*status_cb
,
4416 BDRVQcow2State
*s
= bs
->opaque
;
4417 int old_version
= s
->qcow_version
, new_version
= old_version
;
4418 uint64_t new_size
= 0;
4419 const char *backing_file
= NULL
, *backing_format
= NULL
;
4420 bool lazy_refcounts
= s
->use_lazy_refcounts
;
4421 const char *compat
= NULL
;
4422 uint64_t cluster_size
= s
->cluster_size
;
4425 int refcount_bits
= s
->refcount_bits
;
4427 QemuOptDesc
*desc
= opts
->list
->desc
;
4428 Qcow2AmendHelperCBInfo helper_cb_info
;
4430 while (desc
&& desc
->name
) {
4431 if (!qemu_opt_find(opts
, desc
->name
)) {
4432 /* only change explicitly defined options */
4437 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
4438 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
4440 /* preserve default */
4441 } else if (!strcmp(compat
, "0.10")) {
4443 } else if (!strcmp(compat
, "1.1")) {
4446 error_setg(errp
, "Unknown compatibility level %s", compat
);
4449 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
4450 error_setg(errp
, "Cannot change preallocation mode");
4452 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
4453 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
4454 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
4455 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
4456 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
4457 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
4458 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
4459 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
4462 if (encrypt
!= !!s
->crypto
) {
4464 "Changing the encryption flag is not supported");
4467 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
4468 encformat
= qcow2_crypt_method_from_format(
4469 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
4471 if (encformat
!= s
->crypt_method_header
) {
4473 "Changing the encryption format is not supported");
4476 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
4478 "Changing the encryption parameters is not supported");
4480 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
4481 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
4483 if (cluster_size
!= s
->cluster_size
) {
4484 error_setg(errp
, "Changing the cluster size is not supported");
4487 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
4488 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
4490 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
4491 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
4494 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
4495 !is_power_of_2(refcount_bits
))
4497 error_setg(errp
, "Refcount width must be a power of two and "
4498 "may not exceed 64 bits");
4502 /* if this point is reached, this probably means a new option was
4503 * added without having it covered here */
4510 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
4511 .original_status_cb
= status_cb
,
4512 .original_cb_opaque
= cb_opaque
,
4513 .total_operations
= (new_version
< old_version
)
4514 + (s
->refcount_bits
!= refcount_bits
)
4517 /* Upgrade first (some features may require compat=1.1) */
4518 if (new_version
> old_version
) {
4519 s
->qcow_version
= new_version
;
4520 ret
= qcow2_update_header(bs
);
4522 s
->qcow_version
= old_version
;
4523 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4528 if (s
->refcount_bits
!= refcount_bits
) {
4529 int refcount_order
= ctz32(refcount_bits
);
4531 if (new_version
< 3 && refcount_bits
!= 16) {
4532 error_setg(errp
, "Refcount widths other than 16 bits require "
4533 "compatibility level 1.1 or above (use compat=1.1 or "
4538 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
4539 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
4540 &qcow2_amend_helper_cb
,
4541 &helper_cb_info
, errp
);
4547 if (backing_file
|| backing_format
) {
4548 ret
= qcow2_change_backing_file(bs
,
4549 backing_file
?: s
->image_backing_file
,
4550 backing_format
?: s
->image_backing_format
);
4552 error_setg_errno(errp
, -ret
, "Failed to change the backing file");
4557 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
4558 if (lazy_refcounts
) {
4559 if (new_version
< 3) {
4560 error_setg(errp
, "Lazy refcounts only supported with "
4561 "compatibility level 1.1 and above (use compat=1.1 "
4565 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4566 ret
= qcow2_update_header(bs
);
4568 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4569 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4572 s
->use_lazy_refcounts
= true;
4574 /* make image clean first */
4575 ret
= qcow2_mark_clean(bs
);
4577 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
4580 /* now disallow lazy refcounts */
4581 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4582 ret
= qcow2_update_header(bs
);
4584 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4585 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4588 s
->use_lazy_refcounts
= false;
4593 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
4594 ret
= blk_insert_bs(blk
, bs
, errp
);
4600 ret
= blk_truncate(blk
, new_size
, PREALLOC_MODE_OFF
, errp
);
4607 /* Downgrade last (so unsupported features can be removed before) */
4608 if (new_version
< old_version
) {
4609 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
4610 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
4611 &helper_cb_info
, errp
);
4621 * If offset or size are negative, respectively, they will not be included in
4622 * the BLOCK_IMAGE_CORRUPTED event emitted.
4623 * fatal will be ignored for read-only BDS; corruptions found there will always
4624 * be considered non-fatal.
4626 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
4627 int64_t size
, const char *message_format
, ...)
4629 BDRVQcow2State
*s
= bs
->opaque
;
4630 const char *node_name
;
4634 fatal
= fatal
&& bdrv_is_writable(bs
);
4636 if (s
->signaled_corruption
&&
4637 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
4642 va_start(ap
, message_format
);
4643 message
= g_strdup_vprintf(message_format
, ap
);
4647 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
4648 "corruption events will be suppressed\n", message
);
4650 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
4651 "corruption events will be suppressed\n", message
);
4654 node_name
= bdrv_get_node_name(bs
);
4655 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
4656 *node_name
!= '\0', node_name
,
4657 message
, offset
>= 0, offset
,
4659 fatal
, &error_abort
);
4663 qcow2_mark_corrupt(bs
);
4664 bs
->drv
= NULL
; /* make BDS unusable */
4667 s
->signaled_corruption
= true;
4670 static QemuOptsList qcow2_create_opts
= {
4671 .name
= "qcow2-create-opts",
4672 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
4675 .name
= BLOCK_OPT_SIZE
,
4676 .type
= QEMU_OPT_SIZE
,
4677 .help
= "Virtual disk size"
4680 .name
= BLOCK_OPT_COMPAT_LEVEL
,
4681 .type
= QEMU_OPT_STRING
,
4682 .help
= "Compatibility level (0.10 or 1.1)"
4685 .name
= BLOCK_OPT_BACKING_FILE
,
4686 .type
= QEMU_OPT_STRING
,
4687 .help
= "File name of a base image"
4690 .name
= BLOCK_OPT_BACKING_FMT
,
4691 .type
= QEMU_OPT_STRING
,
4692 .help
= "Image format of the base image"
4695 .name
= BLOCK_OPT_ENCRYPT
,
4696 .type
= QEMU_OPT_BOOL
,
4697 .help
= "Encrypt the image with format 'aes'. (Deprecated "
4698 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
4701 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
4702 .type
= QEMU_OPT_STRING
,
4703 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
4705 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4706 "ID of secret providing qcow AES key or LUKS passphrase"),
4707 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4708 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4709 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4710 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4711 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4712 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4714 .name
= BLOCK_OPT_CLUSTER_SIZE
,
4715 .type
= QEMU_OPT_SIZE
,
4716 .help
= "qcow2 cluster size",
4717 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
4720 .name
= BLOCK_OPT_PREALLOC
,
4721 .type
= QEMU_OPT_STRING
,
4722 .help
= "Preallocation mode (allowed values: off, metadata, "
4726 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
4727 .type
= QEMU_OPT_BOOL
,
4728 .help
= "Postpone refcount updates",
4729 .def_value_str
= "off"
4732 .name
= BLOCK_OPT_REFCOUNT_BITS
,
4733 .type
= QEMU_OPT_NUMBER
,
4734 .help
= "Width of a reference count entry in bits",
4735 .def_value_str
= "16"
4737 { /* end of list */ }
4741 BlockDriver bdrv_qcow2
= {
4742 .format_name
= "qcow2",
4743 .instance_size
= sizeof(BDRVQcow2State
),
4744 .bdrv_probe
= qcow2_probe
,
4745 .bdrv_open
= qcow2_open
,
4746 .bdrv_close
= qcow2_close
,
4747 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
4748 .bdrv_reopen_commit
= qcow2_reopen_commit
,
4749 .bdrv_reopen_abort
= qcow2_reopen_abort
,
4750 .bdrv_join_options
= qcow2_join_options
,
4751 .bdrv_child_perm
= bdrv_format_default_perms
,
4752 .bdrv_co_create_opts
= qcow2_co_create_opts
,
4753 .bdrv_co_create
= qcow2_co_create
,
4754 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
4755 .bdrv_co_block_status
= qcow2_co_block_status
,
4757 .bdrv_co_preadv
= qcow2_co_preadv
,
4758 .bdrv_co_pwritev
= qcow2_co_pwritev
,
4759 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
4761 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
4762 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
4763 .bdrv_co_copy_range_from
= qcow2_co_copy_range_from
,
4764 .bdrv_co_copy_range_to
= qcow2_co_copy_range_to
,
4765 .bdrv_co_truncate
= qcow2_co_truncate
,
4766 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
4767 .bdrv_make_empty
= qcow2_make_empty
,
4769 .bdrv_snapshot_create
= qcow2_snapshot_create
,
4770 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
4771 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
4772 .bdrv_snapshot_list
= qcow2_snapshot_list
,
4773 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
4774 .bdrv_measure
= qcow2_measure
,
4775 .bdrv_get_info
= qcow2_get_info
,
4776 .bdrv_get_specific_info
= qcow2_get_specific_info
,
4778 .bdrv_save_vmstate
= qcow2_save_vmstate
,
4779 .bdrv_load_vmstate
= qcow2_load_vmstate
,
4781 .supports_backing
= true,
4782 .bdrv_change_backing_file
= qcow2_change_backing_file
,
4784 .bdrv_refresh_limits
= qcow2_refresh_limits
,
4785 .bdrv_co_invalidate_cache
= qcow2_co_invalidate_cache
,
4786 .bdrv_inactivate
= qcow2_inactivate
,
4788 .create_opts
= &qcow2_create_opts
,
4789 .bdrv_co_check
= qcow2_co_check
,
4790 .bdrv_amend_options
= qcow2_amend_options
,
4792 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
4793 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
4795 .bdrv_reopen_bitmaps_rw
= qcow2_reopen_bitmaps_rw
,
4796 .bdrv_can_store_new_dirty_bitmap
= qcow2_can_store_new_dirty_bitmap
,
4797 .bdrv_remove_persistent_dirty_bitmap
= qcow2_remove_persistent_dirty_bitmap
,
4800 static void bdrv_qcow2_init(void)
4802 bdrv_register(&bdrv_qcow2
);
4805 block_init(bdrv_qcow2_init
);