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"
27 #include "block/qdict.h"
28 #include "sysemu/block-backend.h"
29 #include "qemu/main-loop.h"
30 #include "qemu/module.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-events-block-core.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
38 #include "qemu/option_int.h"
39 #include "qemu/cutils.h"
40 #include "qemu/bswap.h"
41 #include "qemu/memalign.h"
42 #include "qapi/qobject-input-visitor.h"
43 #include "qapi/qapi-visit-block-core.h"
45 #include "block/aio_task.h"
48 Differences with QCOW:
50 - Support for multiple incremental snapshots.
51 - Memory management by reference counts.
52 - Clusters which have a reference count of one have the bit
53 QCOW_OFLAG_COPIED to optimize write performance.
54 - Size of compressed clusters is stored in sectors to reduce bit usage
55 in the cluster offsets.
56 - Support for storing additional data (such as the VM state) in the
58 - If a backing store is used, the cluster size is not constrained
59 (could be backported to QCOW).
60 - L2 tables have always a size of one cluster.
67 } QEMU_PACKED QCowExtension
;
69 #define QCOW2_EXT_MAGIC_END 0
70 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xe2792aca
71 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
72 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
73 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
74 #define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
76 static int coroutine_fn
77 qcow2_co_preadv_compressed(BlockDriverState
*bs
,
84 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
86 const QCowHeader
*cow_header
= (const void *)buf
;
88 if (buf_size
>= sizeof(QCowHeader
) &&
89 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
90 be32_to_cpu(cow_header
->version
) >= 2)
97 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
98 uint8_t *buf
, size_t buflen
,
99 void *opaque
, Error
**errp
)
101 BlockDriverState
*bs
= opaque
;
102 BDRVQcow2State
*s
= bs
->opaque
;
105 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
106 error_setg(errp
, "Request for data outside of extension header");
110 ret
= bdrv_pread(bs
->file
,
111 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
113 error_setg_errno(errp
, -ret
, "Could not read encryption header");
120 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
121 void *opaque
, Error
**errp
)
123 BlockDriverState
*bs
= opaque
;
124 BDRVQcow2State
*s
= bs
->opaque
;
128 ret
= qcow2_alloc_clusters(bs
, headerlen
);
130 error_setg_errno(errp
, -ret
,
131 "Cannot allocate cluster for LUKS header size %zu",
136 s
->crypto_header
.length
= headerlen
;
137 s
->crypto_header
.offset
= ret
;
140 * Zero fill all space in cluster so it has predictable
141 * content, as we may not initialize some regions of the
142 * header (eg only 1 out of 8 key slots will be initialized)
144 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
145 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
, false) == 0);
146 ret
= bdrv_pwrite_zeroes(bs
->file
,
150 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
158 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
159 const uint8_t *buf
, size_t buflen
,
160 void *opaque
, Error
**errp
)
162 BlockDriverState
*bs
= opaque
;
163 BDRVQcow2State
*s
= bs
->opaque
;
166 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
167 error_setg(errp
, "Request for data outside of extension header");
171 ret
= bdrv_pwrite(bs
->file
,
172 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
174 error_setg_errno(errp
, -ret
, "Could not read encryption header");
181 qcow2_extract_crypto_opts(QemuOpts
*opts
, const char *fmt
, Error
**errp
)
183 QDict
*cryptoopts_qdict
;
186 /* Extract "encrypt." options into a qdict */
187 opts_qdict
= qemu_opts_to_qdict(opts
, NULL
);
188 qdict_extract_subqdict(opts_qdict
, &cryptoopts_qdict
, "encrypt.");
189 qobject_unref(opts_qdict
);
190 qdict_put_str(cryptoopts_qdict
, "format", fmt
);
191 return cryptoopts_qdict
;
195 * read qcow2 extension and fill bs
196 * start reading from start_offset
197 * finish reading upon magic of value 0 or when end_offset reached
198 * unknown magic is skipped (future extension this version knows nothing about)
199 * return 0 upon success, non-0 otherwise
201 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
202 uint64_t end_offset
, void **p_feature_table
,
203 int flags
, bool *need_update_header
,
206 BDRVQcow2State
*s
= bs
->opaque
;
210 Qcow2BitmapHeaderExt bitmaps_ext
;
212 if (need_update_header
!= NULL
) {
213 *need_update_header
= false;
217 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
219 offset
= start_offset
;
220 while (offset
< end_offset
) {
224 if (offset
> s
->cluster_size
)
225 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
227 printf("attempting to read extended header in offset %lu\n", offset
);
230 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
232 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
233 "pread fail from offset %" PRIu64
, offset
);
236 ext
.magic
= be32_to_cpu(ext
.magic
);
237 ext
.len
= be32_to_cpu(ext
.len
);
238 offset
+= sizeof(ext
);
240 printf("ext.magic = 0x%x\n", ext
.magic
);
242 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
243 error_setg(errp
, "Header extension too large");
248 case QCOW2_EXT_MAGIC_END
:
251 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
252 if (ext
.len
>= sizeof(bs
->backing_format
)) {
253 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
254 " too large (>=%zu)", ext
.len
,
255 sizeof(bs
->backing_format
));
258 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
260 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
261 "Could not read format name");
264 bs
->backing_format
[ext
.len
] = '\0';
265 s
->image_backing_format
= g_strdup(bs
->backing_format
);
267 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
271 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
272 if (p_feature_table
!= NULL
) {
273 void *feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
274 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
276 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
277 "Could not read table");
281 *p_feature_table
= feature_table
;
285 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
286 unsigned int cflags
= 0;
287 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
288 error_setg(errp
, "CRYPTO header extension only "
289 "expected with LUKS encryption method");
292 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
293 error_setg(errp
, "CRYPTO header extension size %u, "
294 "but expected size %zu", ext
.len
,
295 sizeof(Qcow2CryptoHeaderExtension
));
299 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
301 error_setg_errno(errp
, -ret
,
302 "Unable to read CRYPTO header extension");
305 s
->crypto_header
.offset
= be64_to_cpu(s
->crypto_header
.offset
);
306 s
->crypto_header
.length
= be64_to_cpu(s
->crypto_header
.length
);
308 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
309 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
310 "not a multiple of cluster size '%u'",
311 s
->crypto_header
.offset
, s
->cluster_size
);
315 if (flags
& BDRV_O_NO_IO
) {
316 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
318 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
319 qcow2_crypto_hdr_read_func
,
320 bs
, cflags
, QCOW2_MAX_THREADS
, errp
);
326 case QCOW2_EXT_MAGIC_BITMAPS
:
327 if (ext
.len
!= sizeof(bitmaps_ext
)) {
328 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
329 "Invalid extension length");
333 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
334 if (s
->qcow_version
< 3) {
335 /* Let's be a bit more specific */
336 warn_report("This qcow2 v2 image contains bitmaps, but "
337 "they may have been modified by a program "
338 "without persistent bitmap support; so now "
339 "they must all be considered inconsistent");
341 warn_report("a program lacking bitmap support "
342 "modified this file, so all bitmaps are now "
343 "considered inconsistent");
345 error_printf("Some clusters may be leaked, "
346 "run 'qemu-img check -r' on the image "
348 if (need_update_header
!= NULL
) {
349 /* Updating is needed to drop invalid bitmap extension. */
350 *need_update_header
= true;
355 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
357 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
358 "Could not read ext header");
362 if (bitmaps_ext
.reserved32
!= 0) {
363 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
364 "Reserved field is not zero");
368 bitmaps_ext
.nb_bitmaps
= be32_to_cpu(bitmaps_ext
.nb_bitmaps
);
369 bitmaps_ext
.bitmap_directory_size
=
370 be64_to_cpu(bitmaps_ext
.bitmap_directory_size
);
371 bitmaps_ext
.bitmap_directory_offset
=
372 be64_to_cpu(bitmaps_ext
.bitmap_directory_offset
);
374 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
376 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
377 "exceeding the QEMU supported maximum of %d",
378 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
382 if (bitmaps_ext
.nb_bitmaps
== 0) {
383 error_setg(errp
, "found bitmaps extension with zero bitmaps");
387 if (offset_into_cluster(s
, bitmaps_ext
.bitmap_directory_offset
)) {
388 error_setg(errp
, "bitmaps_ext: "
389 "invalid bitmap directory offset");
393 if (bitmaps_ext
.bitmap_directory_size
>
394 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
395 error_setg(errp
, "bitmaps_ext: "
396 "bitmap directory size (%" PRIu64
") exceeds "
397 "the maximum supported size (%d)",
398 bitmaps_ext
.bitmap_directory_size
,
399 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
403 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
404 s
->bitmap_directory_offset
=
405 bitmaps_ext
.bitmap_directory_offset
;
406 s
->bitmap_directory_size
=
407 bitmaps_ext
.bitmap_directory_size
;
410 printf("Qcow2: Got bitmaps extension: "
411 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
412 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
416 case QCOW2_EXT_MAGIC_DATA_FILE
:
418 s
->image_data_file
= g_malloc0(ext
.len
+ 1);
419 ret
= bdrv_pread(bs
->file
, offset
, s
->image_data_file
, ext
.len
);
421 error_setg_errno(errp
, -ret
,
422 "ERROR: Could not read data file name");
426 printf("Qcow2: Got external data file %s\n", s
->image_data_file
);
432 /* unknown magic - save it in case we need to rewrite the header */
433 /* If you add a new feature, make sure to also update the fast
434 * path of qcow2_make_empty() to deal with it. */
436 Qcow2UnknownHeaderExtension
*uext
;
438 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
439 uext
->magic
= ext
.magic
;
441 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
443 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
445 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
446 "Could not read data");
453 offset
+= ((ext
.len
+ 7) & ~7);
459 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
461 BDRVQcow2State
*s
= bs
->opaque
;
462 Qcow2UnknownHeaderExtension
*uext
, *next
;
464 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
465 QLIST_REMOVE(uext
, next
);
470 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
473 g_autoptr(GString
) features
= g_string_sized_new(60);
475 while (table
&& table
->name
[0] != '\0') {
476 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
477 if (mask
& (1ULL << table
->bit
)) {
478 if (features
->len
> 0) {
479 g_string_append(features
, ", ");
481 g_string_append_printf(features
, "%.46s", table
->name
);
482 mask
&= ~(1ULL << table
->bit
);
489 if (features
->len
> 0) {
490 g_string_append(features
, ", ");
492 g_string_append_printf(features
,
493 "Unknown incompatible feature: %" PRIx64
, mask
);
496 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
->str
);
500 * Sets the dirty bit and flushes afterwards if necessary.
502 * The incompatible_features bit is only set if the image file header was
503 * updated successfully. Therefore it is not required to check the return
504 * value of this function.
506 int qcow2_mark_dirty(BlockDriverState
*bs
)
508 BDRVQcow2State
*s
= bs
->opaque
;
512 assert(s
->qcow_version
>= 3);
514 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
515 return 0; /* already dirty */
518 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
519 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
524 ret
= bdrv_flush(bs
->file
->bs
);
529 /* Only treat image as dirty if the header was updated successfully */
530 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
535 * Clears the dirty bit and flushes before if necessary. Only call this
536 * function when there are no pending requests, it does not guard against
537 * concurrent requests dirtying the image.
539 static int qcow2_mark_clean(BlockDriverState
*bs
)
541 BDRVQcow2State
*s
= bs
->opaque
;
543 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
546 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
548 ret
= qcow2_flush_caches(bs
);
553 return qcow2_update_header(bs
);
559 * Marks the image as corrupt.
561 int qcow2_mark_corrupt(BlockDriverState
*bs
)
563 BDRVQcow2State
*s
= bs
->opaque
;
565 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
566 return qcow2_update_header(bs
);
570 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
571 * before if necessary.
573 int qcow2_mark_consistent(BlockDriverState
*bs
)
575 BDRVQcow2State
*s
= bs
->opaque
;
577 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
578 int ret
= qcow2_flush_caches(bs
);
583 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
584 return qcow2_update_header(bs
);
589 static void qcow2_add_check_result(BdrvCheckResult
*out
,
590 const BdrvCheckResult
*src
,
591 bool set_allocation_info
)
593 out
->corruptions
+= src
->corruptions
;
594 out
->leaks
+= src
->leaks
;
595 out
->check_errors
+= src
->check_errors
;
596 out
->corruptions_fixed
+= src
->corruptions_fixed
;
597 out
->leaks_fixed
+= src
->leaks_fixed
;
599 if (set_allocation_info
) {
600 out
->image_end_offset
= src
->image_end_offset
;
605 static int coroutine_fn
qcow2_co_check_locked(BlockDriverState
*bs
,
606 BdrvCheckResult
*result
,
609 BdrvCheckResult snapshot_res
= {};
610 BdrvCheckResult refcount_res
= {};
613 memset(result
, 0, sizeof(*result
));
615 ret
= qcow2_check_read_snapshot_table(bs
, &snapshot_res
, fix
);
617 qcow2_add_check_result(result
, &snapshot_res
, false);
621 ret
= qcow2_check_refcounts(bs
, &refcount_res
, fix
);
622 qcow2_add_check_result(result
, &refcount_res
, true);
624 qcow2_add_check_result(result
, &snapshot_res
, false);
628 ret
= qcow2_check_fix_snapshot_table(bs
, &snapshot_res
, fix
);
629 qcow2_add_check_result(result
, &snapshot_res
, false);
634 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
635 ret
= qcow2_mark_clean(bs
);
639 return qcow2_mark_consistent(bs
);
644 static int coroutine_fn
qcow2_co_check(BlockDriverState
*bs
,
645 BdrvCheckResult
*result
,
648 BDRVQcow2State
*s
= bs
->opaque
;
651 qemu_co_mutex_lock(&s
->lock
);
652 ret
= qcow2_co_check_locked(bs
, result
, fix
);
653 qemu_co_mutex_unlock(&s
->lock
);
657 int qcow2_validate_table(BlockDriverState
*bs
, uint64_t offset
,
658 uint64_t entries
, size_t entry_len
,
659 int64_t max_size_bytes
, const char *table_name
,
662 BDRVQcow2State
*s
= bs
->opaque
;
664 if (entries
> max_size_bytes
/ entry_len
) {
665 error_setg(errp
, "%s too large", table_name
);
669 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
670 * because values will be passed to qemu functions taking int64_t. */
671 if ((INT64_MAX
- entries
* entry_len
< offset
) ||
672 (offset_into_cluster(s
, offset
) != 0)) {
673 error_setg(errp
, "%s offset invalid", table_name
);
680 static const char *const mutable_opts
[] = {
681 QCOW2_OPT_LAZY_REFCOUNTS
,
682 QCOW2_OPT_DISCARD_REQUEST
,
683 QCOW2_OPT_DISCARD_SNAPSHOT
,
684 QCOW2_OPT_DISCARD_OTHER
,
686 QCOW2_OPT_OVERLAP_TEMPLATE
,
687 QCOW2_OPT_OVERLAP_MAIN_HEADER
,
688 QCOW2_OPT_OVERLAP_ACTIVE_L1
,
689 QCOW2_OPT_OVERLAP_ACTIVE_L2
,
690 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
691 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
692 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
693 QCOW2_OPT_OVERLAP_INACTIVE_L1
,
694 QCOW2_OPT_OVERLAP_INACTIVE_L2
,
695 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
696 QCOW2_OPT_CACHE_SIZE
,
697 QCOW2_OPT_L2_CACHE_SIZE
,
698 QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
699 QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
700 QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
704 static QemuOptsList qcow2_runtime_opts
= {
706 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
709 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
710 .type
= QEMU_OPT_BOOL
,
711 .help
= "Postpone refcount updates",
714 .name
= QCOW2_OPT_DISCARD_REQUEST
,
715 .type
= QEMU_OPT_BOOL
,
716 .help
= "Pass guest discard requests to the layer below",
719 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
720 .type
= QEMU_OPT_BOOL
,
721 .help
= "Generate discard requests when snapshot related space "
725 .name
= QCOW2_OPT_DISCARD_OTHER
,
726 .type
= QEMU_OPT_BOOL
,
727 .help
= "Generate discard requests when other clusters are freed",
730 .name
= QCOW2_OPT_OVERLAP
,
731 .type
= QEMU_OPT_STRING
,
732 .help
= "Selects which overlap checks to perform from a range of "
733 "templates (none, constant, cached, all)",
736 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
737 .type
= QEMU_OPT_STRING
,
738 .help
= "Selects which overlap checks to perform from a range of "
739 "templates (none, constant, cached, all)",
742 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
743 .type
= QEMU_OPT_BOOL
,
744 .help
= "Check for unintended writes into the main qcow2 header",
747 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
748 .type
= QEMU_OPT_BOOL
,
749 .help
= "Check for unintended writes into the active L1 table",
752 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
753 .type
= QEMU_OPT_BOOL
,
754 .help
= "Check for unintended writes into an active L2 table",
757 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
758 .type
= QEMU_OPT_BOOL
,
759 .help
= "Check for unintended writes into the refcount table",
762 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
763 .type
= QEMU_OPT_BOOL
,
764 .help
= "Check for unintended writes into a refcount block",
767 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
768 .type
= QEMU_OPT_BOOL
,
769 .help
= "Check for unintended writes into the snapshot table",
772 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
773 .type
= QEMU_OPT_BOOL
,
774 .help
= "Check for unintended writes into an inactive L1 table",
777 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
778 .type
= QEMU_OPT_BOOL
,
779 .help
= "Check for unintended writes into an inactive L2 table",
782 .name
= QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
783 .type
= QEMU_OPT_BOOL
,
784 .help
= "Check for unintended writes into the bitmap directory",
787 .name
= QCOW2_OPT_CACHE_SIZE
,
788 .type
= QEMU_OPT_SIZE
,
789 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
793 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
794 .type
= QEMU_OPT_SIZE
,
795 .help
= "Maximum L2 table cache size",
798 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
799 .type
= QEMU_OPT_SIZE
,
800 .help
= "Size of each entry in the L2 cache",
803 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
804 .type
= QEMU_OPT_SIZE
,
805 .help
= "Maximum refcount block cache size",
808 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
809 .type
= QEMU_OPT_NUMBER
,
810 .help
= "Clean unused cache entries after this time (in seconds)",
812 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
813 "ID of secret providing qcow2 AES key or LUKS passphrase"),
814 { /* end of list */ }
818 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
819 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
820 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
821 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
822 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
823 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
824 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
825 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
826 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
827 [QCOW2_OL_BITMAP_DIRECTORY_BITNR
] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
830 static void cache_clean_timer_cb(void *opaque
)
832 BlockDriverState
*bs
= opaque
;
833 BDRVQcow2State
*s
= bs
->opaque
;
834 qcow2_cache_clean_unused(s
->l2_table_cache
);
835 qcow2_cache_clean_unused(s
->refcount_block_cache
);
836 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
837 (int64_t) s
->cache_clean_interval
* 1000);
840 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
842 BDRVQcow2State
*s
= bs
->opaque
;
843 if (s
->cache_clean_interval
> 0) {
844 s
->cache_clean_timer
=
845 aio_timer_new_with_attrs(context
, QEMU_CLOCK_VIRTUAL
,
846 SCALE_MS
, QEMU_TIMER_ATTR_EXTERNAL
,
847 cache_clean_timer_cb
, bs
);
848 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
849 (int64_t) s
->cache_clean_interval
* 1000);
853 static void cache_clean_timer_del(BlockDriverState
*bs
)
855 BDRVQcow2State
*s
= bs
->opaque
;
856 if (s
->cache_clean_timer
) {
857 timer_free(s
->cache_clean_timer
);
858 s
->cache_clean_timer
= NULL
;
862 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
864 cache_clean_timer_del(bs
);
867 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
868 AioContext
*new_context
)
870 cache_clean_timer_init(bs
, new_context
);
873 static bool read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
874 uint64_t *l2_cache_size
,
875 uint64_t *l2_cache_entry_size
,
876 uint64_t *refcount_cache_size
, Error
**errp
)
878 BDRVQcow2State
*s
= bs
->opaque
;
879 uint64_t combined_cache_size
, l2_cache_max_setting
;
880 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
881 bool l2_cache_entry_size_set
;
882 int min_refcount_cache
= MIN_REFCOUNT_CACHE_SIZE
* s
->cluster_size
;
883 uint64_t virtual_disk_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
884 uint64_t max_l2_entries
= DIV_ROUND_UP(virtual_disk_size
, s
->cluster_size
);
885 /* An L2 table is always one cluster in size so the max cache size
886 * should be a multiple of the cluster size. */
887 uint64_t max_l2_cache
= ROUND_UP(max_l2_entries
* l2_entry_size(s
),
890 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
891 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
892 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
893 l2_cache_entry_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
);
895 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
896 l2_cache_max_setting
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
,
897 DEFAULT_L2_CACHE_MAX_SIZE
);
898 *refcount_cache_size
= qemu_opt_get_size(opts
,
899 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
901 *l2_cache_entry_size
= qemu_opt_get_size(
902 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
904 *l2_cache_size
= MIN(max_l2_cache
, l2_cache_max_setting
);
906 if (combined_cache_size_set
) {
907 if (l2_cache_size_set
&& refcount_cache_size_set
) {
908 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
909 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
912 } else if (l2_cache_size_set
&&
913 (l2_cache_max_setting
> combined_cache_size
)) {
914 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
915 QCOW2_OPT_CACHE_SIZE
);
917 } else if (*refcount_cache_size
> combined_cache_size
) {
918 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
919 QCOW2_OPT_CACHE_SIZE
);
923 if (l2_cache_size_set
) {
924 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
925 } else if (refcount_cache_size_set
) {
926 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
928 /* Assign as much memory as possible to the L2 cache, and
929 * use the remainder for the refcount cache */
930 if (combined_cache_size
>= max_l2_cache
+ min_refcount_cache
) {
931 *l2_cache_size
= max_l2_cache
;
932 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
934 *refcount_cache_size
=
935 MIN(combined_cache_size
, min_refcount_cache
);
936 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
942 * If the L2 cache is not enough to cover the whole disk then
943 * default to 4KB entries. Smaller entries reduce the cost of
944 * loads and evictions and increase I/O performance.
946 if (*l2_cache_size
< max_l2_cache
&& !l2_cache_entry_size_set
) {
947 *l2_cache_entry_size
= MIN(s
->cluster_size
, 4096);
950 /* l2_cache_size and refcount_cache_size are ensured to have at least
951 * their minimum values in qcow2_update_options_prepare() */
953 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
954 *l2_cache_entry_size
> s
->cluster_size
||
955 !is_power_of_2(*l2_cache_entry_size
)) {
956 error_setg(errp
, "L2 cache entry size must be a power of two "
957 "between %d and the cluster size (%d)",
958 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
965 typedef struct Qcow2ReopenState
{
966 Qcow2Cache
*l2_table_cache
;
967 Qcow2Cache
*refcount_block_cache
;
968 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
969 bool use_lazy_refcounts
;
971 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
972 uint64_t cache_clean_interval
;
973 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
976 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
978 QDict
*options
, int flags
,
981 BDRVQcow2State
*s
= bs
->opaque
;
982 QemuOpts
*opts
= NULL
;
983 const char *opt_overlap_check
, *opt_overlap_check_template
;
984 int overlap_check_template
= 0;
985 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
987 const char *encryptfmt
;
988 QDict
*encryptopts
= NULL
;
991 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
992 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
994 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
995 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1000 /* get L2 table/refcount block cache size from command line options */
1001 if (!read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
1002 &refcount_cache_size
, errp
)) {
1007 l2_cache_size
/= l2_cache_entry_size
;
1008 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
1009 l2_cache_size
= MIN_L2_CACHE_SIZE
;
1011 if (l2_cache_size
> INT_MAX
) {
1012 error_setg(errp
, "L2 cache size too big");
1017 refcount_cache_size
/= s
->cluster_size
;
1018 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
1019 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
1021 if (refcount_cache_size
> INT_MAX
) {
1022 error_setg(errp
, "Refcount cache size too big");
1027 /* alloc new L2 table/refcount block cache, flush old one */
1028 if (s
->l2_table_cache
) {
1029 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
1031 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
1036 if (s
->refcount_block_cache
) {
1037 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1039 error_setg_errno(errp
, -ret
,
1040 "Failed to flush the refcount block cache");
1045 r
->l2_slice_size
= l2_cache_entry_size
/ l2_entry_size(s
);
1046 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
1047 l2_cache_entry_size
);
1048 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
1050 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
1051 error_setg(errp
, "Could not allocate metadata caches");
1056 /* New interval for cache cleanup timer */
1057 r
->cache_clean_interval
=
1058 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
1059 DEFAULT_CACHE_CLEAN_INTERVAL
);
1060 #ifndef CONFIG_LINUX
1061 if (r
->cache_clean_interval
!= 0) {
1062 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1063 " not supported on this host");
1068 if (r
->cache_clean_interval
> UINT_MAX
) {
1069 error_setg(errp
, "Cache clean interval too big");
1074 /* lazy-refcounts; flush if going from enabled to disabled */
1075 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
1076 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
1077 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
1078 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
1079 "qemu 1.1 compatibility level");
1084 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
1085 ret
= qcow2_mark_clean(bs
);
1087 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
1092 /* Overlap check options */
1093 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
1094 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1095 if (opt_overlap_check_template
&& opt_overlap_check
&&
1096 strcmp(opt_overlap_check_template
, opt_overlap_check
))
1098 error_setg(errp
, "Conflicting values for qcow2 options '"
1099 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1100 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
1104 if (!opt_overlap_check
) {
1105 opt_overlap_check
= opt_overlap_check_template
?: "cached";
1108 if (!strcmp(opt_overlap_check
, "none")) {
1109 overlap_check_template
= 0;
1110 } else if (!strcmp(opt_overlap_check
, "constant")) {
1111 overlap_check_template
= QCOW2_OL_CONSTANT
;
1112 } else if (!strcmp(opt_overlap_check
, "cached")) {
1113 overlap_check_template
= QCOW2_OL_CACHED
;
1114 } else if (!strcmp(opt_overlap_check
, "all")) {
1115 overlap_check_template
= QCOW2_OL_ALL
;
1117 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
1118 "'overlap-check'. Allowed are any of the following: "
1119 "none, constant, cached, all", opt_overlap_check
);
1124 r
->overlap_check
= 0;
1125 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
1126 /* overlap-check defines a template bitmask, but every flag may be
1127 * overwritten through the associated boolean option */
1129 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
1130 overlap_check_template
& (1 << i
)) << i
;
1133 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
1134 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
1135 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
1136 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1137 flags
& BDRV_O_UNMAP
);
1138 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1139 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1140 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1141 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1143 switch (s
->crypt_method_header
) {
1144 case QCOW_CRYPT_NONE
:
1146 error_setg(errp
, "No encryption in image header, but options "
1147 "specified format '%s'", encryptfmt
);
1153 case QCOW_CRYPT_AES
:
1154 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1156 "Header reported 'aes' encryption format but "
1157 "options specify '%s'", encryptfmt
);
1161 qdict_put_str(encryptopts
, "format", "qcow");
1162 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1163 if (!r
->crypto_opts
) {
1169 case QCOW_CRYPT_LUKS
:
1170 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1172 "Header reported 'luks' encryption format but "
1173 "options specify '%s'", encryptfmt
);
1177 qdict_put_str(encryptopts
, "format", "luks");
1178 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1179 if (!r
->crypto_opts
) {
1186 error_setg(errp
, "Unsupported encryption method %d",
1187 s
->crypt_method_header
);
1194 qobject_unref(encryptopts
);
1195 qemu_opts_del(opts
);
1200 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1201 Qcow2ReopenState
*r
)
1203 BDRVQcow2State
*s
= bs
->opaque
;
1206 if (s
->l2_table_cache
) {
1207 qcow2_cache_destroy(s
->l2_table_cache
);
1209 if (s
->refcount_block_cache
) {
1210 qcow2_cache_destroy(s
->refcount_block_cache
);
1212 s
->l2_table_cache
= r
->l2_table_cache
;
1213 s
->refcount_block_cache
= r
->refcount_block_cache
;
1214 s
->l2_slice_size
= r
->l2_slice_size
;
1216 s
->overlap_check
= r
->overlap_check
;
1217 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1219 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1220 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1223 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1224 cache_clean_timer_del(bs
);
1225 s
->cache_clean_interval
= r
->cache_clean_interval
;
1226 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1229 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1230 s
->crypto_opts
= r
->crypto_opts
;
1233 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1234 Qcow2ReopenState
*r
)
1236 if (r
->l2_table_cache
) {
1237 qcow2_cache_destroy(r
->l2_table_cache
);
1239 if (r
->refcount_block_cache
) {
1240 qcow2_cache_destroy(r
->refcount_block_cache
);
1242 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1245 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1246 int flags
, Error
**errp
)
1248 Qcow2ReopenState r
= {};
1251 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1253 qcow2_update_options_commit(bs
, &r
);
1255 qcow2_update_options_abort(bs
, &r
);
1261 static int validate_compression_type(BDRVQcow2State
*s
, Error
**errp
)
1263 switch (s
->compression_type
) {
1264 case QCOW2_COMPRESSION_TYPE_ZLIB
:
1266 case QCOW2_COMPRESSION_TYPE_ZSTD
:
1271 error_setg(errp
, "qcow2: unknown compression type: %u",
1272 s
->compression_type
);
1277 * if the compression type differs from QCOW2_COMPRESSION_TYPE_ZLIB
1278 * the incompatible feature flag must be set
1280 if (s
->compression_type
== QCOW2_COMPRESSION_TYPE_ZLIB
) {
1281 if (s
->incompatible_features
& QCOW2_INCOMPAT_COMPRESSION
) {
1282 error_setg(errp
, "qcow2: Compression type incompatible feature "
1283 "bit must not be set");
1287 if (!(s
->incompatible_features
& QCOW2_INCOMPAT_COMPRESSION
)) {
1288 error_setg(errp
, "qcow2: Compression type incompatible feature "
1297 /* Called with s->lock held. */
1298 static int coroutine_fn
qcow2_do_open(BlockDriverState
*bs
, QDict
*options
,
1299 int flags
, Error
**errp
)
1302 BDRVQcow2State
*s
= bs
->opaque
;
1303 unsigned int len
, i
;
1307 uint64_t l1_vm_state_index
;
1308 bool update_header
= false;
1310 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1312 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1315 header
.magic
= be32_to_cpu(header
.magic
);
1316 header
.version
= be32_to_cpu(header
.version
);
1317 header
.backing_file_offset
= be64_to_cpu(header
.backing_file_offset
);
1318 header
.backing_file_size
= be32_to_cpu(header
.backing_file_size
);
1319 header
.size
= be64_to_cpu(header
.size
);
1320 header
.cluster_bits
= be32_to_cpu(header
.cluster_bits
);
1321 header
.crypt_method
= be32_to_cpu(header
.crypt_method
);
1322 header
.l1_table_offset
= be64_to_cpu(header
.l1_table_offset
);
1323 header
.l1_size
= be32_to_cpu(header
.l1_size
);
1324 header
.refcount_table_offset
= be64_to_cpu(header
.refcount_table_offset
);
1325 header
.refcount_table_clusters
=
1326 be32_to_cpu(header
.refcount_table_clusters
);
1327 header
.snapshots_offset
= be64_to_cpu(header
.snapshots_offset
);
1328 header
.nb_snapshots
= be32_to_cpu(header
.nb_snapshots
);
1330 if (header
.magic
!= QCOW_MAGIC
) {
1331 error_setg(errp
, "Image is not in qcow2 format");
1335 if (header
.version
< 2 || header
.version
> 3) {
1336 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1341 s
->qcow_version
= header
.version
;
1343 /* Initialise cluster size */
1344 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1345 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1346 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1347 header
.cluster_bits
);
1352 s
->cluster_bits
= header
.cluster_bits
;
1353 s
->cluster_size
= 1 << s
->cluster_bits
;
1355 /* Initialise version 3 header fields */
1356 if (header
.version
== 2) {
1357 header
.incompatible_features
= 0;
1358 header
.compatible_features
= 0;
1359 header
.autoclear_features
= 0;
1360 header
.refcount_order
= 4;
1361 header
.header_length
= 72;
1363 header
.incompatible_features
=
1364 be64_to_cpu(header
.incompatible_features
);
1365 header
.compatible_features
= be64_to_cpu(header
.compatible_features
);
1366 header
.autoclear_features
= be64_to_cpu(header
.autoclear_features
);
1367 header
.refcount_order
= be32_to_cpu(header
.refcount_order
);
1368 header
.header_length
= be32_to_cpu(header
.header_length
);
1370 if (header
.header_length
< 104) {
1371 error_setg(errp
, "qcow2 header too short");
1377 if (header
.header_length
> s
->cluster_size
) {
1378 error_setg(errp
, "qcow2 header exceeds cluster size");
1383 if (header
.header_length
> sizeof(header
)) {
1384 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1385 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1386 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1387 s
->unknown_header_fields_size
);
1389 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1395 if (header
.backing_file_offset
> s
->cluster_size
) {
1396 error_setg(errp
, "Invalid backing file offset");
1401 if (header
.backing_file_offset
) {
1402 ext_end
= header
.backing_file_offset
;
1404 ext_end
= 1 << header
.cluster_bits
;
1407 /* Handle feature bits */
1408 s
->incompatible_features
= header
.incompatible_features
;
1409 s
->compatible_features
= header
.compatible_features
;
1410 s
->autoclear_features
= header
.autoclear_features
;
1413 * Handle compression type
1414 * Older qcow2 images don't contain the compression type header.
1415 * Distinguish them by the header length and use
1416 * the only valid (default) compression type in that case
1418 if (header
.header_length
> offsetof(QCowHeader
, compression_type
)) {
1419 s
->compression_type
= header
.compression_type
;
1421 s
->compression_type
= QCOW2_COMPRESSION_TYPE_ZLIB
;
1424 ret
= validate_compression_type(s
, errp
);
1429 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1430 void *feature_table
= NULL
;
1431 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1432 &feature_table
, flags
, NULL
, NULL
);
1433 report_unsupported_feature(errp
, feature_table
,
1434 s
->incompatible_features
&
1435 ~QCOW2_INCOMPAT_MASK
);
1437 g_free(feature_table
);
1441 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1442 /* Corrupt images may not be written to unless they are being repaired
1444 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1445 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1452 s
->subclusters_per_cluster
=
1453 has_subclusters(s
) ? QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER
: 1;
1454 s
->subcluster_size
= s
->cluster_size
/ s
->subclusters_per_cluster
;
1455 s
->subcluster_bits
= ctz32(s
->subcluster_size
);
1457 if (s
->subcluster_size
< (1 << MIN_CLUSTER_BITS
)) {
1458 error_setg(errp
, "Unsupported subcluster size: %d", s
->subcluster_size
);
1463 /* Check support for various header values */
1464 if (header
.refcount_order
> 6) {
1465 error_setg(errp
, "Reference count entry width too large; may not "
1470 s
->refcount_order
= header
.refcount_order
;
1471 s
->refcount_bits
= 1 << s
->refcount_order
;
1472 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1473 s
->refcount_max
+= s
->refcount_max
- 1;
1475 s
->crypt_method_header
= header
.crypt_method
;
1476 if (s
->crypt_method_header
) {
1477 if (bdrv_uses_whitelist() &&
1478 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1480 "Use of AES-CBC encrypted qcow2 images is no longer "
1481 "supported in system emulators");
1482 error_append_hint(errp
,
1483 "You can use 'qemu-img convert' to convert your "
1484 "image to an alternative supported format, such "
1485 "as unencrypted qcow2, or raw with the LUKS "
1486 "format instead.\n");
1491 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1492 s
->crypt_physical_offset
= false;
1494 /* Assuming LUKS and any future crypt methods we
1495 * add will all use physical offsets, due to the
1496 * fact that the alternative is insecure... */
1497 s
->crypt_physical_offset
= true;
1500 bs
->encrypted
= true;
1503 s
->l2_bits
= s
->cluster_bits
- ctz32(l2_entry_size(s
));
1504 s
->l2_size
= 1 << s
->l2_bits
;
1505 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1506 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1507 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1508 bs
->total_sectors
= header
.size
/ BDRV_SECTOR_SIZE
;
1509 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1510 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1511 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1513 s
->refcount_table_offset
= header
.refcount_table_offset
;
1514 s
->refcount_table_size
=
1515 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1517 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1518 error_setg(errp
, "Image does not contain a reference count table");
1523 ret
= qcow2_validate_table(bs
, s
->refcount_table_offset
,
1524 header
.refcount_table_clusters
,
1525 s
->cluster_size
, QCOW_MAX_REFTABLE_SIZE
,
1526 "Reference count table", errp
);
1531 if (!(flags
& BDRV_O_CHECK
)) {
1533 * The total size in bytes of the snapshot table is checked in
1534 * qcow2_read_snapshots() because the size of each snapshot is
1535 * variable and we don't know it yet.
1536 * Here we only check the offset and number of snapshots.
1538 ret
= qcow2_validate_table(bs
, header
.snapshots_offset
,
1539 header
.nb_snapshots
,
1540 sizeof(QCowSnapshotHeader
),
1541 sizeof(QCowSnapshotHeader
) *
1543 "Snapshot table", errp
);
1549 /* read the level 1 table */
1550 ret
= qcow2_validate_table(bs
, header
.l1_table_offset
,
1551 header
.l1_size
, L1E_SIZE
,
1552 QCOW_MAX_L1_SIZE
, "Active L1 table", errp
);
1556 s
->l1_size
= header
.l1_size
;
1557 s
->l1_table_offset
= header
.l1_table_offset
;
1559 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1560 if (l1_vm_state_index
> INT_MAX
) {
1561 error_setg(errp
, "Image is too big");
1565 s
->l1_vm_state_index
= l1_vm_state_index
;
1567 /* the L1 table must contain at least enough entries to put
1568 header.size bytes */
1569 if (s
->l1_size
< s
->l1_vm_state_index
) {
1570 error_setg(errp
, "L1 table is too small");
1575 if (s
->l1_size
> 0) {
1576 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
, s
->l1_size
* L1E_SIZE
);
1577 if (s
->l1_table
== NULL
) {
1578 error_setg(errp
, "Could not allocate L1 table");
1582 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1583 s
->l1_size
* L1E_SIZE
);
1585 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1588 for(i
= 0;i
< s
->l1_size
; i
++) {
1589 s
->l1_table
[i
] = be64_to_cpu(s
->l1_table
[i
]);
1593 /* Parse driver-specific options */
1594 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1601 ret
= qcow2_refcount_init(bs
);
1603 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1607 QLIST_INIT(&s
->cluster_allocs
);
1608 QTAILQ_INIT(&s
->discards
);
1610 /* read qcow2 extensions */
1611 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1612 flags
, &update_header
, errp
)) {
1617 /* Open external data file */
1618 s
->data_file
= bdrv_open_child(NULL
, options
, "data-file", bs
,
1619 &child_of_bds
, BDRV_CHILD_DATA
,
1626 if (s
->incompatible_features
& QCOW2_INCOMPAT_DATA_FILE
) {
1627 if (!s
->data_file
&& s
->image_data_file
) {
1628 s
->data_file
= bdrv_open_child(s
->image_data_file
, options
,
1629 "data-file", bs
, &child_of_bds
,
1630 BDRV_CHILD_DATA
, false, errp
);
1631 if (!s
->data_file
) {
1636 if (!s
->data_file
) {
1637 error_setg(errp
, "'data-file' is required for this image");
1643 bs
->file
->role
&= ~BDRV_CHILD_DATA
;
1645 /* Must succeed because we have given up permissions if anything */
1646 bdrv_child_refresh_perms(bs
, bs
->file
, &error_abort
);
1649 error_setg(errp
, "'data-file' can only be set for images with an "
1650 "external data file");
1655 s
->data_file
= bs
->file
;
1657 if (data_file_is_raw(bs
)) {
1658 error_setg(errp
, "data-file-raw requires a data file");
1664 /* qcow2_read_extension may have set up the crypto context
1665 * if the crypt method needs a header region, some methods
1666 * don't need header extensions, so must check here
1668 if (s
->crypt_method_header
&& !s
->crypto
) {
1669 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1670 unsigned int cflags
= 0;
1671 if (flags
& BDRV_O_NO_IO
) {
1672 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1674 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1676 QCOW2_MAX_THREADS
, errp
);
1681 } else if (!(flags
& BDRV_O_NO_IO
)) {
1682 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1683 s
->crypt_method_header
);
1689 /* read the backing file name */
1690 if (header
.backing_file_offset
!= 0) {
1691 len
= header
.backing_file_size
;
1692 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1693 len
>= sizeof(bs
->backing_file
)) {
1694 error_setg(errp
, "Backing file name too long");
1698 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1699 bs
->auto_backing_file
, len
);
1701 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1704 bs
->auto_backing_file
[len
] = '\0';
1705 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
),
1706 bs
->auto_backing_file
);
1707 s
->image_backing_file
= g_strdup(bs
->auto_backing_file
);
1711 * Internal snapshots; skip reading them in check mode, because
1712 * we do not need them then, and we do not want to abort because
1713 * of a broken table.
1715 if (!(flags
& BDRV_O_CHECK
)) {
1716 s
->snapshots_offset
= header
.snapshots_offset
;
1717 s
->nb_snapshots
= header
.nb_snapshots
;
1719 ret
= qcow2_read_snapshots(bs
, errp
);
1725 /* Clear unknown autoclear feature bits */
1726 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1727 update_header
= update_header
&& bdrv_is_writable(bs
);
1728 if (update_header
) {
1729 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1732 /* == Handle persistent dirty bitmaps ==
1734 * We want load dirty bitmaps in three cases:
1736 * 1. Normal open of the disk in active mode, not related to invalidation
1739 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1740 * bitmaps are _not_ migrating through migration channel, i.e.
1741 * 'dirty-bitmaps' capability is disabled.
1743 * 3. Invalidation of source vm after failed or canceled migration.
1744 * This is a very interesting case. There are two possible types of
1747 * A. Stored on inactivation and removed. They should be loaded from the
1750 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1751 * the migration channel (with dirty-bitmaps capability).
1753 * On the other hand, there are two possible sub-cases:
1755 * 3.1 disk was changed by somebody else while were inactive. In this
1756 * case all in-RAM dirty bitmaps (both persistent and not) are
1757 * definitely invalid. And we don't have any method to determine
1760 * Simple and safe thing is to just drop all the bitmaps of type B on
1761 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1763 * On the other hand, resuming source vm, if disk was already changed
1764 * is a bad thing anyway: not only bitmaps, the whole vm state is
1765 * out of sync with disk.
1767 * This means, that user or management tool, who for some reason
1768 * decided to resume source vm, after disk was already changed by
1769 * target vm, should at least drop all dirty bitmaps by hand.
1771 * So, we can ignore this case for now, but TODO: "generation"
1772 * extension for qcow2, to determine, that image was changed after
1773 * last inactivation. And if it is changed, we will drop (or at least
1774 * mark as 'invalid' all the bitmaps of type B, both persistent
1777 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1778 * to disk ('dirty-bitmaps' capability disabled), or not saved
1779 * ('dirty-bitmaps' capability enabled), but we don't need to care
1780 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1781 * and not stored has flag IN_USE=1 in the image and will be skipped
1784 * One remaining possible case when we don't want load bitmaps:
1786 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1787 * will be loaded on invalidation, no needs try loading them before)
1790 if (!(bdrv_get_flags(bs
) & BDRV_O_INACTIVE
)) {
1791 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1792 bool header_updated
;
1793 if (!qcow2_load_dirty_bitmaps(bs
, &header_updated
, errp
)) {
1798 update_header
= update_header
&& !header_updated
;
1801 if (update_header
) {
1802 ret
= qcow2_update_header(bs
);
1804 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1809 bs
->supported_zero_flags
= header
.version
>= 3 ?
1810 BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
: 0;
1811 bs
->supported_truncate_flags
= BDRV_REQ_ZERO_WRITE
;
1813 /* Repair image if dirty */
1814 if (!(flags
& BDRV_O_CHECK
) && bdrv_is_writable(bs
) &&
1815 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1816 BdrvCheckResult result
= {0};
1818 ret
= qcow2_co_check_locked(bs
, &result
,
1819 BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1820 if (ret
< 0 || result
.check_errors
) {
1824 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1831 BdrvCheckResult result
= {0};
1832 qcow2_check_refcounts(bs
, &result
, 0);
1836 qemu_co_queue_init(&s
->thread_task_queue
);
1841 g_free(s
->image_data_file
);
1842 if (has_data_file(bs
)) {
1843 bdrv_unref_child(bs
, s
->data_file
);
1844 s
->data_file
= NULL
;
1846 g_free(s
->unknown_header_fields
);
1847 cleanup_unknown_header_ext(bs
);
1848 qcow2_free_snapshots(bs
);
1849 qcow2_refcount_close(bs
);
1850 qemu_vfree(s
->l1_table
);
1851 /* else pre-write overlap checks in cache_destroy may crash */
1853 cache_clean_timer_del(bs
);
1854 if (s
->l2_table_cache
) {
1855 qcow2_cache_destroy(s
->l2_table_cache
);
1857 if (s
->refcount_block_cache
) {
1858 qcow2_cache_destroy(s
->refcount_block_cache
);
1860 qcrypto_block_free(s
->crypto
);
1861 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1865 typedef struct QCow2OpenCo
{
1866 BlockDriverState
*bs
;
1873 static void coroutine_fn
qcow2_open_entry(void *opaque
)
1875 QCow2OpenCo
*qoc
= opaque
;
1876 BDRVQcow2State
*s
= qoc
->bs
->opaque
;
1878 qemu_co_mutex_lock(&s
->lock
);
1879 qoc
->ret
= qcow2_do_open(qoc
->bs
, qoc
->options
, qoc
->flags
, qoc
->errp
);
1880 qemu_co_mutex_unlock(&s
->lock
);
1883 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1886 BDRVQcow2State
*s
= bs
->opaque
;
1895 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_of_bds
,
1896 BDRV_CHILD_IMAGE
, false, errp
);
1901 /* Initialise locks */
1902 qemu_co_mutex_init(&s
->lock
);
1904 if (qemu_in_coroutine()) {
1905 /* From bdrv_co_create. */
1906 qcow2_open_entry(&qoc
);
1908 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1909 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry
, &qoc
));
1910 BDRV_POLL_WHILE(bs
, qoc
.ret
== -EINPROGRESS
);
1915 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1917 BDRVQcow2State
*s
= bs
->opaque
;
1919 if (bs
->encrypted
) {
1920 /* Encryption works on a sector granularity */
1921 bs
->bl
.request_alignment
= qcrypto_block_get_sector_size(s
->crypto
);
1923 bs
->bl
.pwrite_zeroes_alignment
= s
->subcluster_size
;
1924 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1927 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1928 BlockReopenQueue
*queue
, Error
**errp
)
1930 BDRVQcow2State
*s
= state
->bs
->opaque
;
1931 Qcow2ReopenState
*r
;
1934 r
= g_new0(Qcow2ReopenState
, 1);
1937 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1938 state
->flags
, errp
);
1943 /* We need to write out any unwritten data if we reopen read-only. */
1944 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1945 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1950 ret
= bdrv_flush(state
->bs
);
1955 ret
= qcow2_mark_clean(state
->bs
);
1962 * Without an external data file, s->data_file points to the same BdrvChild
1963 * as bs->file. It needs to be resynced after reopen because bs->file may
1964 * be changed. We can't use it in the meantime.
1966 if (!has_data_file(state
->bs
)) {
1967 assert(s
->data_file
== state
->bs
->file
);
1968 s
->data_file
= NULL
;
1974 qcow2_update_options_abort(state
->bs
, r
);
1979 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1981 BDRVQcow2State
*s
= state
->bs
->opaque
;
1983 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1984 if (!s
->data_file
) {
1986 * If we don't have an external data file, s->data_file was cleared by
1987 * qcow2_reopen_prepare() and needs to be updated.
1989 s
->data_file
= state
->bs
->file
;
1991 g_free(state
->opaque
);
1994 static void qcow2_reopen_commit_post(BDRVReopenState
*state
)
1996 if (state
->flags
& BDRV_O_RDWR
) {
1997 Error
*local_err
= NULL
;
1999 if (qcow2_reopen_bitmaps_rw(state
->bs
, &local_err
) < 0) {
2001 * This is not fatal, bitmaps just left read-only, so all following
2002 * writes will fail. User can remove read-only bitmaps to unblock
2003 * writes or retry reopen.
2005 error_reportf_err(local_err
,
2006 "%s: Failed to make dirty bitmaps writable: ",
2007 bdrv_get_node_name(state
->bs
));
2012 static void qcow2_reopen_abort(BDRVReopenState
*state
)
2014 BDRVQcow2State
*s
= state
->bs
->opaque
;
2016 if (!s
->data_file
) {
2018 * If we don't have an external data file, s->data_file was cleared by
2019 * qcow2_reopen_prepare() and needs to be restored.
2021 s
->data_file
= state
->bs
->file
;
2023 qcow2_update_options_abort(state
->bs
, state
->opaque
);
2024 g_free(state
->opaque
);
2027 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
2029 bool has_new_overlap_template
=
2030 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
2031 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
2032 bool has_new_total_cache_size
=
2033 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
2034 bool has_all_cache_options
;
2036 /* New overlap template overrides all old overlap options */
2037 if (has_new_overlap_template
) {
2038 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
2039 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
2040 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
2041 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
2042 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
2043 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
2044 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
2045 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
2046 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
2047 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
2050 /* New total cache size overrides all old options */
2051 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
2052 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
2053 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
2056 qdict_join(options
, old_options
, false);
2059 * If after merging all cache size options are set, an old total size is
2060 * overwritten. Do keep all options, however, if all three are new. The
2061 * resulting error message is what we want to happen.
2063 has_all_cache_options
=
2064 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
2065 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
2066 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
2068 if (has_all_cache_options
&& !has_new_total_cache_size
) {
2069 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
2073 static int coroutine_fn
qcow2_co_block_status(BlockDriverState
*bs
,
2075 int64_t offset
, int64_t count
,
2076 int64_t *pnum
, int64_t *map
,
2077 BlockDriverState
**file
)
2079 BDRVQcow2State
*s
= bs
->opaque
;
2080 uint64_t host_offset
;
2082 QCow2SubclusterType type
;
2083 int ret
, status
= 0;
2085 qemu_co_mutex_lock(&s
->lock
);
2087 if (!s
->metadata_preallocation_checked
) {
2088 ret
= qcow2_detect_metadata_preallocation(bs
);
2089 s
->metadata_preallocation
= (ret
== 1);
2090 s
->metadata_preallocation_checked
= true;
2093 bytes
= MIN(INT_MAX
, count
);
2094 ret
= qcow2_get_host_offset(bs
, offset
, &bytes
, &host_offset
, &type
);
2095 qemu_co_mutex_unlock(&s
->lock
);
2102 if ((type
== QCOW2_SUBCLUSTER_NORMAL
||
2103 type
== QCOW2_SUBCLUSTER_ZERO_ALLOC
||
2104 type
== QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC
) && !s
->crypto
) {
2106 *file
= s
->data_file
->bs
;
2107 status
|= BDRV_BLOCK_OFFSET_VALID
;
2109 if (type
== QCOW2_SUBCLUSTER_ZERO_PLAIN
||
2110 type
== QCOW2_SUBCLUSTER_ZERO_ALLOC
) {
2111 status
|= BDRV_BLOCK_ZERO
;
2112 } else if (type
!= QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN
&&
2113 type
!= QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC
) {
2114 status
|= BDRV_BLOCK_DATA
;
2116 if (s
->metadata_preallocation
&& (status
& BDRV_BLOCK_DATA
) &&
2117 (status
& BDRV_BLOCK_OFFSET_VALID
))
2119 status
|= BDRV_BLOCK_RECURSE
;
2124 static coroutine_fn
int qcow2_handle_l2meta(BlockDriverState
*bs
,
2125 QCowL2Meta
**pl2meta
,
2129 QCowL2Meta
*l2meta
= *pl2meta
;
2131 while (l2meta
!= NULL
) {
2135 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
2140 qcow2_alloc_cluster_abort(bs
, l2meta
);
2143 /* Take the request off the list of running requests */
2144 QLIST_REMOVE(l2meta
, next_in_flight
);
2146 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2148 next
= l2meta
->next
;
2157 static coroutine_fn
int
2158 qcow2_co_preadv_encrypted(BlockDriverState
*bs
,
2159 uint64_t host_offset
,
2163 uint64_t qiov_offset
)
2166 BDRVQcow2State
*s
= bs
->opaque
;
2169 assert(bs
->encrypted
&& s
->crypto
);
2170 assert(bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2173 * For encrypted images, read everything into a temporary
2174 * contiguous buffer on which the AES functions can work.
2175 * Also, decryption in a separate buffer is better as it
2176 * prevents the guest from learning information about the
2177 * encrypted nature of the virtual disk.
2180 buf
= qemu_try_blockalign(s
->data_file
->bs
, bytes
);
2185 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
2186 ret
= bdrv_co_pread(s
->data_file
, host_offset
, bytes
, buf
, 0);
2191 if (qcow2_co_decrypt(bs
, host_offset
, offset
, buf
, bytes
) < 0)
2196 qemu_iovec_from_buf(qiov
, qiov_offset
, buf
, bytes
);
2204 typedef struct Qcow2AioTask
{
2207 BlockDriverState
*bs
;
2208 QCow2SubclusterType subcluster_type
; /* only for read */
2209 uint64_t host_offset
; /* or l2_entry for compressed read */
2213 uint64_t qiov_offset
;
2214 QCowL2Meta
*l2meta
; /* only for write */
2217 static coroutine_fn
int qcow2_co_preadv_task_entry(AioTask
*task
);
2218 static coroutine_fn
int qcow2_add_task(BlockDriverState
*bs
,
2221 QCow2SubclusterType subcluster_type
,
2222 uint64_t host_offset
,
2229 Qcow2AioTask local_task
;
2230 Qcow2AioTask
*task
= pool
? g_new(Qcow2AioTask
, 1) : &local_task
;
2232 *task
= (Qcow2AioTask
) {
2235 .subcluster_type
= subcluster_type
,
2237 .host_offset
= host_offset
,
2240 .qiov_offset
= qiov_offset
,
2244 trace_qcow2_add_task(qemu_coroutine_self(), bs
, pool
,
2245 func
== qcow2_co_preadv_task_entry
? "read" : "write",
2246 subcluster_type
, host_offset
, offset
, bytes
,
2250 return func(&task
->task
);
2253 aio_task_pool_start_task(pool
, &task
->task
);
2258 static coroutine_fn
int qcow2_co_preadv_task(BlockDriverState
*bs
,
2259 QCow2SubclusterType subc_type
,
2260 uint64_t host_offset
,
2261 uint64_t offset
, uint64_t bytes
,
2265 BDRVQcow2State
*s
= bs
->opaque
;
2267 switch (subc_type
) {
2268 case QCOW2_SUBCLUSTER_ZERO_PLAIN
:
2269 case QCOW2_SUBCLUSTER_ZERO_ALLOC
:
2270 /* Both zero types are handled in qcow2_co_preadv_part */
2271 g_assert_not_reached();
2273 case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN
:
2274 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC
:
2275 assert(bs
->backing
); /* otherwise handled in qcow2_co_preadv_part */
2277 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
2278 return bdrv_co_preadv_part(bs
->backing
, offset
, bytes
,
2279 qiov
, qiov_offset
, 0);
2281 case QCOW2_SUBCLUSTER_COMPRESSED
:
2282 return qcow2_co_preadv_compressed(bs
, host_offset
,
2283 offset
, bytes
, qiov
, qiov_offset
);
2285 case QCOW2_SUBCLUSTER_NORMAL
:
2286 if (bs
->encrypted
) {
2287 return qcow2_co_preadv_encrypted(bs
, host_offset
,
2288 offset
, bytes
, qiov
, qiov_offset
);
2291 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
2292 return bdrv_co_preadv_part(s
->data_file
, host_offset
,
2293 bytes
, qiov
, qiov_offset
, 0);
2296 g_assert_not_reached();
2299 g_assert_not_reached();
2302 static coroutine_fn
int qcow2_co_preadv_task_entry(AioTask
*task
)
2304 Qcow2AioTask
*t
= container_of(task
, Qcow2AioTask
, task
);
2308 return qcow2_co_preadv_task(t
->bs
, t
->subcluster_type
,
2309 t
->host_offset
, t
->offset
, t
->bytes
,
2310 t
->qiov
, t
->qiov_offset
);
2313 static coroutine_fn
int qcow2_co_preadv_part(BlockDriverState
*bs
,
2314 int64_t offset
, int64_t bytes
,
2317 BdrvRequestFlags flags
)
2319 BDRVQcow2State
*s
= bs
->opaque
;
2321 unsigned int cur_bytes
; /* number of bytes in current iteration */
2322 uint64_t host_offset
= 0;
2323 QCow2SubclusterType type
;
2324 AioTaskPool
*aio
= NULL
;
2326 while (bytes
!= 0 && aio_task_pool_status(aio
) == 0) {
2327 /* prepare next request */
2328 cur_bytes
= MIN(bytes
, INT_MAX
);
2330 cur_bytes
= MIN(cur_bytes
,
2331 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2334 qemu_co_mutex_lock(&s
->lock
);
2335 ret
= qcow2_get_host_offset(bs
, offset
, &cur_bytes
,
2336 &host_offset
, &type
);
2337 qemu_co_mutex_unlock(&s
->lock
);
2342 if (type
== QCOW2_SUBCLUSTER_ZERO_PLAIN
||
2343 type
== QCOW2_SUBCLUSTER_ZERO_ALLOC
||
2344 (type
== QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN
&& !bs
->backing
) ||
2345 (type
== QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC
&& !bs
->backing
))
2347 qemu_iovec_memset(qiov
, qiov_offset
, 0, cur_bytes
);
2349 if (!aio
&& cur_bytes
!= bytes
) {
2350 aio
= aio_task_pool_new(QCOW2_MAX_WORKERS
);
2352 ret
= qcow2_add_task(bs
, aio
, qcow2_co_preadv_task_entry
, type
,
2353 host_offset
, offset
, cur_bytes
,
2354 qiov
, qiov_offset
, NULL
);
2361 offset
+= cur_bytes
;
2362 qiov_offset
+= cur_bytes
;
2367 aio_task_pool_wait_all(aio
);
2369 ret
= aio_task_pool_status(aio
);
2377 /* Check if it's possible to merge a write request with the writing of
2378 * the data from the COW regions */
2379 static bool merge_cow(uint64_t offset
, unsigned bytes
,
2380 QEMUIOVector
*qiov
, size_t qiov_offset
,
2385 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
2386 /* If both COW regions are empty then there's nothing to merge */
2387 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
2391 /* If COW regions are handled already, skip this too */
2397 * The write request should start immediately after the first
2398 * COW region. This does not always happen because the area
2399 * touched by the request can be larger than the one defined
2400 * by @m (a single request can span an area consisting of a
2401 * mix of previously unallocated and allocated clusters, that
2402 * is why @l2meta is a list).
2404 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
2405 /* In this case the request starts before this region */
2406 assert(offset
< l2meta_cow_start(m
));
2407 assert(m
->cow_start
.nb_bytes
== 0);
2411 /* The write request should end immediately before the second
2412 * COW region (see above for why it does not always happen) */
2413 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
2414 assert(offset
+ bytes
> m
->offset
+ m
->cow_end
.offset
);
2415 assert(m
->cow_end
.nb_bytes
== 0);
2419 /* Make sure that adding both COW regions to the QEMUIOVector
2420 * does not exceed IOV_MAX */
2421 if (qemu_iovec_subvec_niov(qiov
, qiov_offset
, bytes
) > IOV_MAX
- 2) {
2425 m
->data_qiov
= qiov
;
2426 m
->data_qiov_offset
= qiov_offset
;
2434 * Return 1 if the COW regions read as zeroes, 0 if not, < 0 on error.
2435 * Note that returning 0 does not guarantee non-zero data.
2437 static int is_zero_cow(BlockDriverState
*bs
, QCowL2Meta
*m
)
2440 * This check is designed for optimization shortcut so it must be
2442 * Instead of is_zero(), use bdrv_co_is_zero_fast() as it is
2443 * faster (but not as accurate and can result in false negatives).
2445 int ret
= bdrv_co_is_zero_fast(bs
, m
->offset
+ m
->cow_start
.offset
,
2446 m
->cow_start
.nb_bytes
);
2451 return bdrv_co_is_zero_fast(bs
, m
->offset
+ m
->cow_end
.offset
,
2452 m
->cow_end
.nb_bytes
);
2455 static int handle_alloc_space(BlockDriverState
*bs
, QCowL2Meta
*l2meta
)
2457 BDRVQcow2State
*s
= bs
->opaque
;
2460 if (!(s
->data_file
->bs
->supported_zero_flags
& BDRV_REQ_NO_FALLBACK
)) {
2464 if (bs
->encrypted
) {
2468 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
2470 uint64_t start_offset
= m
->alloc_offset
+ m
->cow_start
.offset
;
2471 unsigned nb_bytes
= m
->cow_end
.offset
+ m
->cow_end
.nb_bytes
-
2472 m
->cow_start
.offset
;
2474 if (!m
->cow_start
.nb_bytes
&& !m
->cow_end
.nb_bytes
) {
2478 ret
= is_zero_cow(bs
, m
);
2481 } else if (ret
== 0) {
2486 * instead of writing zero COW buffers,
2487 * efficiently zero out the whole clusters
2490 ret
= qcow2_pre_write_overlap_check(bs
, 0, start_offset
, nb_bytes
,
2496 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC_SPACE
);
2497 ret
= bdrv_co_pwrite_zeroes(s
->data_file
, start_offset
, nb_bytes
,
2498 BDRV_REQ_NO_FALLBACK
);
2500 if (ret
!= -ENOTSUP
&& ret
!= -EAGAIN
) {
2506 trace_qcow2_skip_cow(qemu_coroutine_self(), m
->offset
, m
->nb_clusters
);
2513 * qcow2_co_pwritev_task
2514 * Called with s->lock unlocked
2515 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2516 * not use it somehow after qcow2_co_pwritev_task() call
2518 static coroutine_fn
int qcow2_co_pwritev_task(BlockDriverState
*bs
,
2519 uint64_t host_offset
,
2520 uint64_t offset
, uint64_t bytes
,
2522 uint64_t qiov_offset
,
2526 BDRVQcow2State
*s
= bs
->opaque
;
2527 void *crypt_buf
= NULL
;
2528 QEMUIOVector encrypted_qiov
;
2530 if (bs
->encrypted
) {
2532 assert(bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2533 crypt_buf
= qemu_try_blockalign(bs
->file
->bs
, bytes
);
2534 if (crypt_buf
== NULL
) {
2538 qemu_iovec_to_buf(qiov
, qiov_offset
, crypt_buf
, bytes
);
2540 if (qcow2_co_encrypt(bs
, host_offset
, offset
, crypt_buf
, bytes
) < 0) {
2545 qemu_iovec_init_buf(&encrypted_qiov
, crypt_buf
, bytes
);
2546 qiov
= &encrypted_qiov
;
2550 /* Try to efficiently initialize the physical space with zeroes */
2551 ret
= handle_alloc_space(bs
, l2meta
);
2557 * If we need to do COW, check if it's possible to merge the
2558 * writing of the guest data together with that of the COW regions.
2559 * If it's not possible (or not necessary) then write the
2562 if (!merge_cow(offset
, bytes
, qiov
, qiov_offset
, l2meta
)) {
2563 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
2564 trace_qcow2_writev_data(qemu_coroutine_self(), host_offset
);
2565 ret
= bdrv_co_pwritev_part(s
->data_file
, host_offset
,
2566 bytes
, qiov
, qiov_offset
, 0);
2572 qemu_co_mutex_lock(&s
->lock
);
2574 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
2578 qemu_co_mutex_lock(&s
->lock
);
2581 qcow2_handle_l2meta(bs
, &l2meta
, false);
2582 qemu_co_mutex_unlock(&s
->lock
);
2584 qemu_vfree(crypt_buf
);
2589 static coroutine_fn
int qcow2_co_pwritev_task_entry(AioTask
*task
)
2591 Qcow2AioTask
*t
= container_of(task
, Qcow2AioTask
, task
);
2593 assert(!t
->subcluster_type
);
2595 return qcow2_co_pwritev_task(t
->bs
, t
->host_offset
,
2596 t
->offset
, t
->bytes
, t
->qiov
, t
->qiov_offset
,
2600 static coroutine_fn
int qcow2_co_pwritev_part(
2601 BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2602 QEMUIOVector
*qiov
, size_t qiov_offset
, BdrvRequestFlags flags
)
2604 BDRVQcow2State
*s
= bs
->opaque
;
2605 int offset_in_cluster
;
2607 unsigned int cur_bytes
; /* number of sectors in current iteration */
2608 uint64_t host_offset
;
2609 QCowL2Meta
*l2meta
= NULL
;
2610 AioTaskPool
*aio
= NULL
;
2612 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
2614 while (bytes
!= 0 && aio_task_pool_status(aio
) == 0) {
2618 trace_qcow2_writev_start_part(qemu_coroutine_self());
2619 offset_in_cluster
= offset_into_cluster(s
, offset
);
2620 cur_bytes
= MIN(bytes
, INT_MAX
);
2621 if (bs
->encrypted
) {
2622 cur_bytes
= MIN(cur_bytes
,
2623 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
2624 - offset_in_cluster
);
2627 qemu_co_mutex_lock(&s
->lock
);
2629 ret
= qcow2_alloc_host_offset(bs
, offset
, &cur_bytes
,
2630 &host_offset
, &l2meta
);
2635 ret
= qcow2_pre_write_overlap_check(bs
, 0, host_offset
,
2641 qemu_co_mutex_unlock(&s
->lock
);
2643 if (!aio
&& cur_bytes
!= bytes
) {
2644 aio
= aio_task_pool_new(QCOW2_MAX_WORKERS
);
2646 ret
= qcow2_add_task(bs
, aio
, qcow2_co_pwritev_task_entry
, 0,
2647 host_offset
, offset
,
2648 cur_bytes
, qiov
, qiov_offset
, l2meta
);
2649 l2meta
= NULL
; /* l2meta is consumed by qcow2_co_pwritev_task() */
2655 offset
+= cur_bytes
;
2656 qiov_offset
+= cur_bytes
;
2657 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2661 qemu_co_mutex_lock(&s
->lock
);
2664 qcow2_handle_l2meta(bs
, &l2meta
, false);
2666 qemu_co_mutex_unlock(&s
->lock
);
2670 aio_task_pool_wait_all(aio
);
2672 ret
= aio_task_pool_status(aio
);
2677 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2682 static int qcow2_inactivate(BlockDriverState
*bs
)
2684 BDRVQcow2State
*s
= bs
->opaque
;
2685 int ret
, result
= 0;
2686 Error
*local_err
= NULL
;
2688 qcow2_store_persistent_dirty_bitmaps(bs
, true, &local_err
);
2689 if (local_err
!= NULL
) {
2691 error_reportf_err(local_err
, "Lost persistent bitmaps during "
2692 "inactivation of node '%s': ",
2693 bdrv_get_device_or_node_name(bs
));
2696 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2699 error_report("Failed to flush the L2 table cache: %s",
2703 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2706 error_report("Failed to flush the refcount block cache: %s",
2711 qcow2_mark_clean(bs
);
2717 static void qcow2_close(BlockDriverState
*bs
)
2719 BDRVQcow2State
*s
= bs
->opaque
;
2720 qemu_vfree(s
->l1_table
);
2721 /* else pre-write overlap checks in cache_destroy may crash */
2724 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2725 qcow2_inactivate(bs
);
2728 cache_clean_timer_del(bs
);
2729 qcow2_cache_destroy(s
->l2_table_cache
);
2730 qcow2_cache_destroy(s
->refcount_block_cache
);
2732 qcrypto_block_free(s
->crypto
);
2734 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
2736 g_free(s
->unknown_header_fields
);
2737 cleanup_unknown_header_ext(bs
);
2739 g_free(s
->image_data_file
);
2740 g_free(s
->image_backing_file
);
2741 g_free(s
->image_backing_format
);
2743 if (has_data_file(bs
)) {
2744 bdrv_unref_child(bs
, s
->data_file
);
2745 s
->data_file
= NULL
;
2748 qcow2_refcount_close(bs
);
2749 qcow2_free_snapshots(bs
);
2752 static void coroutine_fn
qcow2_co_invalidate_cache(BlockDriverState
*bs
,
2756 BDRVQcow2State
*s
= bs
->opaque
;
2757 int flags
= s
->flags
;
2758 QCryptoBlock
*crypto
= NULL
;
2763 * Backing files are read-only which makes all of their metadata immutable,
2764 * that means we don't have to worry about reopening them here.
2772 memset(s
, 0, sizeof(BDRVQcow2State
));
2773 options
= qdict_clone_shallow(bs
->options
);
2775 flags
&= ~BDRV_O_INACTIVE
;
2776 qemu_co_mutex_lock(&s
->lock
);
2777 ret
= qcow2_do_open(bs
, options
, flags
, errp
);
2778 qemu_co_mutex_unlock(&s
->lock
);
2779 qobject_unref(options
);
2781 error_prepend(errp
, "Could not reopen qcow2 layer: ");
2789 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2790 size_t len
, size_t buflen
)
2792 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2793 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2795 if (buflen
< ext_len
) {
2799 *ext_backing_fmt
= (QCowExtension
) {
2800 .magic
= cpu_to_be32(magic
),
2801 .len
= cpu_to_be32(len
),
2805 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2812 * Updates the qcow2 header, including the variable length parts of it, i.e.
2813 * the backing file name and all extensions. qcow2 was not designed to allow
2814 * such changes, so if we run out of space (we can only use the first cluster)
2815 * this function may fail.
2817 * Returns 0 on success, -errno in error cases.
2819 int qcow2_update_header(BlockDriverState
*bs
)
2821 BDRVQcow2State
*s
= bs
->opaque
;
2824 size_t buflen
= s
->cluster_size
;
2826 uint64_t total_size
;
2827 uint32_t refcount_table_clusters
;
2828 size_t header_length
;
2829 Qcow2UnknownHeaderExtension
*uext
;
2831 buf
= qemu_blockalign(bs
, buflen
);
2833 /* Header structure */
2834 header
= (QCowHeader
*) buf
;
2836 if (buflen
< sizeof(*header
)) {
2841 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2842 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2843 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2845 ret
= validate_compression_type(s
, NULL
);
2850 *header
= (QCowHeader
) {
2851 /* Version 2 fields */
2852 .magic
= cpu_to_be32(QCOW_MAGIC
),
2853 .version
= cpu_to_be32(s
->qcow_version
),
2854 .backing_file_offset
= 0,
2855 .backing_file_size
= 0,
2856 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2857 .size
= cpu_to_be64(total_size
),
2858 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2859 .l1_size
= cpu_to_be32(s
->l1_size
),
2860 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2861 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2862 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2863 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2864 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2866 /* Version 3 fields */
2867 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2868 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2869 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2870 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2871 .header_length
= cpu_to_be32(header_length
),
2872 .compression_type
= s
->compression_type
,
2875 /* For older versions, write a shorter header */
2876 switch (s
->qcow_version
) {
2878 ret
= offsetof(QCowHeader
, incompatible_features
);
2881 ret
= sizeof(*header
);
2890 memset(buf
, 0, buflen
);
2892 /* Preserve any unknown field in the header */
2893 if (s
->unknown_header_fields_size
) {
2894 if (buflen
< s
->unknown_header_fields_size
) {
2899 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2900 buf
+= s
->unknown_header_fields_size
;
2901 buflen
-= s
->unknown_header_fields_size
;
2904 /* Backing file format header extension */
2905 if (s
->image_backing_format
) {
2906 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2907 s
->image_backing_format
,
2908 strlen(s
->image_backing_format
),
2918 /* External data file header extension */
2919 if (has_data_file(bs
) && s
->image_data_file
) {
2920 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_DATA_FILE
,
2921 s
->image_data_file
, strlen(s
->image_data_file
),
2931 /* Full disk encryption header pointer extension */
2932 if (s
->crypto_header
.offset
!= 0) {
2933 s
->crypto_header
.offset
= cpu_to_be64(s
->crypto_header
.offset
);
2934 s
->crypto_header
.length
= cpu_to_be64(s
->crypto_header
.length
);
2935 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2936 &s
->crypto_header
, sizeof(s
->crypto_header
),
2938 s
->crypto_header
.offset
= be64_to_cpu(s
->crypto_header
.offset
);
2939 s
->crypto_header
.length
= be64_to_cpu(s
->crypto_header
.length
);
2948 * Feature table. A mere 8 feature names occupies 392 bytes, and
2949 * when coupled with the v3 minimum header of 104 bytes plus the
2950 * 8-byte end-of-extension marker, that would leave only 8 bytes
2951 * for a backing file name in an image with 512-byte clusters.
2952 * Thus, we choose to omit this header for cluster sizes 4k and
2955 if (s
->qcow_version
>= 3 && s
->cluster_size
> 4096) {
2956 static const Qcow2Feature features
[] = {
2958 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2959 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2960 .name
= "dirty bit",
2963 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2964 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2965 .name
= "corrupt bit",
2968 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2969 .bit
= QCOW2_INCOMPAT_DATA_FILE_BITNR
,
2970 .name
= "external data file",
2973 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2974 .bit
= QCOW2_INCOMPAT_COMPRESSION_BITNR
,
2975 .name
= "compression type",
2978 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2979 .bit
= QCOW2_INCOMPAT_EXTL2_BITNR
,
2980 .name
= "extended L2 entries",
2983 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2984 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2985 .name
= "lazy refcounts",
2988 .type
= QCOW2_FEAT_TYPE_AUTOCLEAR
,
2989 .bit
= QCOW2_AUTOCLEAR_BITMAPS_BITNR
,
2993 .type
= QCOW2_FEAT_TYPE_AUTOCLEAR
,
2994 .bit
= QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR
,
2995 .name
= "raw external data",
2999 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
3000 features
, sizeof(features
), buflen
);
3008 /* Bitmap extension */
3009 if (s
->nb_bitmaps
> 0) {
3010 Qcow2BitmapHeaderExt bitmaps_header
= {
3011 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
3012 .bitmap_directory_size
=
3013 cpu_to_be64(s
->bitmap_directory_size
),
3014 .bitmap_directory_offset
=
3015 cpu_to_be64(s
->bitmap_directory_offset
)
3017 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
3018 &bitmaps_header
, sizeof(bitmaps_header
),
3027 /* Keep unknown header extensions */
3028 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
3029 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
3038 /* End of header extensions */
3039 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
3047 /* Backing file name */
3048 if (s
->image_backing_file
) {
3049 size_t backing_file_len
= strlen(s
->image_backing_file
);
3051 if (buflen
< backing_file_len
) {
3056 /* Using strncpy is ok here, since buf is not NUL-terminated. */
3057 strncpy(buf
, s
->image_backing_file
, buflen
);
3059 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
3060 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
3063 /* Write the new header */
3064 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
3075 static int qcow2_change_backing_file(BlockDriverState
*bs
,
3076 const char *backing_file
, const char *backing_fmt
)
3078 BDRVQcow2State
*s
= bs
->opaque
;
3080 /* Adding a backing file means that the external data file alone won't be
3081 * enough to make sense of the content */
3082 if (backing_file
&& data_file_is_raw(bs
)) {
3086 if (backing_file
&& strlen(backing_file
) > 1023) {
3090 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
3091 backing_file
?: "");
3092 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
3093 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
3095 g_free(s
->image_backing_file
);
3096 g_free(s
->image_backing_format
);
3098 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
3099 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
3101 return qcow2_update_header(bs
);
3104 static int qcow2_set_up_encryption(BlockDriverState
*bs
,
3105 QCryptoBlockCreateOptions
*cryptoopts
,
3108 BDRVQcow2State
*s
= bs
->opaque
;
3109 QCryptoBlock
*crypto
= NULL
;
3112 switch (cryptoopts
->format
) {
3113 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
3114 fmt
= QCOW_CRYPT_LUKS
;
3116 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
3117 fmt
= QCOW_CRYPT_AES
;
3120 error_setg(errp
, "Crypto format not supported in qcow2");
3124 s
->crypt_method_header
= fmt
;
3126 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
3127 qcow2_crypto_hdr_init_func
,
3128 qcow2_crypto_hdr_write_func
,
3134 ret
= qcow2_update_header(bs
);
3136 error_setg_errno(errp
, -ret
, "Could not write encryption header");
3142 qcrypto_block_free(crypto
);
3147 * Preallocates metadata structures for data clusters between @offset (in the
3148 * guest disk) and @new_length (which is thus generally the new guest disk
3151 * Returns: 0 on success, -errno on failure.
3153 static int coroutine_fn
preallocate_co(BlockDriverState
*bs
, uint64_t offset
,
3154 uint64_t new_length
, PreallocMode mode
,
3157 BDRVQcow2State
*s
= bs
->opaque
;
3159 uint64_t host_offset
= 0;
3160 int64_t file_length
;
3161 unsigned int cur_bytes
;
3163 QCowL2Meta
*meta
= NULL
, *m
;
3165 assert(offset
<= new_length
);
3166 bytes
= new_length
- offset
;
3169 cur_bytes
= MIN(bytes
, QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
));
3170 ret
= qcow2_alloc_host_offset(bs
, offset
, &cur_bytes
,
3171 &host_offset
, &meta
);
3173 error_setg_errno(errp
, -ret
, "Allocating clusters failed");
3177 for (m
= meta
; m
!= NULL
; m
= m
->next
) {
3181 ret
= qcow2_handle_l2meta(bs
, &meta
, true);
3183 error_setg_errno(errp
, -ret
, "Mapping clusters failed");
3187 /* TODO Preallocate data if requested */
3190 offset
+= cur_bytes
;
3194 * It is expected that the image file is large enough to actually contain
3195 * all of the allocated clusters (otherwise we get failing reads after
3196 * EOF). Extend the image to the last allocated sector.
3198 file_length
= bdrv_getlength(s
->data_file
->bs
);
3199 if (file_length
< 0) {
3200 error_setg_errno(errp
, -file_length
, "Could not get file size");
3205 if (host_offset
+ cur_bytes
> file_length
) {
3206 if (mode
== PREALLOC_MODE_METADATA
) {
3207 mode
= PREALLOC_MODE_OFF
;
3209 ret
= bdrv_co_truncate(s
->data_file
, host_offset
+ cur_bytes
, false,
3219 qcow2_handle_l2meta(bs
, &meta
, false);
3223 /* qcow2_refcount_metadata_size:
3224 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3225 * @cluster_size: size of a cluster, in bytes
3226 * @refcount_order: refcount bits power-of-2 exponent
3227 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3230 * Returns: Number of bytes required for refcount blocks and table metadata.
3232 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
3233 int refcount_order
, bool generous_increase
,
3234 uint64_t *refblock_count
)
3237 * Every host cluster is reference-counted, including metadata (even
3238 * refcount metadata is recursively included).
3240 * An accurate formula for the size of refcount metadata size is difficult
3241 * to derive. An easier method of calculation is finding the fixed point
3242 * where no further refcount blocks or table clusters are required to
3243 * reference count every cluster.
3245 int64_t blocks_per_table_cluster
= cluster_size
/ REFTABLE_ENTRY_SIZE
;
3246 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
3247 int64_t table
= 0; /* number of refcount table clusters */
3248 int64_t blocks
= 0; /* number of refcount block clusters */
3254 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
3255 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
3256 n
= clusters
+ blocks
+ table
;
3258 if (n
== last
&& generous_increase
) {
3259 clusters
+= DIV_ROUND_UP(table
, 2);
3260 n
= 0; /* force another loop */
3261 generous_increase
= false;
3263 } while (n
!= last
);
3265 if (refblock_count
) {
3266 *refblock_count
= blocks
;
3269 return (blocks
+ table
) * cluster_size
;
3273 * qcow2_calc_prealloc_size:
3274 * @total_size: virtual disk size in bytes
3275 * @cluster_size: cluster size in bytes
3276 * @refcount_order: refcount bits power-of-2 exponent
3277 * @extended_l2: true if the image has extended L2 entries
3279 * Returns: Total number of bytes required for the fully allocated image
3280 * (including metadata).
3282 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
3283 size_t cluster_size
,
3287 int64_t meta_size
= 0;
3288 uint64_t nl1e
, nl2e
;
3289 int64_t aligned_total_size
= ROUND_UP(total_size
, cluster_size
);
3290 size_t l2e_size
= extended_l2
? L2E_SIZE_EXTENDED
: L2E_SIZE_NORMAL
;
3292 /* header: 1 cluster */
3293 meta_size
+= cluster_size
;
3295 /* total size of L2 tables */
3296 nl2e
= aligned_total_size
/ cluster_size
;
3297 nl2e
= ROUND_UP(nl2e
, cluster_size
/ l2e_size
);
3298 meta_size
+= nl2e
* l2e_size
;
3300 /* total size of L1 tables */
3301 nl1e
= nl2e
* l2e_size
/ cluster_size
;
3302 nl1e
= ROUND_UP(nl1e
, cluster_size
/ L1E_SIZE
);
3303 meta_size
+= nl1e
* L1E_SIZE
;
3305 /* total size of refcount table and blocks */
3306 meta_size
+= qcow2_refcount_metadata_size(
3307 (meta_size
+ aligned_total_size
) / cluster_size
,
3308 cluster_size
, refcount_order
, false, NULL
);
3310 return meta_size
+ aligned_total_size
;
3313 static bool validate_cluster_size(size_t cluster_size
, bool extended_l2
,
3316 int cluster_bits
= ctz32(cluster_size
);
3317 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
3318 (1 << cluster_bits
) != cluster_size
)
3320 error_setg(errp
, "Cluster size must be a power of two between %d and "
3321 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
3326 unsigned min_cluster_size
=
3327 (1 << MIN_CLUSTER_BITS
) * QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER
;
3328 if (cluster_size
< min_cluster_size
) {
3329 error_setg(errp
, "Extended L2 entries are only supported with "
3330 "cluster sizes of at least %u bytes", min_cluster_size
);
3338 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, bool extended_l2
,
3341 size_t cluster_size
;
3343 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
3344 DEFAULT_CLUSTER_SIZE
);
3345 if (!validate_cluster_size(cluster_size
, extended_l2
, errp
)) {
3348 return cluster_size
;
3351 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
3356 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
3358 ret
= 3; /* default */
3359 } else if (!strcmp(buf
, "0.10")) {
3361 } else if (!strcmp(buf
, "1.1")) {
3364 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
3371 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
3374 uint64_t refcount_bits
;
3376 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
3377 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
3378 error_setg(errp
, "Refcount width must be a power of two and may not "
3383 if (version
< 3 && refcount_bits
!= 16) {
3384 error_setg(errp
, "Different refcount widths than 16 bits require "
3385 "compatibility level 1.1 or above (use compat=1.1 or "
3390 return refcount_bits
;
3393 static int coroutine_fn
3394 qcow2_co_create(BlockdevCreateOptions
*create_options
, Error
**errp
)
3396 BlockdevCreateOptionsQcow2
*qcow2_opts
;
3400 * Open the image file and write a minimal qcow2 header.
3402 * We keep things simple and start with a zero-sized image. We also
3403 * do without refcount blocks or a L1 table for now. We'll fix the
3404 * inconsistency later.
3406 * We do need a refcount table because growing the refcount table means
3407 * allocating two new refcount blocks - the second of which would be at
3408 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3409 * size for any qcow2 image.
3411 BlockBackend
*blk
= NULL
;
3412 BlockDriverState
*bs
= NULL
;
3413 BlockDriverState
*data_bs
= NULL
;
3415 size_t cluster_size
;
3418 uint64_t *refcount_table
;
3420 uint8_t compression_type
= QCOW2_COMPRESSION_TYPE_ZLIB
;
3422 assert(create_options
->driver
== BLOCKDEV_DRIVER_QCOW2
);
3423 qcow2_opts
= &create_options
->u
.qcow2
;
3425 bs
= bdrv_open_blockdev_ref(qcow2_opts
->file
, errp
);
3430 /* Validate options and set default values */
3431 if (!QEMU_IS_ALIGNED(qcow2_opts
->size
, BDRV_SECTOR_SIZE
)) {
3432 error_setg(errp
, "Image size must be a multiple of %u bytes",
3433 (unsigned) BDRV_SECTOR_SIZE
);
3438 if (qcow2_opts
->has_version
) {
3439 switch (qcow2_opts
->version
) {
3440 case BLOCKDEV_QCOW2_VERSION_V2
:
3443 case BLOCKDEV_QCOW2_VERSION_V3
:
3447 g_assert_not_reached();
3453 if (qcow2_opts
->has_cluster_size
) {
3454 cluster_size
= qcow2_opts
->cluster_size
;
3456 cluster_size
= DEFAULT_CLUSTER_SIZE
;
3459 if (!qcow2_opts
->has_extended_l2
) {
3460 qcow2_opts
->extended_l2
= false;
3462 if (qcow2_opts
->extended_l2
) {
3464 error_setg(errp
, "Extended L2 entries are only supported with "
3465 "compatibility level 1.1 and above (use version=v3 or "
3472 if (!validate_cluster_size(cluster_size
, qcow2_opts
->extended_l2
, errp
)) {
3477 if (!qcow2_opts
->has_preallocation
) {
3478 qcow2_opts
->preallocation
= PREALLOC_MODE_OFF
;
3480 if (qcow2_opts
->has_backing_file
&&
3481 qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
&&
3482 !qcow2_opts
->extended_l2
)
3484 error_setg(errp
, "Backing file and preallocation can only be used at "
3485 "the same time if extended_l2 is on");
3489 if (qcow2_opts
->has_backing_fmt
&& !qcow2_opts
->has_backing_file
) {
3490 error_setg(errp
, "Backing format cannot be used without backing file");
3495 if (!qcow2_opts
->has_lazy_refcounts
) {
3496 qcow2_opts
->lazy_refcounts
= false;
3498 if (version
< 3 && qcow2_opts
->lazy_refcounts
) {
3499 error_setg(errp
, "Lazy refcounts only supported with compatibility "
3500 "level 1.1 and above (use version=v3 or greater)");
3505 if (!qcow2_opts
->has_refcount_bits
) {
3506 qcow2_opts
->refcount_bits
= 16;
3508 if (qcow2_opts
->refcount_bits
> 64 ||
3509 !is_power_of_2(qcow2_opts
->refcount_bits
))
3511 error_setg(errp
, "Refcount width must be a power of two and may not "
3516 if (version
< 3 && qcow2_opts
->refcount_bits
!= 16) {
3517 error_setg(errp
, "Different refcount widths than 16 bits require "
3518 "compatibility level 1.1 or above (use version=v3 or "
3523 refcount_order
= ctz32(qcow2_opts
->refcount_bits
);
3525 if (qcow2_opts
->data_file_raw
&& !qcow2_opts
->data_file
) {
3526 error_setg(errp
, "data-file-raw requires data-file");
3530 if (qcow2_opts
->data_file_raw
&& qcow2_opts
->has_backing_file
) {
3531 error_setg(errp
, "Backing file and data-file-raw cannot be used at "
3536 if (qcow2_opts
->data_file_raw
&&
3537 qcow2_opts
->preallocation
== PREALLOC_MODE_OFF
)
3540 * data-file-raw means that "the external data file can be
3541 * read as a consistent standalone raw image without looking
3542 * at the qcow2 metadata." It does not say that the metadata
3543 * must be ignored, though (and the qcow2 driver in fact does
3544 * not ignore it), so the L1/L2 tables must be present and
3545 * give a 1:1 mapping, so you get the same result regardless
3546 * of whether you look at the metadata or whether you ignore
3549 qcow2_opts
->preallocation
= PREALLOC_MODE_METADATA
;
3552 * Cannot use preallocation with backing files, but giving a
3553 * backing file when specifying data_file_raw is an error
3556 assert(!qcow2_opts
->has_backing_file
);
3559 if (qcow2_opts
->data_file
) {
3561 error_setg(errp
, "External data files are only supported with "
3562 "compatibility level 1.1 and above (use version=v3 or "
3567 data_bs
= bdrv_open_blockdev_ref(qcow2_opts
->data_file
, errp
);
3568 if (data_bs
== NULL
) {
3574 if (qcow2_opts
->has_compression_type
&&
3575 qcow2_opts
->compression_type
!= QCOW2_COMPRESSION_TYPE_ZLIB
) {
3580 error_setg(errp
, "Non-zlib compression type is only supported with "
3581 "compatibility level 1.1 and above (use version=v3 or "
3586 switch (qcow2_opts
->compression_type
) {
3588 case QCOW2_COMPRESSION_TYPE_ZSTD
:
3592 error_setg(errp
, "Unknown compression type");
3596 compression_type
= qcow2_opts
->compression_type
;
3599 /* Create BlockBackend to write to the image */
3600 blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
| BLK_PERM_RESIZE
, BLK_PERM_ALL
,
3606 blk_set_allow_write_beyond_eof(blk
, true);
3608 /* Write the header */
3609 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
3610 header
= g_malloc0(cluster_size
);
3611 *header
= (QCowHeader
) {
3612 .magic
= cpu_to_be32(QCOW_MAGIC
),
3613 .version
= cpu_to_be32(version
),
3614 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
3615 .size
= cpu_to_be64(0),
3616 .l1_table_offset
= cpu_to_be64(0),
3617 .l1_size
= cpu_to_be32(0),
3618 .refcount_table_offset
= cpu_to_be64(cluster_size
),
3619 .refcount_table_clusters
= cpu_to_be32(1),
3620 .refcount_order
= cpu_to_be32(refcount_order
),
3621 /* don't deal with endianness since compression_type is 1 byte long */
3622 .compression_type
= compression_type
,
3623 .header_length
= cpu_to_be32(sizeof(*header
)),
3626 /* We'll update this to correct value later */
3627 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
3629 if (qcow2_opts
->lazy_refcounts
) {
3630 header
->compatible_features
|=
3631 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
3634 header
->incompatible_features
|=
3635 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE
);
3637 if (qcow2_opts
->data_file_raw
) {
3638 header
->autoclear_features
|=
3639 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW
);
3641 if (compression_type
!= QCOW2_COMPRESSION_TYPE_ZLIB
) {
3642 header
->incompatible_features
|=
3643 cpu_to_be64(QCOW2_INCOMPAT_COMPRESSION
);
3646 if (qcow2_opts
->extended_l2
) {
3647 header
->incompatible_features
|=
3648 cpu_to_be64(QCOW2_INCOMPAT_EXTL2
);
3651 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
3654 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
3658 /* Write a refcount table with one refcount block */
3659 refcount_table
= g_malloc0(2 * cluster_size
);
3660 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
3661 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
3662 g_free(refcount_table
);
3665 error_setg_errno(errp
, -ret
, "Could not write refcount table");
3673 * And now open the image and make it consistent first (i.e. increase the
3674 * refcount of the cluster that is occupied by the header and the refcount
3677 options
= qdict_new();
3678 qdict_put_str(options
, "driver", "qcow2");
3679 qdict_put_str(options
, "file", bs
->node_name
);
3681 qdict_put_str(options
, "data-file", data_bs
->node_name
);
3683 blk
= blk_new_open(NULL
, NULL
, options
,
3684 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
3691 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
3693 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
3694 "header and refcount table");
3697 } else if (ret
!= 0) {
3698 error_report("Huh, first cluster in empty image is already in use?");
3702 /* Set the external data file if necessary */
3704 BDRVQcow2State
*s
= blk_bs(blk
)->opaque
;
3705 s
->image_data_file
= g_strdup(data_bs
->filename
);
3708 /* Create a full header (including things like feature table) */
3709 ret
= qcow2_update_header(blk_bs(blk
));
3711 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
3715 /* Okay, now that we have a valid image, let's give it the right size */
3716 ret
= blk_truncate(blk
, qcow2_opts
->size
, false, qcow2_opts
->preallocation
,
3719 error_prepend(errp
, "Could not resize image: ");
3723 /* Want a backing file? There you go. */
3724 if (qcow2_opts
->has_backing_file
) {
3725 const char *backing_format
= NULL
;
3727 if (qcow2_opts
->has_backing_fmt
) {
3728 backing_format
= BlockdevDriver_str(qcow2_opts
->backing_fmt
);
3731 ret
= bdrv_change_backing_file(blk_bs(blk
), qcow2_opts
->backing_file
,
3732 backing_format
, false);
3734 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
3735 "with format '%s'", qcow2_opts
->backing_file
,
3741 /* Want encryption? There you go. */
3742 if (qcow2_opts
->has_encrypt
) {
3743 ret
= qcow2_set_up_encryption(blk_bs(blk
), qcow2_opts
->encrypt
, errp
);
3752 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3753 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3754 * have to setup decryption context. We're not doing any I/O on the top
3755 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3758 options
= qdict_new();
3759 qdict_put_str(options
, "driver", "qcow2");
3760 qdict_put_str(options
, "file", bs
->node_name
);
3762 qdict_put_str(options
, "data-file", data_bs
->node_name
);
3764 blk
= blk_new_open(NULL
, NULL
, options
,
3765 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
3776 bdrv_unref(data_bs
);
3780 static int coroutine_fn
qcow2_co_create_opts(BlockDriver
*drv
,
3781 const char *filename
,
3785 BlockdevCreateOptions
*create_options
= NULL
;
3788 BlockDriverState
*bs
= NULL
;
3789 BlockDriverState
*data_bs
= NULL
;
3793 /* Only the keyval visitor supports the dotted syntax needed for
3794 * encryption, so go through a QDict before getting a QAPI type. Ignore
3795 * options meant for the protocol layer so that the visitor doesn't
3797 qdict
= qemu_opts_to_qdict_filtered(opts
, NULL
, bdrv_qcow2
.create_opts
,
3800 /* Handle encryption options */
3801 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT
);
3802 if (val
&& !strcmp(val
, "on")) {
3803 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT
, "qcow");
3804 } else if (val
&& !strcmp(val
, "off")) {
3805 qdict_del(qdict
, BLOCK_OPT_ENCRYPT
);
3808 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
);
3809 if (val
&& !strcmp(val
, "aes")) {
3810 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
, "qcow");
3813 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3814 * version=v2/v3 below. */
3815 val
= qdict_get_try_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
);
3816 if (val
&& !strcmp(val
, "0.10")) {
3817 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v2");
3818 } else if (val
&& !strcmp(val
, "1.1")) {
3819 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v3");
3822 /* Change legacy command line options into QMP ones */
3823 static const QDictRenames opt_renames
[] = {
3824 { BLOCK_OPT_BACKING_FILE
, "backing-file" },
3825 { BLOCK_OPT_BACKING_FMT
, "backing-fmt" },
3826 { BLOCK_OPT_CLUSTER_SIZE
, "cluster-size" },
3827 { BLOCK_OPT_LAZY_REFCOUNTS
, "lazy-refcounts" },
3828 { BLOCK_OPT_EXTL2
, "extended-l2" },
3829 { BLOCK_OPT_REFCOUNT_BITS
, "refcount-bits" },
3830 { BLOCK_OPT_ENCRYPT
, BLOCK_OPT_ENCRYPT_FORMAT
},
3831 { BLOCK_OPT_COMPAT_LEVEL
, "version" },
3832 { BLOCK_OPT_DATA_FILE_RAW
, "data-file-raw" },
3833 { BLOCK_OPT_COMPRESSION_TYPE
, "compression-type" },
3837 if (!qdict_rename_keys(qdict
, opt_renames
, errp
)) {
3842 /* Create and open the file (protocol layer) */
3843 ret
= bdrv_create_file(filename
, opts
, errp
);
3848 bs
= bdrv_open(filename
, NULL
, NULL
,
3849 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
, errp
);
3855 /* Create and open an external data file (protocol layer) */
3856 val
= qdict_get_try_str(qdict
, BLOCK_OPT_DATA_FILE
);
3858 ret
= bdrv_create_file(val
, opts
, errp
);
3863 data_bs
= bdrv_open(val
, NULL
, NULL
,
3864 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
3866 if (data_bs
== NULL
) {
3871 qdict_del(qdict
, BLOCK_OPT_DATA_FILE
);
3872 qdict_put_str(qdict
, "data-file", data_bs
->node_name
);
3875 /* Set 'driver' and 'node' options */
3876 qdict_put_str(qdict
, "driver", "qcow2");
3877 qdict_put_str(qdict
, "file", bs
->node_name
);
3879 /* Now get the QAPI type BlockdevCreateOptions */
3880 v
= qobject_input_visitor_new_flat_confused(qdict
, errp
);
3886 visit_type_BlockdevCreateOptions(v
, NULL
, &create_options
, errp
);
3888 if (!create_options
) {
3893 /* Silently round up size */
3894 create_options
->u
.qcow2
.size
= ROUND_UP(create_options
->u
.qcow2
.size
,
3897 /* Create the qcow2 image (format layer) */
3898 ret
= qcow2_co_create(create_options
, errp
);
3901 bdrv_co_delete_file_noerr(bs
);
3902 bdrv_co_delete_file_noerr(data_bs
);
3907 qobject_unref(qdict
);
3909 bdrv_unref(data_bs
);
3910 qapi_free_BlockdevCreateOptions(create_options
);
3915 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3920 /* Clamp to image length, before checking status of underlying sectors */
3921 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3922 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3930 * bdrv_block_status_above doesn't merge different types of zeros, for
3931 * example, zeros which come from the region which is unallocated in
3932 * the whole backing chain, and zeros which come because of a short
3933 * backing file. So, we need a loop.
3936 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3939 } while (res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
&& bytes
);
3941 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && bytes
== 0;
3944 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3945 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
)
3948 BDRVQcow2State
*s
= bs
->opaque
;
3950 uint32_t head
= offset_into_subcluster(s
, offset
);
3951 uint32_t tail
= ROUND_UP(offset
+ bytes
, s
->subcluster_size
) -
3954 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3955 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3962 QCow2SubclusterType type
;
3964 assert(head
+ bytes
+ tail
<= s
->subcluster_size
);
3966 /* check whether remainder of cluster already reads as zero */
3967 if (!(is_zero(bs
, offset
- head
, head
) &&
3968 is_zero(bs
, offset
+ bytes
, tail
))) {
3972 qemu_co_mutex_lock(&s
->lock
);
3973 /* We can have new write after previous check */
3975 bytes
= s
->subcluster_size
;
3976 nr
= s
->subcluster_size
;
3977 ret
= qcow2_get_host_offset(bs
, offset
, &nr
, &off
, &type
);
3979 (type
!= QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN
&&
3980 type
!= QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC
&&
3981 type
!= QCOW2_SUBCLUSTER_ZERO_PLAIN
&&
3982 type
!= QCOW2_SUBCLUSTER_ZERO_ALLOC
)) {
3983 qemu_co_mutex_unlock(&s
->lock
);
3984 return ret
< 0 ? ret
: -ENOTSUP
;
3987 qemu_co_mutex_lock(&s
->lock
);
3990 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3992 /* Whatever is left can use real zero subclusters */
3993 ret
= qcow2_subcluster_zeroize(bs
, offset
, bytes
, flags
);
3994 qemu_co_mutex_unlock(&s
->lock
);
3999 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
4000 int64_t offset
, int64_t bytes
)
4003 BDRVQcow2State
*s
= bs
->opaque
;
4005 /* If the image does not support QCOW_OFLAG_ZERO then discarding
4006 * clusters could expose stale data from the backing file. */
4007 if (s
->qcow_version
< 3 && bs
->backing
) {
4011 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
4012 assert(bytes
< s
->cluster_size
);
4013 /* Ignore partial clusters, except for the special case of the
4014 * complete partial cluster at the end of an unaligned file */
4015 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
4016 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
4021 qemu_co_mutex_lock(&s
->lock
);
4022 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
4024 qemu_co_mutex_unlock(&s
->lock
);
4028 static int coroutine_fn
4029 qcow2_co_copy_range_from(BlockDriverState
*bs
,
4030 BdrvChild
*src
, int64_t src_offset
,
4031 BdrvChild
*dst
, int64_t dst_offset
,
4032 int64_t bytes
, BdrvRequestFlags read_flags
,
4033 BdrvRequestFlags write_flags
)
4035 BDRVQcow2State
*s
= bs
->opaque
;
4037 unsigned int cur_bytes
; /* number of bytes in current iteration */
4038 BdrvChild
*child
= NULL
;
4039 BdrvRequestFlags cur_write_flags
;
4041 assert(!bs
->encrypted
);
4042 qemu_co_mutex_lock(&s
->lock
);
4044 while (bytes
!= 0) {
4045 uint64_t copy_offset
= 0;
4046 QCow2SubclusterType type
;
4047 /* prepare next request */
4048 cur_bytes
= MIN(bytes
, INT_MAX
);
4049 cur_write_flags
= write_flags
;
4051 ret
= qcow2_get_host_offset(bs
, src_offset
, &cur_bytes
,
4052 ©_offset
, &type
);
4058 case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN
:
4059 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC
:
4060 if (bs
->backing
&& bs
->backing
->bs
) {
4061 int64_t backing_length
= bdrv_getlength(bs
->backing
->bs
);
4062 if (src_offset
>= backing_length
) {
4063 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
4065 child
= bs
->backing
;
4066 cur_bytes
= MIN(cur_bytes
, backing_length
- src_offset
);
4067 copy_offset
= src_offset
;
4070 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
4074 case QCOW2_SUBCLUSTER_ZERO_PLAIN
:
4075 case QCOW2_SUBCLUSTER_ZERO_ALLOC
:
4076 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
4079 case QCOW2_SUBCLUSTER_COMPRESSED
:
4083 case QCOW2_SUBCLUSTER_NORMAL
:
4084 child
= s
->data_file
;
4090 qemu_co_mutex_unlock(&s
->lock
);
4091 ret
= bdrv_co_copy_range_from(child
,
4094 cur_bytes
, read_flags
, cur_write_flags
);
4095 qemu_co_mutex_lock(&s
->lock
);
4101 src_offset
+= cur_bytes
;
4102 dst_offset
+= cur_bytes
;
4107 qemu_co_mutex_unlock(&s
->lock
);
4111 static int coroutine_fn
4112 qcow2_co_copy_range_to(BlockDriverState
*bs
,
4113 BdrvChild
*src
, int64_t src_offset
,
4114 BdrvChild
*dst
, int64_t dst_offset
,
4115 int64_t bytes
, BdrvRequestFlags read_flags
,
4116 BdrvRequestFlags write_flags
)
4118 BDRVQcow2State
*s
= bs
->opaque
;
4120 unsigned int cur_bytes
; /* number of sectors in current iteration */
4121 uint64_t host_offset
;
4122 QCowL2Meta
*l2meta
= NULL
;
4124 assert(!bs
->encrypted
);
4126 qemu_co_mutex_lock(&s
->lock
);
4128 while (bytes
!= 0) {
4132 cur_bytes
= MIN(bytes
, INT_MAX
);
4135 * If src->bs == dst->bs, we could simply copy by incrementing
4136 * the refcnt, without copying user data.
4137 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
4138 ret
= qcow2_alloc_host_offset(bs
, dst_offset
, &cur_bytes
,
4139 &host_offset
, &l2meta
);
4144 ret
= qcow2_pre_write_overlap_check(bs
, 0, host_offset
, cur_bytes
,
4150 qemu_co_mutex_unlock(&s
->lock
);
4151 ret
= bdrv_co_copy_range_to(src
, src_offset
, s
->data_file
, host_offset
,
4152 cur_bytes
, read_flags
, write_flags
);
4153 qemu_co_mutex_lock(&s
->lock
);
4158 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
4164 src_offset
+= cur_bytes
;
4165 dst_offset
+= cur_bytes
;
4170 qcow2_handle_l2meta(bs
, &l2meta
, false);
4172 qemu_co_mutex_unlock(&s
->lock
);
4174 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
4179 static int coroutine_fn
qcow2_co_truncate(BlockDriverState
*bs
, int64_t offset
,
4180 bool exact
, PreallocMode prealloc
,
4181 BdrvRequestFlags flags
, Error
**errp
)
4183 BDRVQcow2State
*s
= bs
->opaque
;
4184 uint64_t old_length
;
4185 int64_t new_l1_size
;
4189 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
4190 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
4192 error_setg(errp
, "Unsupported preallocation mode '%s'",
4193 PreallocMode_str(prealloc
));
4197 if (!QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
)) {
4198 error_setg(errp
, "The new size must be a multiple of %u",
4199 (unsigned) BDRV_SECTOR_SIZE
);
4203 qemu_co_mutex_lock(&s
->lock
);
4206 * Even though we store snapshot size for all images, it was not
4207 * required until v3, so it is not safe to proceed for v2.
4209 if (s
->nb_snapshots
&& s
->qcow_version
< 3) {
4210 error_setg(errp
, "Can't resize a v2 image which has snapshots");
4215 /* See qcow2-bitmap.c for which bitmap scenarios prevent a resize. */
4216 if (qcow2_truncate_bitmaps_check(bs
, errp
)) {
4221 old_length
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
4222 new_l1_size
= size_to_l1(s
, offset
);
4224 if (offset
< old_length
) {
4225 int64_t last_cluster
, old_file_size
;
4226 if (prealloc
!= PREALLOC_MODE_OFF
) {
4228 "Preallocation can't be used for shrinking an image");
4233 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
4234 old_length
- ROUND_UP(offset
,
4236 QCOW2_DISCARD_ALWAYS
, true);
4238 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
4242 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
4244 error_setg_errno(errp
, -ret
,
4245 "Failed to reduce the number of L2 tables");
4249 ret
= qcow2_shrink_reftable(bs
);
4251 error_setg_errno(errp
, -ret
,
4252 "Failed to discard unused refblocks");
4256 old_file_size
= bdrv_getlength(bs
->file
->bs
);
4257 if (old_file_size
< 0) {
4258 error_setg_errno(errp
, -old_file_size
,
4259 "Failed to inquire current file length");
4260 ret
= old_file_size
;
4263 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
4264 if (last_cluster
< 0) {
4265 error_setg_errno(errp
, -last_cluster
,
4266 "Failed to find the last cluster");
4270 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
4271 Error
*local_err
= NULL
;
4274 * Do not pass @exact here: It will not help the user if
4275 * we get an error here just because they wanted to shrink
4276 * their qcow2 image (on a block device) with qemu-img.
4277 * (And on the qcow2 layer, the @exact requirement is
4278 * always fulfilled, so there is no need to pass it on.)
4280 bdrv_co_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
4281 false, PREALLOC_MODE_OFF
, 0, &local_err
);
4283 warn_reportf_err(local_err
,
4284 "Failed to truncate the tail of the image: ");
4288 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
4290 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
4294 if (data_file_is_raw(bs
) && prealloc
== PREALLOC_MODE_OFF
) {
4296 * When creating a qcow2 image with data-file-raw, we enforce
4297 * at least prealloc=metadata, so that the L1/L2 tables are
4298 * fully allocated and reading from the data file will return
4299 * the same data as reading from the qcow2 image. When the
4300 * image is grown, we must consequently preallocate the
4301 * metadata structures to cover the added area.
4303 prealloc
= PREALLOC_MODE_METADATA
;
4308 case PREALLOC_MODE_OFF
:
4309 if (has_data_file(bs
)) {
4311 * If the caller wants an exact resize, the external data
4312 * file should be resized to the exact target size, too,
4313 * so we pass @exact here.
4315 ret
= bdrv_co_truncate(s
->data_file
, offset
, exact
, prealloc
, 0,
4323 case PREALLOC_MODE_METADATA
:
4324 ret
= preallocate_co(bs
, old_length
, offset
, prealloc
, errp
);
4330 case PREALLOC_MODE_FALLOC
:
4331 case PREALLOC_MODE_FULL
:
4333 int64_t allocation_start
, host_offset
, guest_offset
;
4334 int64_t clusters_allocated
;
4335 int64_t old_file_size
, last_cluster
, new_file_size
;
4336 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
4337 bool subclusters_need_allocation
= false;
4339 /* With a data file, preallocation means just allocating the metadata
4340 * and forwarding the truncate request to the data file */
4341 if (has_data_file(bs
)) {
4342 ret
= preallocate_co(bs
, old_length
, offset
, prealloc
, errp
);
4349 old_file_size
= bdrv_getlength(bs
->file
->bs
);
4350 if (old_file_size
< 0) {
4351 error_setg_errno(errp
, -old_file_size
,
4352 "Failed to inquire current file length");
4353 ret
= old_file_size
;
4357 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
4358 if (last_cluster
>= 0) {
4359 old_file_size
= (last_cluster
+ 1) * s
->cluster_size
;
4361 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
4364 nb_new_data_clusters
= (ROUND_UP(offset
, s
->cluster_size
) -
4365 start_of_cluster(s
, old_length
)) >> s
->cluster_bits
;
4367 /* This is an overestimation; we will not actually allocate space for
4368 * these in the file but just make sure the new refcount structures are
4369 * able to cover them so we will not have to allocate new refblocks
4370 * while entering the data blocks in the potentially new L2 tables.
4371 * (We do not actually care where the L2 tables are placed. Maybe they
4372 * are already allocated or they can be placed somewhere before
4373 * @old_file_size. It does not matter because they will be fully
4374 * allocated automatically, so they do not need to be covered by the
4375 * preallocation. All that matters is that we will not have to allocate
4376 * new refcount structures for them.) */
4377 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
4378 s
->cluster_size
/ l2_entry_size(s
));
4379 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4380 * table for a potential head/tail */
4383 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
4384 nb_new_data_clusters
+
4387 if (allocation_start
< 0) {
4388 error_setg_errno(errp
, -allocation_start
,
4389 "Failed to resize refcount structures");
4390 ret
= allocation_start
;
4394 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
4395 nb_new_data_clusters
);
4396 if (clusters_allocated
< 0) {
4397 error_setg_errno(errp
, -clusters_allocated
,
4398 "Failed to allocate data clusters");
4399 ret
= clusters_allocated
;
4403 assert(clusters_allocated
== nb_new_data_clusters
);
4405 /* Allocate the data area */
4406 new_file_size
= allocation_start
+
4407 nb_new_data_clusters
* s
->cluster_size
;
4409 * Image file grows, so @exact does not matter.
4411 * If we need to zero out the new area, try first whether the protocol
4412 * driver can already take care of this.
4414 if (flags
& BDRV_REQ_ZERO_WRITE
) {
4415 ret
= bdrv_co_truncate(bs
->file
, new_file_size
, false, prealloc
,
4416 BDRV_REQ_ZERO_WRITE
, NULL
);
4418 flags
&= ~BDRV_REQ_ZERO_WRITE
;
4419 /* Ensure that we read zeroes and not backing file data */
4420 subclusters_need_allocation
= true;
4426 ret
= bdrv_co_truncate(bs
->file
, new_file_size
, false, prealloc
, 0,
4430 error_prepend(errp
, "Failed to resize underlying file: ");
4431 qcow2_free_clusters(bs
, allocation_start
,
4432 nb_new_data_clusters
* s
->cluster_size
,
4433 QCOW2_DISCARD_OTHER
);
4437 /* Create the necessary L2 entries */
4438 host_offset
= allocation_start
;
4439 guest_offset
= old_length
;
4440 while (nb_new_data_clusters
) {
4441 int64_t nb_clusters
= MIN(
4442 nb_new_data_clusters
,
4443 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
4444 unsigned cow_start_length
= offset_into_cluster(s
, guest_offset
);
4445 QCowL2Meta allocation
;
4446 guest_offset
= start_of_cluster(s
, guest_offset
);
4447 allocation
= (QCowL2Meta
) {
4448 .offset
= guest_offset
,
4449 .alloc_offset
= host_offset
,
4450 .nb_clusters
= nb_clusters
,
4453 .nb_bytes
= cow_start_length
,
4456 .offset
= nb_clusters
<< s
->cluster_bits
,
4459 .prealloc
= !subclusters_need_allocation
,
4461 qemu_co_queue_init(&allocation
.dependent_requests
);
4463 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
4465 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
4466 qcow2_free_clusters(bs
, host_offset
,
4467 nb_new_data_clusters
* s
->cluster_size
,
4468 QCOW2_DISCARD_OTHER
);
4472 guest_offset
+= nb_clusters
* s
->cluster_size
;
4473 host_offset
+= nb_clusters
* s
->cluster_size
;
4474 nb_new_data_clusters
-= nb_clusters
;
4480 g_assert_not_reached();
4483 if ((flags
& BDRV_REQ_ZERO_WRITE
) && offset
> old_length
) {
4484 uint64_t zero_start
= QEMU_ALIGN_UP(old_length
, s
->subcluster_size
);
4487 * Use zero clusters as much as we can. qcow2_subcluster_zeroize()
4488 * requires a subcluster-aligned start. The end may be unaligned if
4489 * it is at the end of the image (which it is here).
4491 if (offset
> zero_start
) {
4492 ret
= qcow2_subcluster_zeroize(bs
, zero_start
, offset
- zero_start
,
4495 error_setg_errno(errp
, -ret
, "Failed to zero out new clusters");
4500 /* Write explicit zeros for the unaligned head */
4501 if (zero_start
> old_length
) {
4502 uint64_t len
= MIN(zero_start
, offset
) - old_length
;
4503 uint8_t *buf
= qemu_blockalign0(bs
, len
);
4505 qemu_iovec_init_buf(&qiov
, buf
, len
);
4507 qemu_co_mutex_unlock(&s
->lock
);
4508 ret
= qcow2_co_pwritev_part(bs
, old_length
, len
, &qiov
, 0, 0);
4509 qemu_co_mutex_lock(&s
->lock
);
4513 error_setg_errno(errp
, -ret
, "Failed to zero out the new area");
4519 if (prealloc
!= PREALLOC_MODE_OFF
) {
4520 /* Flush metadata before actually changing the image size */
4521 ret
= qcow2_write_caches(bs
);
4523 error_setg_errno(errp
, -ret
,
4524 "Failed to flush the preallocated area to disk");
4529 bs
->total_sectors
= offset
/ BDRV_SECTOR_SIZE
;
4531 /* write updated header.size */
4532 offset
= cpu_to_be64(offset
);
4533 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
4534 &offset
, sizeof(offset
));
4536 error_setg_errno(errp
, -ret
, "Failed to update the image size");
4540 s
->l1_vm_state_index
= new_l1_size
;
4542 /* Update cache sizes */
4543 options
= qdict_clone_shallow(bs
->options
);
4544 ret
= qcow2_update_options(bs
, options
, s
->flags
, errp
);
4545 qobject_unref(options
);
4551 qemu_co_mutex_unlock(&s
->lock
);
4555 static coroutine_fn
int
4556 qcow2_co_pwritev_compressed_task(BlockDriverState
*bs
,
4557 uint64_t offset
, uint64_t bytes
,
4558 QEMUIOVector
*qiov
, size_t qiov_offset
)
4560 BDRVQcow2State
*s
= bs
->opaque
;
4563 uint8_t *buf
, *out_buf
;
4564 uint64_t cluster_offset
;
4566 assert(bytes
== s
->cluster_size
|| (bytes
< s
->cluster_size
&&
4567 (offset
+ bytes
== bs
->total_sectors
<< BDRV_SECTOR_BITS
)));
4569 buf
= qemu_blockalign(bs
, s
->cluster_size
);
4570 if (bytes
< s
->cluster_size
) {
4571 /* Zero-pad last write if image size is not cluster aligned */
4572 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
4574 qemu_iovec_to_buf(qiov
, qiov_offset
, buf
, bytes
);
4576 out_buf
= g_malloc(s
->cluster_size
);
4578 out_len
= qcow2_co_compress(bs
, out_buf
, s
->cluster_size
- 1,
4579 buf
, s
->cluster_size
);
4580 if (out_len
== -ENOMEM
) {
4581 /* could not compress: write normal cluster */
4582 ret
= qcow2_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
, 0);
4587 } else if (out_len
< 0) {
4592 qemu_co_mutex_lock(&s
->lock
);
4593 ret
= qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
,
4596 qemu_co_mutex_unlock(&s
->lock
);
4600 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
, true);
4601 qemu_co_mutex_unlock(&s
->lock
);
4606 BLKDBG_EVENT(s
->data_file
, BLKDBG_WRITE_COMPRESSED
);
4607 ret
= bdrv_co_pwrite(s
->data_file
, cluster_offset
, out_len
, out_buf
, 0);
4619 static coroutine_fn
int qcow2_co_pwritev_compressed_task_entry(AioTask
*task
)
4621 Qcow2AioTask
*t
= container_of(task
, Qcow2AioTask
, task
);
4623 assert(!t
->subcluster_type
&& !t
->l2meta
);
4625 return qcow2_co_pwritev_compressed_task(t
->bs
, t
->offset
, t
->bytes
, t
->qiov
,
4630 * XXX: put compressed sectors first, then all the cluster aligned
4631 * tables to avoid losing bytes in alignment
4633 static coroutine_fn
int
4634 qcow2_co_pwritev_compressed_part(BlockDriverState
*bs
,
4635 int64_t offset
, int64_t bytes
,
4636 QEMUIOVector
*qiov
, size_t qiov_offset
)
4638 BDRVQcow2State
*s
= bs
->opaque
;
4639 AioTaskPool
*aio
= NULL
;
4642 if (has_data_file(bs
)) {
4648 * align end of file to a sector boundary to ease reading with
4651 int64_t len
= bdrv_getlength(bs
->file
->bs
);
4655 return bdrv_co_truncate(bs
->file
, len
, false, PREALLOC_MODE_OFF
, 0,
4659 if (offset_into_cluster(s
, offset
)) {
4663 if (offset_into_cluster(s
, bytes
) &&
4664 (offset
+ bytes
) != (bs
->total_sectors
<< BDRV_SECTOR_BITS
)) {
4668 while (bytes
&& aio_task_pool_status(aio
) == 0) {
4669 uint64_t chunk_size
= MIN(bytes
, s
->cluster_size
);
4671 if (!aio
&& chunk_size
!= bytes
) {
4672 aio
= aio_task_pool_new(QCOW2_MAX_WORKERS
);
4675 ret
= qcow2_add_task(bs
, aio
, qcow2_co_pwritev_compressed_task_entry
,
4676 0, 0, offset
, chunk_size
, qiov
, qiov_offset
, NULL
);
4680 qiov_offset
+= chunk_size
;
4681 offset
+= chunk_size
;
4682 bytes
-= chunk_size
;
4686 aio_task_pool_wait_all(aio
);
4688 ret
= aio_task_pool_status(aio
);
4696 static int coroutine_fn
4697 qcow2_co_preadv_compressed(BlockDriverState
*bs
,
4704 BDRVQcow2State
*s
= bs
->opaque
;
4707 uint8_t *buf
, *out_buf
;
4708 int offset_in_cluster
= offset_into_cluster(s
, offset
);
4710 qcow2_parse_compressed_l2_entry(bs
, l2_entry
, &coffset
, &csize
);
4712 buf
= g_try_malloc(csize
);
4717 out_buf
= qemu_blockalign(bs
, s
->cluster_size
);
4719 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_COMPRESSED
);
4720 ret
= bdrv_co_pread(bs
->file
, coffset
, csize
, buf
, 0);
4725 if (qcow2_co_decompress(bs
, out_buf
, s
->cluster_size
, buf
, csize
) < 0) {
4730 qemu_iovec_from_buf(qiov
, qiov_offset
, out_buf
+ offset_in_cluster
, bytes
);
4733 qemu_vfree(out_buf
);
4739 static int make_completely_empty(BlockDriverState
*bs
)
4741 BDRVQcow2State
*s
= bs
->opaque
;
4742 Error
*local_err
= NULL
;
4743 int ret
, l1_clusters
;
4745 uint64_t *new_reftable
= NULL
;
4746 uint64_t rt_entry
, l1_size2
;
4749 uint64_t reftable_offset
;
4750 uint32_t reftable_clusters
;
4751 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
4753 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
4758 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
4763 /* Refcounts will be broken utterly */
4764 ret
= qcow2_mark_dirty(bs
);
4769 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
4771 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ L1E_SIZE
);
4772 l1_size2
= (uint64_t)s
->l1_size
* L1E_SIZE
;
4774 /* After this call, neither the in-memory nor the on-disk refcount
4775 * information accurately describe the actual references */
4777 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
4778 l1_clusters
* s
->cluster_size
, 0);
4780 goto fail_broken_refcounts
;
4782 memset(s
->l1_table
, 0, l1_size2
);
4784 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
4786 /* Overwrite enough clusters at the beginning of the sectors to place
4787 * the refcount table, a refcount block and the L1 table in; this may
4788 * overwrite parts of the existing refcount and L1 table, which is not
4789 * an issue because the dirty flag is set, complete data loss is in fact
4790 * desired and partial data loss is consequently fine as well */
4791 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
4792 (2 + l1_clusters
) * s
->cluster_size
, 0);
4793 /* This call (even if it failed overall) may have overwritten on-disk
4794 * refcount structures; in that case, the in-memory refcount information
4795 * will probably differ from the on-disk information which makes the BDS
4798 goto fail_broken_refcounts
;
4801 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
4802 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
4804 /* "Create" an empty reftable (one cluster) directly after the image
4805 * header and an empty L1 table three clusters after the image header;
4806 * the cluster between those two will be used as the first refblock */
4807 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
4808 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
4809 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
4810 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
4811 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
4813 goto fail_broken_refcounts
;
4816 s
->l1_table_offset
= 3 * s
->cluster_size
;
4818 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ REFTABLE_ENTRY_SIZE
);
4819 if (!new_reftable
) {
4821 goto fail_broken_refcounts
;
4824 s
->refcount_table_offset
= s
->cluster_size
;
4825 s
->refcount_table_size
= s
->cluster_size
/ REFTABLE_ENTRY_SIZE
;
4826 s
->max_refcount_table_index
= 0;
4828 g_free(s
->refcount_table
);
4829 s
->refcount_table
= new_reftable
;
4830 new_reftable
= NULL
;
4832 /* Now the in-memory refcount information again corresponds to the on-disk
4833 * information (reftable is empty and no refblocks (the refblock cache is
4834 * empty)); however, this means some clusters (e.g. the image header) are
4835 * referenced, but not refcounted, but the normal qcow2 code assumes that
4836 * the in-memory information is always correct */
4838 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
4840 /* Enter the first refblock into the reftable */
4841 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
4842 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
4843 &rt_entry
, sizeof(rt_entry
));
4845 goto fail_broken_refcounts
;
4847 s
->refcount_table
[0] = 2 * s
->cluster_size
;
4849 s
->free_cluster_index
= 0;
4850 assert(3 + l1_clusters
<= s
->refcount_block_size
);
4851 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
4854 goto fail_broken_refcounts
;
4855 } else if (offset
> 0) {
4856 error_report("First cluster in emptied image is in use");
4860 /* Now finally the in-memory information corresponds to the on-disk
4861 * structures and is correct */
4862 ret
= qcow2_mark_clean(bs
);
4867 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
, false,
4868 PREALLOC_MODE_OFF
, 0, &local_err
);
4870 error_report_err(local_err
);
4876 fail_broken_refcounts
:
4877 /* The BDS is unusable at this point. If we wanted to make it usable, we
4878 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4879 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4880 * again. However, because the functions which could have caused this error
4881 * path to be taken are used by those functions as well, it's very likely
4882 * that that sequence will fail as well. Therefore, just eject the BDS. */
4886 g_free(new_reftable
);
4890 static int qcow2_make_empty(BlockDriverState
*bs
)
4892 BDRVQcow2State
*s
= bs
->opaque
;
4893 uint64_t offset
, end_offset
;
4894 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
4895 int l1_clusters
, ret
= 0;
4897 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ L1E_SIZE
);
4899 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
4900 3 + l1_clusters
<= s
->refcount_block_size
&&
4901 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
&&
4902 !has_data_file(bs
)) {
4903 /* The following function only works for qcow2 v3 images (it
4904 * requires the dirty flag) and only as long as there are no
4905 * features that reserve extra clusters (such as snapshots,
4906 * LUKS header, or persistent bitmaps), because it completely
4907 * empties the image. Furthermore, the L1 table and three
4908 * additional clusters (image header, refcount table, one
4909 * refcount block) have to fit inside one refcount block. It
4910 * only resets the image file, i.e. does not work with an
4911 * external data file. */
4912 return make_completely_empty(bs
);
4915 /* This fallback code simply discards every active cluster; this is slow,
4916 * but works in all cases */
4917 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
4918 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
4919 /* As this function is generally used after committing an external
4920 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4921 * default action for this kind of discard is to pass the discard,
4922 * which will ideally result in an actually smaller image file, as
4923 * is probably desired. */
4924 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
4925 QCOW2_DISCARD_SNAPSHOT
, true);
4934 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
4936 BDRVQcow2State
*s
= bs
->opaque
;
4939 qemu_co_mutex_lock(&s
->lock
);
4940 ret
= qcow2_write_caches(bs
);
4941 qemu_co_mutex_unlock(&s
->lock
);
4946 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
4949 Error
*local_err
= NULL
;
4950 BlockMeasureInfo
*info
;
4951 uint64_t required
= 0; /* bytes that contribute to required size */
4952 uint64_t virtual_size
; /* disk size as seen by guest */
4953 uint64_t refcount_bits
;
4955 uint64_t luks_payload_size
= 0;
4956 size_t cluster_size
;
4959 PreallocMode prealloc
;
4960 bool has_backing_file
;
4965 /* Parse image creation options */
4966 extended_l2
= qemu_opt_get_bool_del(opts
, BLOCK_OPT_EXTL2
, false);
4968 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, extended_l2
,
4974 version
= qcow2_opt_get_version_del(opts
, &local_err
);
4979 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
4984 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
4985 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
4986 PREALLOC_MODE_OFF
, &local_err
);
4992 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
4993 has_backing_file
= !!optstr
;
4996 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
4997 has_luks
= optstr
&& strcmp(optstr
, "luks") == 0;
5001 g_autoptr(QCryptoBlockCreateOptions
) create_opts
= NULL
;
5002 QDict
*cryptoopts
= qcow2_extract_crypto_opts(opts
, "luks", errp
);
5005 create_opts
= block_crypto_create_opts_init(cryptoopts
, errp
);
5006 qobject_unref(cryptoopts
);
5011 if (!qcrypto_block_calculate_payload_offset(create_opts
,
5018 luks_payload_size
= ROUND_UP(headerlen
, cluster_size
);
5021 virtual_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
5022 virtual_size
= ROUND_UP(virtual_size
, cluster_size
);
5024 /* Check that virtual disk size is valid */
5025 l2e_size
= extended_l2
? L2E_SIZE_EXTENDED
: L2E_SIZE_NORMAL
;
5026 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
5027 cluster_size
/ l2e_size
);
5028 if (l2_tables
* L1E_SIZE
> QCOW_MAX_L1_SIZE
) {
5029 error_setg(&local_err
, "The image size is too large "
5030 "(try using a larger cluster size)");
5034 /* Account for input image */
5036 int64_t ssize
= bdrv_getlength(in_bs
);
5038 error_setg_errno(&local_err
, -ssize
,
5039 "Unable to get image virtual_size");
5043 virtual_size
= ROUND_UP(ssize
, cluster_size
);
5045 if (has_backing_file
) {
5046 /* We don't how much of the backing chain is shared by the input
5047 * image and the new image file. In the worst case the new image's
5048 * backing file has nothing in common with the input image. Be
5049 * conservative and assume all clusters need to be written.
5051 required
= virtual_size
;
5056 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
5059 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
5060 ssize
- offset
, &pnum
, NULL
,
5063 error_setg_errno(&local_err
, -ret
,
5064 "Unable to get block status");
5068 if (ret
& BDRV_BLOCK_ZERO
) {
5069 /* Skip zero regions (safe with no backing file) */
5070 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
5071 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
5072 /* Extend pnum to end of cluster for next iteration */
5073 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
5075 /* Count clusters we've seen */
5076 required
+= offset
% cluster_size
+ pnum
;
5082 /* Take into account preallocation. Nothing special is needed for
5083 * PREALLOC_MODE_METADATA since metadata is always counted.
5085 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
5086 required
= virtual_size
;
5089 info
= g_new0(BlockMeasureInfo
, 1);
5090 info
->fully_allocated
= luks_payload_size
+
5091 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
5092 ctz32(refcount_bits
), extended_l2
);
5095 * Remove data clusters that are not required. This overestimates the
5096 * required size because metadata needed for the fully allocated file is
5097 * still counted. Show bitmaps only if both source and destination
5098 * would support them.
5100 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
5101 info
->has_bitmaps
= version
>= 3 && in_bs
&&
5102 bdrv_supports_persistent_dirty_bitmap(in_bs
);
5103 if (info
->has_bitmaps
) {
5104 info
->bitmaps
= qcow2_get_persistent_dirty_bitmap_size(in_bs
,
5110 error_propagate(errp
, local_err
);
5114 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
5116 BDRVQcow2State
*s
= bs
->opaque
;
5117 bdi
->cluster_size
= s
->cluster_size
;
5118 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
5119 bdi
->is_dirty
= s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
;
5123 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
,
5126 BDRVQcow2State
*s
= bs
->opaque
;
5127 ImageInfoSpecific
*spec_info
;
5128 QCryptoBlockInfo
*encrypt_info
= NULL
;
5130 if (s
->crypto
!= NULL
) {
5131 encrypt_info
= qcrypto_block_get_info(s
->crypto
, errp
);
5132 if (!encrypt_info
) {
5137 spec_info
= g_new(ImageInfoSpecific
, 1);
5138 *spec_info
= (ImageInfoSpecific
){
5139 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
5140 .u
.qcow2
.data
= g_new0(ImageInfoSpecificQCow2
, 1),
5142 if (s
->qcow_version
== 2) {
5143 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
5144 .compat
= g_strdup("0.10"),
5145 .refcount_bits
= s
->refcount_bits
,
5147 } else if (s
->qcow_version
== 3) {
5148 Qcow2BitmapInfoList
*bitmaps
;
5149 if (!qcow2_get_bitmap_info_list(bs
, &bitmaps
, errp
)) {
5150 qapi_free_ImageInfoSpecific(spec_info
);
5151 qapi_free_QCryptoBlockInfo(encrypt_info
);
5154 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
5155 .compat
= g_strdup("1.1"),
5156 .lazy_refcounts
= s
->compatible_features
&
5157 QCOW2_COMPAT_LAZY_REFCOUNTS
,
5158 .has_lazy_refcounts
= true,
5159 .corrupt
= s
->incompatible_features
&
5160 QCOW2_INCOMPAT_CORRUPT
,
5161 .has_corrupt
= true,
5162 .has_extended_l2
= true,
5163 .extended_l2
= has_subclusters(s
),
5164 .refcount_bits
= s
->refcount_bits
,
5165 .has_bitmaps
= !!bitmaps
,
5167 .has_data_file
= !!s
->image_data_file
,
5168 .data_file
= g_strdup(s
->image_data_file
),
5169 .has_data_file_raw
= has_data_file(bs
),
5170 .data_file_raw
= data_file_is_raw(bs
),
5171 .compression_type
= s
->compression_type
,
5174 /* if this assertion fails, this probably means a new version was
5175 * added without having it covered here */
5180 ImageInfoSpecificQCow2Encryption
*qencrypt
=
5181 g_new(ImageInfoSpecificQCow2Encryption
, 1);
5182 switch (encrypt_info
->format
) {
5183 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
5184 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
5186 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
5187 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
5188 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
5193 /* Since we did shallow copy above, erase any pointers
5194 * in the original info */
5195 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
5196 qapi_free_QCryptoBlockInfo(encrypt_info
);
5198 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
5199 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
5205 static int qcow2_has_zero_init(BlockDriverState
*bs
)
5207 BDRVQcow2State
*s
= bs
->opaque
;
5210 if (qemu_in_coroutine()) {
5211 qemu_co_mutex_lock(&s
->lock
);
5214 * Check preallocation status: Preallocated images have all L2
5215 * tables allocated, nonpreallocated images have none. It is
5216 * therefore enough to check the first one.
5218 preallocated
= s
->l1_size
> 0 && s
->l1_table
[0] != 0;
5219 if (qemu_in_coroutine()) {
5220 qemu_co_mutex_unlock(&s
->lock
);
5223 if (!preallocated
) {
5225 } else if (bs
->encrypted
) {
5228 return bdrv_has_zero_init(s
->data_file
->bs
);
5233 * Check the request to vmstate. On success return
5234 * qcow2_vm_state_offset(bs) + @pos
5236 static int64_t qcow2_check_vmstate_request(BlockDriverState
*bs
,
5237 QEMUIOVector
*qiov
, int64_t pos
)
5239 BDRVQcow2State
*s
= bs
->opaque
;
5240 int64_t vmstate_offset
= qcow2_vm_state_offset(s
);
5243 /* Incoming requests must be OK */
5244 bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, &error_abort
);
5246 if (INT64_MAX
- pos
< vmstate_offset
) {
5250 pos
+= vmstate_offset
;
5251 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
5259 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
5262 int64_t offset
= qcow2_check_vmstate_request(bs
, qiov
, pos
);
5267 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
5268 return bs
->drv
->bdrv_co_pwritev_part(bs
, offset
, qiov
->size
, qiov
, 0, 0);
5271 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
5274 int64_t offset
= qcow2_check_vmstate_request(bs
, qiov
, pos
);
5279 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
5280 return bs
->drv
->bdrv_co_preadv_part(bs
, offset
, qiov
->size
, qiov
, 0, 0);
5283 static int qcow2_has_compressed_clusters(BlockDriverState
*bs
)
5286 int64_t bytes
= bdrv_getlength(bs
);
5292 while (bytes
!= 0) {
5294 QCow2SubclusterType type
;
5295 unsigned int cur_bytes
= MIN(INT_MAX
, bytes
);
5296 uint64_t host_offset
;
5298 ret
= qcow2_get_host_offset(bs
, offset
, &cur_bytes
, &host_offset
,
5304 if (type
== QCOW2_SUBCLUSTER_COMPRESSED
) {
5308 offset
+= cur_bytes
;
5316 * Downgrades an image's version. To achieve this, any incompatible features
5317 * have to be removed.
5319 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
5320 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
5323 BDRVQcow2State
*s
= bs
->opaque
;
5324 int current_version
= s
->qcow_version
;
5328 /* This is qcow2_downgrade(), not qcow2_upgrade() */
5329 assert(target_version
< current_version
);
5331 /* There are no other versions (now) that you can downgrade to */
5332 assert(target_version
== 2);
5334 if (s
->refcount_order
!= 4) {
5335 error_setg(errp
, "compat=0.10 requires refcount_bits=16");
5339 if (has_data_file(bs
)) {
5340 error_setg(errp
, "Cannot downgrade an image with a data file");
5345 * If any internal snapshot has a different size than the current
5346 * image size, or VM state size that exceeds 32 bits, downgrading
5347 * is unsafe. Even though we would still use v3-compliant output
5348 * to preserve that data, other v2 programs might not realize
5349 * those optional fields are important.
5351 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
5352 if (s
->snapshots
[i
].vm_state_size
> UINT32_MAX
||
5353 s
->snapshots
[i
].disk_size
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
5354 error_setg(errp
, "Internal snapshots prevent downgrade of image");
5359 /* clear incompatible features */
5360 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
5361 ret
= qcow2_mark_clean(bs
);
5363 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
5368 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
5369 * the first place; if that happens nonetheless, returning -ENOTSUP is the
5370 * best thing to do anyway */
5372 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_COMPRESSION
) {
5373 error_setg(errp
, "Cannot downgrade an image with incompatible features "
5374 "0x%" PRIx64
" set",
5375 s
->incompatible_features
& ~QCOW2_INCOMPAT_COMPRESSION
);
5379 /* since we can ignore compatible features, we can set them to 0 as well */
5380 s
->compatible_features
= 0;
5381 /* if lazy refcounts have been used, they have already been fixed through
5382 * clearing the dirty flag */
5384 /* clearing autoclear features is trivial */
5385 s
->autoclear_features
= 0;
5387 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
5389 error_setg_errno(errp
, -ret
, "Failed to turn zero into data clusters");
5393 if (s
->incompatible_features
& QCOW2_INCOMPAT_COMPRESSION
) {
5394 ret
= qcow2_has_compressed_clusters(bs
);
5396 error_setg(errp
, "Failed to check block status");
5400 error_setg(errp
, "Cannot downgrade an image with zstd compression "
5401 "type and existing compressed clusters");
5405 * No compressed clusters for now, so just chose default zlib
5408 s
->incompatible_features
&= ~QCOW2_INCOMPAT_COMPRESSION
;
5409 s
->compression_type
= QCOW2_COMPRESSION_TYPE_ZLIB
;
5412 assert(s
->incompatible_features
== 0);
5414 s
->qcow_version
= target_version
;
5415 ret
= qcow2_update_header(bs
);
5417 s
->qcow_version
= current_version
;
5418 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5425 * Upgrades an image's version. While newer versions encompass all
5426 * features of older versions, some things may have to be presented
5429 static int qcow2_upgrade(BlockDriverState
*bs
, int target_version
,
5430 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
5433 BDRVQcow2State
*s
= bs
->opaque
;
5434 bool need_snapshot_update
;
5435 int current_version
= s
->qcow_version
;
5439 /* This is qcow2_upgrade(), not qcow2_downgrade() */
5440 assert(target_version
> current_version
);
5442 /* There are no other versions (yet) that you can upgrade to */
5443 assert(target_version
== 3);
5445 status_cb(bs
, 0, 2, cb_opaque
);
5448 * In v2, snapshots do not need to have extra data. v3 requires
5449 * the 64-bit VM state size and the virtual disk size to be
5451 * qcow2_write_snapshots() will always write the list in the
5452 * v3-compliant format.
5454 need_snapshot_update
= false;
5455 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
5456 if (s
->snapshots
[i
].extra_data_size
<
5457 sizeof_field(QCowSnapshotExtraData
, vm_state_size_large
) +
5458 sizeof_field(QCowSnapshotExtraData
, disk_size
))
5460 need_snapshot_update
= true;
5464 if (need_snapshot_update
) {
5465 ret
= qcow2_write_snapshots(bs
);
5467 error_setg_errno(errp
, -ret
, "Failed to update the snapshot table");
5471 status_cb(bs
, 1, 2, cb_opaque
);
5473 s
->qcow_version
= target_version
;
5474 ret
= qcow2_update_header(bs
);
5476 s
->qcow_version
= current_version
;
5477 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5480 status_cb(bs
, 2, 2, cb_opaque
);
5485 typedef enum Qcow2AmendOperation
{
5486 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5487 * statically initialized to so that the helper CB can discern the first
5488 * invocation from an operation change */
5489 QCOW2_NO_OPERATION
= 0,
5492 QCOW2_UPDATING_ENCRYPTION
,
5493 QCOW2_CHANGING_REFCOUNT_ORDER
,
5495 } Qcow2AmendOperation
;
5497 typedef struct Qcow2AmendHelperCBInfo
{
5498 /* The code coordinating the amend operations should only modify
5499 * these four fields; the rest will be managed by the CB */
5500 BlockDriverAmendStatusCB
*original_status_cb
;
5501 void *original_cb_opaque
;
5503 Qcow2AmendOperation current_operation
;
5505 /* Total number of operations to perform (only set once) */
5506 int total_operations
;
5508 /* The following fields are managed by the CB */
5510 /* Number of operations completed */
5511 int operations_completed
;
5513 /* Cumulative offset of all completed operations */
5514 int64_t offset_completed
;
5516 Qcow2AmendOperation last_operation
;
5517 int64_t last_work_size
;
5518 } Qcow2AmendHelperCBInfo
;
5520 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
5521 int64_t operation_offset
,
5522 int64_t operation_work_size
, void *opaque
)
5524 Qcow2AmendHelperCBInfo
*info
= opaque
;
5525 int64_t current_work_size
;
5526 int64_t projected_work_size
;
5528 if (info
->current_operation
!= info
->last_operation
) {
5529 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
5530 info
->offset_completed
+= info
->last_work_size
;
5531 info
->operations_completed
++;
5534 info
->last_operation
= info
->current_operation
;
5537 assert(info
->total_operations
> 0);
5538 assert(info
->operations_completed
< info
->total_operations
);
5540 info
->last_work_size
= operation_work_size
;
5542 current_work_size
= info
->offset_completed
+ operation_work_size
;
5544 /* current_work_size is the total work size for (operations_completed + 1)
5545 * operations (which includes this one), so multiply it by the number of
5546 * operations not covered and divide it by the number of operations
5547 * covered to get a projection for the operations not covered */
5548 projected_work_size
= current_work_size
* (info
->total_operations
-
5549 info
->operations_completed
- 1)
5550 / (info
->operations_completed
+ 1);
5552 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
5553 current_work_size
+ projected_work_size
,
5554 info
->original_cb_opaque
);
5557 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
5558 BlockDriverAmendStatusCB
*status_cb
,
5563 BDRVQcow2State
*s
= bs
->opaque
;
5564 int old_version
= s
->qcow_version
, new_version
= old_version
;
5565 uint64_t new_size
= 0;
5566 const char *backing_file
= NULL
, *backing_format
= NULL
, *data_file
= NULL
;
5567 bool lazy_refcounts
= s
->use_lazy_refcounts
;
5568 bool data_file_raw
= data_file_is_raw(bs
);
5569 const char *compat
= NULL
;
5570 int refcount_bits
= s
->refcount_bits
;
5572 QemuOptDesc
*desc
= opts
->list
->desc
;
5573 Qcow2AmendHelperCBInfo helper_cb_info
;
5574 bool encryption_update
= false;
5576 while (desc
&& desc
->name
) {
5577 if (!qemu_opt_find(opts
, desc
->name
)) {
5578 /* only change explicitly defined options */
5583 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
5584 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
5586 /* preserve default */
5587 } else if (!strcmp(compat
, "0.10") || !strcmp(compat
, "v2")) {
5589 } else if (!strcmp(compat
, "1.1") || !strcmp(compat
, "v3")) {
5592 error_setg(errp
, "Unknown compatibility level %s", compat
);
5595 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
5596 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
5597 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
5598 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
5599 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
5600 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
5601 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
5604 "Can't amend encryption options - encryption not present");
5607 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
5609 "Only LUKS encryption options can be amended");
5612 encryption_update
= true;
5613 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
5614 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
5616 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
5617 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
5620 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
5621 !is_power_of_2(refcount_bits
))
5623 error_setg(errp
, "Refcount width must be a power of two and "
5624 "may not exceed 64 bits");
5627 } else if (!strcmp(desc
->name
, BLOCK_OPT_DATA_FILE
)) {
5628 data_file
= qemu_opt_get(opts
, BLOCK_OPT_DATA_FILE
);
5629 if (data_file
&& !has_data_file(bs
)) {
5630 error_setg(errp
, "data-file can only be set for images that "
5631 "use an external data file");
5634 } else if (!strcmp(desc
->name
, BLOCK_OPT_DATA_FILE_RAW
)) {
5635 data_file_raw
= qemu_opt_get_bool(opts
, BLOCK_OPT_DATA_FILE_RAW
,
5637 if (data_file_raw
&& !data_file_is_raw(bs
)) {
5638 error_setg(errp
, "data-file-raw cannot be set on existing "
5643 /* if this point is reached, this probably means a new option was
5644 * added without having it covered here */
5651 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
5652 .original_status_cb
= status_cb
,
5653 .original_cb_opaque
= cb_opaque
,
5654 .total_operations
= (new_version
!= old_version
)
5655 + (s
->refcount_bits
!= refcount_bits
) +
5656 (encryption_update
== true)
5659 /* Upgrade first (some features may require compat=1.1) */
5660 if (new_version
> old_version
) {
5661 helper_cb_info
.current_operation
= QCOW2_UPGRADING
;
5662 ret
= qcow2_upgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
5663 &helper_cb_info
, errp
);
5669 if (encryption_update
) {
5670 QDict
*amend_opts_dict
;
5671 QCryptoBlockAmendOptions
*amend_opts
;
5673 helper_cb_info
.current_operation
= QCOW2_UPDATING_ENCRYPTION
;
5674 amend_opts_dict
= qcow2_extract_crypto_opts(opts
, "luks", errp
);
5675 if (!amend_opts_dict
) {
5678 amend_opts
= block_crypto_amend_opts_init(amend_opts_dict
, errp
);
5679 qobject_unref(amend_opts_dict
);
5683 ret
= qcrypto_block_amend_options(s
->crypto
,
5684 qcow2_crypto_hdr_read_func
,
5685 qcow2_crypto_hdr_write_func
,
5690 qapi_free_QCryptoBlockAmendOptions(amend_opts
);
5696 if (s
->refcount_bits
!= refcount_bits
) {
5697 int refcount_order
= ctz32(refcount_bits
);
5699 if (new_version
< 3 && refcount_bits
!= 16) {
5700 error_setg(errp
, "Refcount widths other than 16 bits require "
5701 "compatibility level 1.1 or above (use compat=1.1 or "
5706 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
5707 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
5708 &qcow2_amend_helper_cb
,
5709 &helper_cb_info
, errp
);
5715 /* data-file-raw blocks backing files, so clear it first if requested */
5716 if (data_file_raw
) {
5717 s
->autoclear_features
|= QCOW2_AUTOCLEAR_DATA_FILE_RAW
;
5719 s
->autoclear_features
&= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW
;
5723 g_free(s
->image_data_file
);
5724 s
->image_data_file
= *data_file
? g_strdup(data_file
) : NULL
;
5727 ret
= qcow2_update_header(bs
);
5729 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5733 if (backing_file
|| backing_format
) {
5734 if (g_strcmp0(backing_file
, s
->image_backing_file
) ||
5735 g_strcmp0(backing_format
, s
->image_backing_format
)) {
5736 error_setg(errp
, "Cannot amend the backing file");
5737 error_append_hint(errp
,
5738 "You can use 'qemu-img rebase' instead.\n");
5743 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
5744 if (lazy_refcounts
) {
5745 if (new_version
< 3) {
5746 error_setg(errp
, "Lazy refcounts only supported with "
5747 "compatibility level 1.1 and above (use compat=1.1 "
5751 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
5752 ret
= qcow2_update_header(bs
);
5754 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
5755 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5758 s
->use_lazy_refcounts
= true;
5760 /* make image clean first */
5761 ret
= qcow2_mark_clean(bs
);
5763 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
5766 /* now disallow lazy refcounts */
5767 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
5768 ret
= qcow2_update_header(bs
);
5770 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
5771 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5774 s
->use_lazy_refcounts
= false;
5779 BlockBackend
*blk
= blk_new_with_bs(bs
, BLK_PERM_RESIZE
, BLK_PERM_ALL
,
5786 * Amending image options should ensure that the image has
5787 * exactly the given new values, so pass exact=true here.
5789 ret
= blk_truncate(blk
, new_size
, true, PREALLOC_MODE_OFF
, 0, errp
);
5796 /* Downgrade last (so unsupported features can be removed before) */
5797 if (new_version
< old_version
) {
5798 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
5799 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
5800 &helper_cb_info
, errp
);
5809 static int coroutine_fn
qcow2_co_amend(BlockDriverState
*bs
,
5810 BlockdevAmendOptions
*opts
,
5814 BlockdevAmendOptionsQcow2
*qopts
= &opts
->u
.qcow2
;
5815 BDRVQcow2State
*s
= bs
->opaque
;
5818 if (qopts
->has_encrypt
) {
5820 error_setg(errp
, "image is not encrypted, can't amend");
5824 if (qopts
->encrypt
->format
!= Q_CRYPTO_BLOCK_FORMAT_LUKS
) {
5826 "Amend can't be used to change the qcow2 encryption format");
5830 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
5832 "Only LUKS encryption options can be amended for qcow2 with blockdev-amend");
5836 ret
= qcrypto_block_amend_options(s
->crypto
,
5837 qcow2_crypto_hdr_read_func
,
5838 qcow2_crypto_hdr_write_func
,
5848 * If offset or size are negative, respectively, they will not be included in
5849 * the BLOCK_IMAGE_CORRUPTED event emitted.
5850 * fatal will be ignored for read-only BDS; corruptions found there will always
5851 * be considered non-fatal.
5853 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
5854 int64_t size
, const char *message_format
, ...)
5856 BDRVQcow2State
*s
= bs
->opaque
;
5857 const char *node_name
;
5861 fatal
= fatal
&& bdrv_is_writable(bs
);
5863 if (s
->signaled_corruption
&&
5864 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
5869 va_start(ap
, message_format
);
5870 message
= g_strdup_vprintf(message_format
, ap
);
5874 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
5875 "corruption events will be suppressed\n", message
);
5877 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
5878 "corruption events will be suppressed\n", message
);
5881 node_name
= bdrv_get_node_name(bs
);
5882 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
5883 *node_name
!= '\0', node_name
,
5884 message
, offset
>= 0, offset
,
5890 qcow2_mark_corrupt(bs
);
5891 bs
->drv
= NULL
; /* make BDS unusable */
5894 s
->signaled_corruption
= true;
5897 #define QCOW_COMMON_OPTIONS \
5899 .name = BLOCK_OPT_SIZE, \
5900 .type = QEMU_OPT_SIZE, \
5901 .help = "Virtual disk size" \
5904 .name = BLOCK_OPT_COMPAT_LEVEL, \
5905 .type = QEMU_OPT_STRING, \
5906 .help = "Compatibility level (v2 [0.10] or v3 [1.1])" \
5909 .name = BLOCK_OPT_BACKING_FILE, \
5910 .type = QEMU_OPT_STRING, \
5911 .help = "File name of a base image" \
5914 .name = BLOCK_OPT_BACKING_FMT, \
5915 .type = QEMU_OPT_STRING, \
5916 .help = "Image format of the base image" \
5919 .name = BLOCK_OPT_DATA_FILE, \
5920 .type = QEMU_OPT_STRING, \
5921 .help = "File name of an external data file" \
5924 .name = BLOCK_OPT_DATA_FILE_RAW, \
5925 .type = QEMU_OPT_BOOL, \
5926 .help = "The external data file must stay valid " \
5930 .name = BLOCK_OPT_LAZY_REFCOUNTS, \
5931 .type = QEMU_OPT_BOOL, \
5932 .help = "Postpone refcount updates", \
5933 .def_value_str = "off" \
5936 .name = BLOCK_OPT_REFCOUNT_BITS, \
5937 .type = QEMU_OPT_NUMBER, \
5938 .help = "Width of a reference count entry in bits", \
5939 .def_value_str = "16" \
5942 static QemuOptsList qcow2_create_opts
= {
5943 .name
= "qcow2-create-opts",
5944 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
5947 .name
= BLOCK_OPT_ENCRYPT
, \
5948 .type
= QEMU_OPT_BOOL
, \
5949 .help
= "Encrypt the image with format 'aes'. (Deprecated " \
5950 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)", \
5953 .name
= BLOCK_OPT_ENCRYPT_FORMAT
, \
5954 .type
= QEMU_OPT_STRING
, \
5955 .help
= "Encrypt the image, format choices: 'aes', 'luks'", \
5957 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.", \
5958 "ID of secret providing qcow AES key or LUKS passphrase"), \
5959 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."), \
5960 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."), \
5961 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."), \
5962 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."), \
5963 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."), \
5964 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."), \
5966 .name
= BLOCK_OPT_CLUSTER_SIZE
, \
5967 .type
= QEMU_OPT_SIZE
, \
5968 .help
= "qcow2 cluster size", \
5969 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
) \
5972 .name
= BLOCK_OPT_EXTL2
, \
5973 .type
= QEMU_OPT_BOOL
, \
5974 .help
= "Extended L2 tables", \
5975 .def_value_str
= "off" \
5978 .name
= BLOCK_OPT_PREALLOC
, \
5979 .type
= QEMU_OPT_STRING
, \
5980 .help
= "Preallocation mode (allowed values: off, " \
5981 "metadata, falloc, full)" \
5984 .name
= BLOCK_OPT_COMPRESSION_TYPE
, \
5985 .type
= QEMU_OPT_STRING
, \
5986 .help
= "Compression method used for image cluster " \
5988 .def_value_str
= "zlib" \
5990 QCOW_COMMON_OPTIONS
,
5991 { /* end of list */ }
5995 static QemuOptsList qcow2_amend_opts
= {
5996 .name
= "qcow2-amend-opts",
5997 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_amend_opts
.head
),
5999 BLOCK_CRYPTO_OPT_DEF_LUKS_STATE("encrypt."),
6000 BLOCK_CRYPTO_OPT_DEF_LUKS_KEYSLOT("encrypt."),
6001 BLOCK_CRYPTO_OPT_DEF_LUKS_OLD_SECRET("encrypt."),
6002 BLOCK_CRYPTO_OPT_DEF_LUKS_NEW_SECRET("encrypt."),
6003 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
6004 QCOW_COMMON_OPTIONS
,
6005 { /* end of list */ }
6009 static const char *const qcow2_strong_runtime_opts
[] = {
6010 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET
,
6015 BlockDriver bdrv_qcow2
= {
6016 .format_name
= "qcow2",
6017 .instance_size
= sizeof(BDRVQcow2State
),
6018 .bdrv_probe
= qcow2_probe
,
6019 .bdrv_open
= qcow2_open
,
6020 .bdrv_close
= qcow2_close
,
6021 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
6022 .bdrv_reopen_commit
= qcow2_reopen_commit
,
6023 .bdrv_reopen_commit_post
= qcow2_reopen_commit_post
,
6024 .bdrv_reopen_abort
= qcow2_reopen_abort
,
6025 .bdrv_join_options
= qcow2_join_options
,
6026 .bdrv_child_perm
= bdrv_default_perms
,
6027 .bdrv_co_create_opts
= qcow2_co_create_opts
,
6028 .bdrv_co_create
= qcow2_co_create
,
6029 .bdrv_has_zero_init
= qcow2_has_zero_init
,
6030 .bdrv_co_block_status
= qcow2_co_block_status
,
6032 .bdrv_co_preadv_part
= qcow2_co_preadv_part
,
6033 .bdrv_co_pwritev_part
= qcow2_co_pwritev_part
,
6034 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
6036 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
6037 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
6038 .bdrv_co_copy_range_from
= qcow2_co_copy_range_from
,
6039 .bdrv_co_copy_range_to
= qcow2_co_copy_range_to
,
6040 .bdrv_co_truncate
= qcow2_co_truncate
,
6041 .bdrv_co_pwritev_compressed_part
= qcow2_co_pwritev_compressed_part
,
6042 .bdrv_make_empty
= qcow2_make_empty
,
6044 .bdrv_snapshot_create
= qcow2_snapshot_create
,
6045 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
6046 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
6047 .bdrv_snapshot_list
= qcow2_snapshot_list
,
6048 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
6049 .bdrv_measure
= qcow2_measure
,
6050 .bdrv_get_info
= qcow2_get_info
,
6051 .bdrv_get_specific_info
= qcow2_get_specific_info
,
6053 .bdrv_save_vmstate
= qcow2_save_vmstate
,
6054 .bdrv_load_vmstate
= qcow2_load_vmstate
,
6057 .supports_backing
= true,
6058 .bdrv_change_backing_file
= qcow2_change_backing_file
,
6060 .bdrv_refresh_limits
= qcow2_refresh_limits
,
6061 .bdrv_co_invalidate_cache
= qcow2_co_invalidate_cache
,
6062 .bdrv_inactivate
= qcow2_inactivate
,
6064 .create_opts
= &qcow2_create_opts
,
6065 .amend_opts
= &qcow2_amend_opts
,
6066 .strong_runtime_opts
= qcow2_strong_runtime_opts
,
6067 .mutable_opts
= mutable_opts
,
6068 .bdrv_co_check
= qcow2_co_check
,
6069 .bdrv_amend_options
= qcow2_amend_options
,
6070 .bdrv_co_amend
= qcow2_co_amend
,
6072 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
6073 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
6075 .bdrv_supports_persistent_dirty_bitmap
=
6076 qcow2_supports_persistent_dirty_bitmap
,
6077 .bdrv_co_can_store_new_dirty_bitmap
= qcow2_co_can_store_new_dirty_bitmap
,
6078 .bdrv_co_remove_persistent_dirty_bitmap
=
6079 qcow2_co_remove_persistent_dirty_bitmap
,
6082 static void bdrv_qcow2_init(void)
6084 bdrv_register(&bdrv_qcow2
);
6087 block_init(bdrv_qcow2_init
);