2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
26 #include "block/block_int.h"
27 #include "block/qdict.h"
28 #include "sysemu/block-backend.h"
29 #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 "qapi/qobject-input-visitor.h"
42 #include "qapi/qapi-visit-block-core.h"
46 Differences with QCOW:
48 - Support for multiple incremental snapshots.
49 - Memory management by reference counts.
50 - Clusters which have a reference count of one have the bit
51 QCOW_OFLAG_COPIED to optimize write performance.
52 - Size of compressed clusters is stored in sectors to reduce bit usage
53 in the cluster offsets.
54 - Support for storing additional data (such as the VM state) in the
56 - If a backing store is used, the cluster size is not constrained
57 (could be backported to QCOW).
58 - L2 tables have always a size of one cluster.
65 } QEMU_PACKED QCowExtension
;
67 #define QCOW2_EXT_MAGIC_END 0
68 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
69 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
70 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
71 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
73 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
75 const QCowHeader
*cow_header
= (const void *)buf
;
77 if (buf_size
>= sizeof(QCowHeader
) &&
78 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
79 be32_to_cpu(cow_header
->version
) >= 2)
86 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
87 uint8_t *buf
, size_t buflen
,
88 void *opaque
, Error
**errp
)
90 BlockDriverState
*bs
= opaque
;
91 BDRVQcow2State
*s
= bs
->opaque
;
94 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
95 error_setg(errp
, "Request for data outside of extension header");
99 ret
= bdrv_pread(bs
->file
,
100 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
102 error_setg_errno(errp
, -ret
, "Could not read encryption header");
109 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
110 void *opaque
, Error
**errp
)
112 BlockDriverState
*bs
= opaque
;
113 BDRVQcow2State
*s
= bs
->opaque
;
117 ret
= qcow2_alloc_clusters(bs
, headerlen
);
119 error_setg_errno(errp
, -ret
,
120 "Cannot allocate cluster for LUKS header size %zu",
125 s
->crypto_header
.length
= headerlen
;
126 s
->crypto_header
.offset
= ret
;
128 /* Zero fill remaining space in cluster so it has predictable
129 * content in case of future spec changes */
130 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
131 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
) == 0);
132 ret
= bdrv_pwrite_zeroes(bs
->file
,
134 clusterlen
- headerlen
, 0);
136 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
144 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
145 const uint8_t *buf
, size_t buflen
,
146 void *opaque
, Error
**errp
)
148 BlockDriverState
*bs
= opaque
;
149 BDRVQcow2State
*s
= bs
->opaque
;
152 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
153 error_setg(errp
, "Request for data outside of extension header");
157 ret
= bdrv_pwrite(bs
->file
,
158 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
160 error_setg_errno(errp
, -ret
, "Could not read encryption header");
168 * read qcow2 extension and fill bs
169 * start reading from start_offset
170 * finish reading upon magic of value 0 or when end_offset reached
171 * unknown magic is skipped (future extension this version knows nothing about)
172 * return 0 upon success, non-0 otherwise
174 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
175 uint64_t end_offset
, void **p_feature_table
,
176 int flags
, bool *need_update_header
,
179 BDRVQcow2State
*s
= bs
->opaque
;
183 Qcow2BitmapHeaderExt bitmaps_ext
;
185 if (need_update_header
!= NULL
) {
186 *need_update_header
= false;
190 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
192 offset
= start_offset
;
193 while (offset
< end_offset
) {
197 if (offset
> s
->cluster_size
)
198 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
200 printf("attempting to read extended header in offset %lu\n", offset
);
203 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
205 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
206 "pread fail from offset %" PRIu64
, offset
);
209 be32_to_cpus(&ext
.magic
);
210 be32_to_cpus(&ext
.len
);
211 offset
+= sizeof(ext
);
213 printf("ext.magic = 0x%x\n", ext
.magic
);
215 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
216 error_setg(errp
, "Header extension too large");
221 case QCOW2_EXT_MAGIC_END
:
224 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
225 if (ext
.len
>= sizeof(bs
->backing_format
)) {
226 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
227 " too large (>=%zu)", ext
.len
,
228 sizeof(bs
->backing_format
));
231 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
233 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
234 "Could not read format name");
237 bs
->backing_format
[ext
.len
] = '\0';
238 s
->image_backing_format
= g_strdup(bs
->backing_format
);
240 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
244 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
245 if (p_feature_table
!= NULL
) {
246 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
247 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
249 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
250 "Could not read table");
254 *p_feature_table
= feature_table
;
258 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
259 unsigned int cflags
= 0;
260 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
261 error_setg(errp
, "CRYPTO header extension only "
262 "expected with LUKS encryption method");
265 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
266 error_setg(errp
, "CRYPTO header extension size %u, "
267 "but expected size %zu", ext
.len
,
268 sizeof(Qcow2CryptoHeaderExtension
));
272 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
274 error_setg_errno(errp
, -ret
,
275 "Unable to read CRYPTO header extension");
278 be64_to_cpus(&s
->crypto_header
.offset
);
279 be64_to_cpus(&s
->crypto_header
.length
);
281 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
282 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
283 "not a multiple of cluster size '%u'",
284 s
->crypto_header
.offset
, s
->cluster_size
);
288 if (flags
& BDRV_O_NO_IO
) {
289 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
291 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
292 qcow2_crypto_hdr_read_func
,
299 case QCOW2_EXT_MAGIC_BITMAPS
:
300 if (ext
.len
!= sizeof(bitmaps_ext
)) {
301 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
302 "Invalid extension length");
306 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
307 if (s
->qcow_version
< 3) {
308 /* Let's be a bit more specific */
309 warn_report("This qcow2 v2 image contains bitmaps, but "
310 "they may have been modified by a program "
311 "without persistent bitmap support; so now "
312 "they must all be considered inconsistent");
314 warn_report("a program lacking bitmap support "
315 "modified this file, so all bitmaps are now "
316 "considered inconsistent");
318 error_printf("Some clusters may be leaked, "
319 "run 'qemu-img check -r' on the image "
321 if (need_update_header
!= NULL
) {
322 /* Updating is needed to drop invalid bitmap extension. */
323 *need_update_header
= true;
328 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
330 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
331 "Could not read ext header");
335 if (bitmaps_ext
.reserved32
!= 0) {
336 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
337 "Reserved field is not zero");
341 be32_to_cpus(&bitmaps_ext
.nb_bitmaps
);
342 be64_to_cpus(&bitmaps_ext
.bitmap_directory_size
);
343 be64_to_cpus(&bitmaps_ext
.bitmap_directory_offset
);
345 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
347 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
348 "exceeding the QEMU supported maximum of %d",
349 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
353 if (bitmaps_ext
.nb_bitmaps
== 0) {
354 error_setg(errp
, "found bitmaps extension with zero bitmaps");
358 if (bitmaps_ext
.bitmap_directory_offset
& (s
->cluster_size
- 1)) {
359 error_setg(errp
, "bitmaps_ext: "
360 "invalid bitmap directory offset");
364 if (bitmaps_ext
.bitmap_directory_size
>
365 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
366 error_setg(errp
, "bitmaps_ext: "
367 "bitmap directory size (%" PRIu64
") exceeds "
368 "the maximum supported size (%d)",
369 bitmaps_ext
.bitmap_directory_size
,
370 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
374 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
375 s
->bitmap_directory_offset
=
376 bitmaps_ext
.bitmap_directory_offset
;
377 s
->bitmap_directory_size
=
378 bitmaps_ext
.bitmap_directory_size
;
381 printf("Qcow2: Got bitmaps extension: "
382 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
383 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
388 /* unknown magic - save it in case we need to rewrite the header */
389 /* If you add a new feature, make sure to also update the fast
390 * path of qcow2_make_empty() to deal with it. */
392 Qcow2UnknownHeaderExtension
*uext
;
394 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
395 uext
->magic
= ext
.magic
;
397 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
399 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
401 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
402 "Could not read data");
409 offset
+= ((ext
.len
+ 7) & ~7);
415 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
417 BDRVQcow2State
*s
= bs
->opaque
;
418 Qcow2UnknownHeaderExtension
*uext
, *next
;
420 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
421 QLIST_REMOVE(uext
, next
);
426 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
429 char *features
= g_strdup("");
432 while (table
&& table
->name
[0] != '\0') {
433 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
434 if (mask
& (1ULL << table
->bit
)) {
436 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
439 mask
&= ~(1ULL << table
->bit
);
447 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
448 old
, *old
? ", " : "", mask
);
452 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
457 * Sets the dirty bit and flushes afterwards if necessary.
459 * The incompatible_features bit is only set if the image file header was
460 * updated successfully. Therefore it is not required to check the return
461 * value of this function.
463 int qcow2_mark_dirty(BlockDriverState
*bs
)
465 BDRVQcow2State
*s
= bs
->opaque
;
469 assert(s
->qcow_version
>= 3);
471 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
472 return 0; /* already dirty */
475 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
476 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
481 ret
= bdrv_flush(bs
->file
->bs
);
486 /* Only treat image as dirty if the header was updated successfully */
487 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
492 * Clears the dirty bit and flushes before if necessary. Only call this
493 * function when there are no pending requests, it does not guard against
494 * concurrent requests dirtying the image.
496 static int qcow2_mark_clean(BlockDriverState
*bs
)
498 BDRVQcow2State
*s
= bs
->opaque
;
500 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
503 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
505 ret
= qcow2_flush_caches(bs
);
510 return qcow2_update_header(bs
);
516 * Marks the image as corrupt.
518 int qcow2_mark_corrupt(BlockDriverState
*bs
)
520 BDRVQcow2State
*s
= bs
->opaque
;
522 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
523 return qcow2_update_header(bs
);
527 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
528 * before if necessary.
530 int qcow2_mark_consistent(BlockDriverState
*bs
)
532 BDRVQcow2State
*s
= bs
->opaque
;
534 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
535 int ret
= qcow2_flush_caches(bs
);
540 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
541 return qcow2_update_header(bs
);
546 static int coroutine_fn
qcow2_co_check_locked(BlockDriverState
*bs
,
547 BdrvCheckResult
*result
,
550 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
555 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
556 ret
= qcow2_mark_clean(bs
);
560 return qcow2_mark_consistent(bs
);
565 static int coroutine_fn
qcow2_co_check(BlockDriverState
*bs
,
566 BdrvCheckResult
*result
,
569 BDRVQcow2State
*s
= bs
->opaque
;
572 qemu_co_mutex_lock(&s
->lock
);
573 ret
= qcow2_co_check_locked(bs
, result
, fix
);
574 qemu_co_mutex_unlock(&s
->lock
);
578 int qcow2_validate_table(BlockDriverState
*bs
, uint64_t offset
,
579 uint64_t entries
, size_t entry_len
,
580 int64_t max_size_bytes
, const char *table_name
,
583 BDRVQcow2State
*s
= bs
->opaque
;
585 if (entries
> max_size_bytes
/ entry_len
) {
586 error_setg(errp
, "%s too large", table_name
);
590 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
591 * because values will be passed to qemu functions taking int64_t. */
592 if ((INT64_MAX
- entries
* entry_len
< offset
) ||
593 (offset_into_cluster(s
, offset
) != 0)) {
594 error_setg(errp
, "%s offset invalid", table_name
);
601 static QemuOptsList qcow2_runtime_opts
= {
603 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
606 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
607 .type
= QEMU_OPT_BOOL
,
608 .help
= "Postpone refcount updates",
611 .name
= QCOW2_OPT_DISCARD_REQUEST
,
612 .type
= QEMU_OPT_BOOL
,
613 .help
= "Pass guest discard requests to the layer below",
616 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
617 .type
= QEMU_OPT_BOOL
,
618 .help
= "Generate discard requests when snapshot related space "
622 .name
= QCOW2_OPT_DISCARD_OTHER
,
623 .type
= QEMU_OPT_BOOL
,
624 .help
= "Generate discard requests when other clusters are freed",
627 .name
= QCOW2_OPT_OVERLAP
,
628 .type
= QEMU_OPT_STRING
,
629 .help
= "Selects which overlap checks to perform from a range of "
630 "templates (none, constant, cached, all)",
633 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
634 .type
= QEMU_OPT_STRING
,
635 .help
= "Selects which overlap checks to perform from a range of "
636 "templates (none, constant, cached, all)",
639 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
640 .type
= QEMU_OPT_BOOL
,
641 .help
= "Check for unintended writes into the main qcow2 header",
644 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
645 .type
= QEMU_OPT_BOOL
,
646 .help
= "Check for unintended writes into the active L1 table",
649 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
650 .type
= QEMU_OPT_BOOL
,
651 .help
= "Check for unintended writes into an active L2 table",
654 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
655 .type
= QEMU_OPT_BOOL
,
656 .help
= "Check for unintended writes into the refcount table",
659 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
660 .type
= QEMU_OPT_BOOL
,
661 .help
= "Check for unintended writes into a refcount block",
664 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
665 .type
= QEMU_OPT_BOOL
,
666 .help
= "Check for unintended writes into the snapshot table",
669 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
670 .type
= QEMU_OPT_BOOL
,
671 .help
= "Check for unintended writes into an inactive L1 table",
674 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
675 .type
= QEMU_OPT_BOOL
,
676 .help
= "Check for unintended writes into an inactive L2 table",
679 .name
= QCOW2_OPT_CACHE_SIZE
,
680 .type
= QEMU_OPT_SIZE
,
681 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
685 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
686 .type
= QEMU_OPT_SIZE
,
687 .help
= "Maximum L2 table cache size",
690 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
691 .type
= QEMU_OPT_SIZE
,
692 .help
= "Size of each entry in the L2 cache",
695 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
696 .type
= QEMU_OPT_SIZE
,
697 .help
= "Maximum refcount block cache size",
700 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
701 .type
= QEMU_OPT_NUMBER
,
702 .help
= "Clean unused cache entries after this time (in seconds)",
704 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
705 "ID of secret providing qcow2 AES key or LUKS passphrase"),
706 { /* end of list */ }
710 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
711 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
712 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
713 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
714 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
715 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
716 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
717 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
718 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
721 static void cache_clean_timer_cb(void *opaque
)
723 BlockDriverState
*bs
= opaque
;
724 BDRVQcow2State
*s
= bs
->opaque
;
725 qcow2_cache_clean_unused(s
->l2_table_cache
);
726 qcow2_cache_clean_unused(s
->refcount_block_cache
);
727 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
728 (int64_t) s
->cache_clean_interval
* 1000);
731 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
733 BDRVQcow2State
*s
= bs
->opaque
;
734 if (s
->cache_clean_interval
> 0) {
735 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
736 SCALE_MS
, cache_clean_timer_cb
,
738 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
739 (int64_t) s
->cache_clean_interval
* 1000);
743 static void cache_clean_timer_del(BlockDriverState
*bs
)
745 BDRVQcow2State
*s
= bs
->opaque
;
746 if (s
->cache_clean_timer
) {
747 timer_del(s
->cache_clean_timer
);
748 timer_free(s
->cache_clean_timer
);
749 s
->cache_clean_timer
= NULL
;
753 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
755 cache_clean_timer_del(bs
);
758 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
759 AioContext
*new_context
)
761 cache_clean_timer_init(bs
, new_context
);
764 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
765 uint64_t *l2_cache_size
,
766 uint64_t *l2_cache_entry_size
,
767 uint64_t *refcount_cache_size
, Error
**errp
)
769 BDRVQcow2State
*s
= bs
->opaque
;
770 uint64_t combined_cache_size
;
771 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
772 int min_refcount_cache
= MIN_REFCOUNT_CACHE_SIZE
* s
->cluster_size
;
774 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
775 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
776 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
778 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
779 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
780 *refcount_cache_size
= qemu_opt_get_size(opts
,
781 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
783 *l2_cache_entry_size
= qemu_opt_get_size(
784 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
786 if (combined_cache_size_set
) {
787 if (l2_cache_size_set
&& refcount_cache_size_set
) {
788 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
789 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
792 } else if (*l2_cache_size
> combined_cache_size
) {
793 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
794 QCOW2_OPT_CACHE_SIZE
);
796 } else if (*refcount_cache_size
> combined_cache_size
) {
797 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
798 QCOW2_OPT_CACHE_SIZE
);
802 if (l2_cache_size_set
) {
803 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
804 } else if (refcount_cache_size_set
) {
805 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
807 uint64_t virtual_disk_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
808 uint64_t max_l2_cache
= virtual_disk_size
/ (s
->cluster_size
/ 8);
810 /* Assign as much memory as possible to the L2 cache, and
811 * use the remainder for the refcount cache */
812 if (combined_cache_size
>= max_l2_cache
+ min_refcount_cache
) {
813 *l2_cache_size
= max_l2_cache
;
814 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
816 *refcount_cache_size
=
817 MIN(combined_cache_size
, min_refcount_cache
);
818 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
822 if (!l2_cache_size_set
) {
823 *l2_cache_size
= MAX(DEFAULT_L2_CACHE_BYTE_SIZE
,
824 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
827 if (!refcount_cache_size_set
) {
828 *refcount_cache_size
= min_refcount_cache
;
832 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
833 *l2_cache_entry_size
> s
->cluster_size
||
834 !is_power_of_2(*l2_cache_entry_size
)) {
835 error_setg(errp
, "L2 cache entry size must be a power of two "
836 "between %d and the cluster size (%d)",
837 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
842 typedef struct Qcow2ReopenState
{
843 Qcow2Cache
*l2_table_cache
;
844 Qcow2Cache
*refcount_block_cache
;
845 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
846 bool use_lazy_refcounts
;
848 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
849 uint64_t cache_clean_interval
;
850 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
853 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
855 QDict
*options
, int flags
,
858 BDRVQcow2State
*s
= bs
->opaque
;
859 QemuOpts
*opts
= NULL
;
860 const char *opt_overlap_check
, *opt_overlap_check_template
;
861 int overlap_check_template
= 0;
862 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
864 const char *encryptfmt
;
865 QDict
*encryptopts
= NULL
;
866 Error
*local_err
= NULL
;
869 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
870 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
872 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
873 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
875 error_propagate(errp
, local_err
);
880 /* get L2 table/refcount block cache size from command line options */
881 read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
882 &refcount_cache_size
, &local_err
);
884 error_propagate(errp
, local_err
);
889 l2_cache_size
/= l2_cache_entry_size
;
890 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
891 l2_cache_size
= MIN_L2_CACHE_SIZE
;
893 if (l2_cache_size
> INT_MAX
) {
894 error_setg(errp
, "L2 cache size too big");
899 refcount_cache_size
/= s
->cluster_size
;
900 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
901 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
903 if (refcount_cache_size
> INT_MAX
) {
904 error_setg(errp
, "Refcount cache size too big");
909 /* alloc new L2 table/refcount block cache, flush old one */
910 if (s
->l2_table_cache
) {
911 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
913 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
918 if (s
->refcount_block_cache
) {
919 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
921 error_setg_errno(errp
, -ret
,
922 "Failed to flush the refcount block cache");
927 r
->l2_slice_size
= l2_cache_entry_size
/ sizeof(uint64_t);
928 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
929 l2_cache_entry_size
);
930 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
932 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
933 error_setg(errp
, "Could not allocate metadata caches");
938 /* New interval for cache cleanup timer */
939 r
->cache_clean_interval
=
940 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
941 s
->cache_clean_interval
);
943 if (r
->cache_clean_interval
!= 0) {
944 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
945 " not supported on this host");
950 if (r
->cache_clean_interval
> UINT_MAX
) {
951 error_setg(errp
, "Cache clean interval too big");
956 /* lazy-refcounts; flush if going from enabled to disabled */
957 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
958 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
959 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
960 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
961 "qemu 1.1 compatibility level");
966 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
967 ret
= qcow2_mark_clean(bs
);
969 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
974 /* Overlap check options */
975 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
976 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
977 if (opt_overlap_check_template
&& opt_overlap_check
&&
978 strcmp(opt_overlap_check_template
, opt_overlap_check
))
980 error_setg(errp
, "Conflicting values for qcow2 options '"
981 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
982 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
986 if (!opt_overlap_check
) {
987 opt_overlap_check
= opt_overlap_check_template
?: "cached";
990 if (!strcmp(opt_overlap_check
, "none")) {
991 overlap_check_template
= 0;
992 } else if (!strcmp(opt_overlap_check
, "constant")) {
993 overlap_check_template
= QCOW2_OL_CONSTANT
;
994 } else if (!strcmp(opt_overlap_check
, "cached")) {
995 overlap_check_template
= QCOW2_OL_CACHED
;
996 } else if (!strcmp(opt_overlap_check
, "all")) {
997 overlap_check_template
= QCOW2_OL_ALL
;
999 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
1000 "'overlap-check'. Allowed are any of the following: "
1001 "none, constant, cached, all", opt_overlap_check
);
1006 r
->overlap_check
= 0;
1007 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
1008 /* overlap-check defines a template bitmask, but every flag may be
1009 * overwritten through the associated boolean option */
1011 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
1012 overlap_check_template
& (1 << i
)) << i
;
1015 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
1016 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
1017 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
1018 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1019 flags
& BDRV_O_UNMAP
);
1020 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1021 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1022 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1023 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1025 switch (s
->crypt_method_header
) {
1026 case QCOW_CRYPT_NONE
:
1028 error_setg(errp
, "No encryption in image header, but options "
1029 "specified format '%s'", encryptfmt
);
1035 case QCOW_CRYPT_AES
:
1036 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1038 "Header reported 'aes' encryption format but "
1039 "options specify '%s'", encryptfmt
);
1043 qdict_put_str(encryptopts
, "format", "qcow");
1044 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1047 case QCOW_CRYPT_LUKS
:
1048 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1050 "Header reported 'luks' encryption format but "
1051 "options specify '%s'", encryptfmt
);
1055 qdict_put_str(encryptopts
, "format", "luks");
1056 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1060 error_setg(errp
, "Unsupported encryption method %d",
1061 s
->crypt_method_header
);
1064 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1071 qobject_unref(encryptopts
);
1072 qemu_opts_del(opts
);
1077 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1078 Qcow2ReopenState
*r
)
1080 BDRVQcow2State
*s
= bs
->opaque
;
1083 if (s
->l2_table_cache
) {
1084 qcow2_cache_destroy(s
->l2_table_cache
);
1086 if (s
->refcount_block_cache
) {
1087 qcow2_cache_destroy(s
->refcount_block_cache
);
1089 s
->l2_table_cache
= r
->l2_table_cache
;
1090 s
->refcount_block_cache
= r
->refcount_block_cache
;
1091 s
->l2_slice_size
= r
->l2_slice_size
;
1093 s
->overlap_check
= r
->overlap_check
;
1094 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1096 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1097 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1100 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1101 cache_clean_timer_del(bs
);
1102 s
->cache_clean_interval
= r
->cache_clean_interval
;
1103 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1106 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1107 s
->crypto_opts
= r
->crypto_opts
;
1110 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1111 Qcow2ReopenState
*r
)
1113 if (r
->l2_table_cache
) {
1114 qcow2_cache_destroy(r
->l2_table_cache
);
1116 if (r
->refcount_block_cache
) {
1117 qcow2_cache_destroy(r
->refcount_block_cache
);
1119 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1122 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1123 int flags
, Error
**errp
)
1125 Qcow2ReopenState r
= {};
1128 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1130 qcow2_update_options_commit(bs
, &r
);
1132 qcow2_update_options_abort(bs
, &r
);
1138 /* Called with s->lock held. */
1139 static int coroutine_fn
qcow2_do_open(BlockDriverState
*bs
, QDict
*options
,
1140 int flags
, Error
**errp
)
1142 BDRVQcow2State
*s
= bs
->opaque
;
1143 unsigned int len
, i
;
1146 Error
*local_err
= NULL
;
1148 uint64_t l1_vm_state_index
;
1149 bool update_header
= false;
1150 bool header_updated
= false;
1152 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1154 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1157 be32_to_cpus(&header
.magic
);
1158 be32_to_cpus(&header
.version
);
1159 be64_to_cpus(&header
.backing_file_offset
);
1160 be32_to_cpus(&header
.backing_file_size
);
1161 be64_to_cpus(&header
.size
);
1162 be32_to_cpus(&header
.cluster_bits
);
1163 be32_to_cpus(&header
.crypt_method
);
1164 be64_to_cpus(&header
.l1_table_offset
);
1165 be32_to_cpus(&header
.l1_size
);
1166 be64_to_cpus(&header
.refcount_table_offset
);
1167 be32_to_cpus(&header
.refcount_table_clusters
);
1168 be64_to_cpus(&header
.snapshots_offset
);
1169 be32_to_cpus(&header
.nb_snapshots
);
1171 if (header
.magic
!= QCOW_MAGIC
) {
1172 error_setg(errp
, "Image is not in qcow2 format");
1176 if (header
.version
< 2 || header
.version
> 3) {
1177 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1182 s
->qcow_version
= header
.version
;
1184 /* Initialise cluster size */
1185 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1186 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1187 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1188 header
.cluster_bits
);
1193 s
->cluster_bits
= header
.cluster_bits
;
1194 s
->cluster_size
= 1 << s
->cluster_bits
;
1195 s
->cluster_sectors
= 1 << (s
->cluster_bits
- BDRV_SECTOR_BITS
);
1197 /* Initialise version 3 header fields */
1198 if (header
.version
== 2) {
1199 header
.incompatible_features
= 0;
1200 header
.compatible_features
= 0;
1201 header
.autoclear_features
= 0;
1202 header
.refcount_order
= 4;
1203 header
.header_length
= 72;
1205 be64_to_cpus(&header
.incompatible_features
);
1206 be64_to_cpus(&header
.compatible_features
);
1207 be64_to_cpus(&header
.autoclear_features
);
1208 be32_to_cpus(&header
.refcount_order
);
1209 be32_to_cpus(&header
.header_length
);
1211 if (header
.header_length
< 104) {
1212 error_setg(errp
, "qcow2 header too short");
1218 if (header
.header_length
> s
->cluster_size
) {
1219 error_setg(errp
, "qcow2 header exceeds cluster size");
1224 if (header
.header_length
> sizeof(header
)) {
1225 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1226 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1227 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1228 s
->unknown_header_fields_size
);
1230 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1236 if (header
.backing_file_offset
> s
->cluster_size
) {
1237 error_setg(errp
, "Invalid backing file offset");
1242 if (header
.backing_file_offset
) {
1243 ext_end
= header
.backing_file_offset
;
1245 ext_end
= 1 << header
.cluster_bits
;
1248 /* Handle feature bits */
1249 s
->incompatible_features
= header
.incompatible_features
;
1250 s
->compatible_features
= header
.compatible_features
;
1251 s
->autoclear_features
= header
.autoclear_features
;
1253 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1254 void *feature_table
= NULL
;
1255 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1256 &feature_table
, flags
, NULL
, NULL
);
1257 report_unsupported_feature(errp
, feature_table
,
1258 s
->incompatible_features
&
1259 ~QCOW2_INCOMPAT_MASK
);
1261 g_free(feature_table
);
1265 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1266 /* Corrupt images may not be written to unless they are being repaired
1268 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1269 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1276 /* Check support for various header values */
1277 if (header
.refcount_order
> 6) {
1278 error_setg(errp
, "Reference count entry width too large; may not "
1283 s
->refcount_order
= header
.refcount_order
;
1284 s
->refcount_bits
= 1 << s
->refcount_order
;
1285 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1286 s
->refcount_max
+= s
->refcount_max
- 1;
1288 s
->crypt_method_header
= header
.crypt_method
;
1289 if (s
->crypt_method_header
) {
1290 if (bdrv_uses_whitelist() &&
1291 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1293 "Use of AES-CBC encrypted qcow2 images is no longer "
1294 "supported in system emulators");
1295 error_append_hint(errp
,
1296 "You can use 'qemu-img convert' to convert your "
1297 "image to an alternative supported format, such "
1298 "as unencrypted qcow2, or raw with the LUKS "
1299 "format instead.\n");
1304 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1305 s
->crypt_physical_offset
= false;
1307 /* Assuming LUKS and any future crypt methods we
1308 * add will all use physical offsets, due to the
1309 * fact that the alternative is insecure... */
1310 s
->crypt_physical_offset
= true;
1313 bs
->encrypted
= true;
1316 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
1317 s
->l2_size
= 1 << s
->l2_bits
;
1318 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1319 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1320 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1321 bs
->total_sectors
= header
.size
/ 512;
1322 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1323 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1324 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1326 s
->refcount_table_offset
= header
.refcount_table_offset
;
1327 s
->refcount_table_size
=
1328 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1330 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1331 error_setg(errp
, "Image does not contain a reference count table");
1336 ret
= qcow2_validate_table(bs
, s
->refcount_table_offset
,
1337 header
.refcount_table_clusters
,
1338 s
->cluster_size
, QCOW_MAX_REFTABLE_SIZE
,
1339 "Reference count table", errp
);
1344 /* The total size in bytes of the snapshot table is checked in
1345 * qcow2_read_snapshots() because the size of each snapshot is
1346 * variable and we don't know it yet.
1347 * Here we only check the offset and number of snapshots. */
1348 ret
= qcow2_validate_table(bs
, header
.snapshots_offset
,
1349 header
.nb_snapshots
,
1350 sizeof(QCowSnapshotHeader
),
1351 sizeof(QCowSnapshotHeader
) * QCOW_MAX_SNAPSHOTS
,
1352 "Snapshot table", errp
);
1357 /* read the level 1 table */
1358 ret
= qcow2_validate_table(bs
, header
.l1_table_offset
,
1359 header
.l1_size
, sizeof(uint64_t),
1360 QCOW_MAX_L1_SIZE
, "Active L1 table", errp
);
1364 s
->l1_size
= header
.l1_size
;
1365 s
->l1_table_offset
= header
.l1_table_offset
;
1367 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1368 if (l1_vm_state_index
> INT_MAX
) {
1369 error_setg(errp
, "Image is too big");
1373 s
->l1_vm_state_index
= l1_vm_state_index
;
1375 /* the L1 table must contain at least enough entries to put
1376 header.size bytes */
1377 if (s
->l1_size
< s
->l1_vm_state_index
) {
1378 error_setg(errp
, "L1 table is too small");
1383 if (s
->l1_size
> 0) {
1384 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1385 ROUND_UP(s
->l1_size
* sizeof(uint64_t), 512));
1386 if (s
->l1_table
== NULL
) {
1387 error_setg(errp
, "Could not allocate L1 table");
1391 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1392 s
->l1_size
* sizeof(uint64_t));
1394 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1397 for(i
= 0;i
< s
->l1_size
; i
++) {
1398 be64_to_cpus(&s
->l1_table
[i
]);
1402 /* Parse driver-specific options */
1403 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1408 s
->cluster_cache_offset
= -1;
1411 ret
= qcow2_refcount_init(bs
);
1413 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1417 QLIST_INIT(&s
->cluster_allocs
);
1418 QTAILQ_INIT(&s
->discards
);
1420 /* read qcow2 extensions */
1421 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1422 flags
, &update_header
, &local_err
)) {
1423 error_propagate(errp
, local_err
);
1428 /* qcow2_read_extension may have set up the crypto context
1429 * if the crypt method needs a header region, some methods
1430 * don't need header extensions, so must check here
1432 if (s
->crypt_method_header
&& !s
->crypto
) {
1433 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1434 unsigned int cflags
= 0;
1435 if (flags
& BDRV_O_NO_IO
) {
1436 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1438 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1439 NULL
, NULL
, cflags
, errp
);
1444 } else if (!(flags
& BDRV_O_NO_IO
)) {
1445 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1446 s
->crypt_method_header
);
1452 /* read the backing file name */
1453 if (header
.backing_file_offset
!= 0) {
1454 len
= header
.backing_file_size
;
1455 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1456 len
>= sizeof(bs
->backing_file
)) {
1457 error_setg(errp
, "Backing file name too long");
1461 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1462 bs
->backing_file
, len
);
1464 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1467 bs
->backing_file
[len
] = '\0';
1468 s
->image_backing_file
= g_strdup(bs
->backing_file
);
1471 /* Internal snapshots */
1472 s
->snapshots_offset
= header
.snapshots_offset
;
1473 s
->nb_snapshots
= header
.nb_snapshots
;
1475 ret
= qcow2_read_snapshots(bs
);
1477 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1481 /* Clear unknown autoclear feature bits */
1482 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1484 update_header
&& !bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
);
1485 if (update_header
) {
1486 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1489 if (s
->dirty_bitmaps_loaded
) {
1490 /* It's some kind of reopen. There are no known cases where we need to
1491 * reload bitmaps in such a situation, so it's safer to skip them.
1493 * Moreover, if we have some readonly bitmaps and we are reopening for
1494 * rw we should reopen bitmaps correspondingly.
1496 if (bdrv_has_readonly_bitmaps(bs
) &&
1497 !bdrv_is_read_only(bs
) && !(bdrv_get_flags(bs
) & BDRV_O_INACTIVE
))
1499 qcow2_reopen_bitmaps_rw_hint(bs
, &header_updated
, &local_err
);
1502 header_updated
= qcow2_load_dirty_bitmaps(bs
, &local_err
);
1503 s
->dirty_bitmaps_loaded
= true;
1505 update_header
= update_header
&& !header_updated
;
1506 if (local_err
!= NULL
) {
1507 error_propagate(errp
, local_err
);
1512 if (update_header
) {
1513 ret
= qcow2_update_header(bs
);
1515 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1520 bs
->supported_zero_flags
= header
.version
>= 3 ? BDRV_REQ_MAY_UNMAP
: 0;
1522 /* Repair image if dirty */
1523 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1524 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1525 BdrvCheckResult result
= {0};
1527 ret
= qcow2_co_check_locked(bs
, &result
,
1528 BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1529 if (ret
< 0 || result
.check_errors
) {
1533 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1540 BdrvCheckResult result
= {0};
1541 qcow2_check_refcounts(bs
, &result
, 0);
1547 g_free(s
->unknown_header_fields
);
1548 cleanup_unknown_header_ext(bs
);
1549 qcow2_free_snapshots(bs
);
1550 qcow2_refcount_close(bs
);
1551 qemu_vfree(s
->l1_table
);
1552 /* else pre-write overlap checks in cache_destroy may crash */
1554 cache_clean_timer_del(bs
);
1555 if (s
->l2_table_cache
) {
1556 qcow2_cache_destroy(s
->l2_table_cache
);
1558 if (s
->refcount_block_cache
) {
1559 qcow2_cache_destroy(s
->refcount_block_cache
);
1561 qcrypto_block_free(s
->crypto
);
1562 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1566 typedef struct QCow2OpenCo
{
1567 BlockDriverState
*bs
;
1574 static void coroutine_fn
qcow2_open_entry(void *opaque
)
1576 QCow2OpenCo
*qoc
= opaque
;
1577 BDRVQcow2State
*s
= qoc
->bs
->opaque
;
1579 qemu_co_mutex_lock(&s
->lock
);
1580 qoc
->ret
= qcow2_do_open(qoc
->bs
, qoc
->options
, qoc
->flags
, qoc
->errp
);
1581 qemu_co_mutex_unlock(&s
->lock
);
1584 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1587 BDRVQcow2State
*s
= bs
->opaque
;
1596 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1602 /* Initialise locks */
1603 qemu_co_mutex_init(&s
->lock
);
1605 if (qemu_in_coroutine()) {
1606 /* From bdrv_co_create. */
1607 qcow2_open_entry(&qoc
);
1609 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry
, &qoc
));
1610 BDRV_POLL_WHILE(bs
, qoc
.ret
== -EINPROGRESS
);
1615 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1617 BDRVQcow2State
*s
= bs
->opaque
;
1619 if (bs
->encrypted
) {
1620 /* Encryption works on a sector granularity */
1621 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1623 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1624 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1627 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1628 BlockReopenQueue
*queue
, Error
**errp
)
1630 Qcow2ReopenState
*r
;
1633 r
= g_new0(Qcow2ReopenState
, 1);
1636 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1637 state
->flags
, errp
);
1642 /* We need to write out any unwritten data if we reopen read-only. */
1643 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1644 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1649 ret
= bdrv_flush(state
->bs
);
1654 ret
= qcow2_mark_clean(state
->bs
);
1663 qcow2_update_options_abort(state
->bs
, r
);
1668 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1670 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1671 g_free(state
->opaque
);
1674 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1676 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1677 g_free(state
->opaque
);
1680 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1682 bool has_new_overlap_template
=
1683 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1684 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1685 bool has_new_total_cache_size
=
1686 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1687 bool has_all_cache_options
;
1689 /* New overlap template overrides all old overlap options */
1690 if (has_new_overlap_template
) {
1691 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1692 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1693 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1694 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1695 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1696 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1697 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1698 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1699 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1700 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1703 /* New total cache size overrides all old options */
1704 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1705 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1706 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1709 qdict_join(options
, old_options
, false);
1712 * If after merging all cache size options are set, an old total size is
1713 * overwritten. Do keep all options, however, if all three are new. The
1714 * resulting error message is what we want to happen.
1716 has_all_cache_options
=
1717 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1718 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1719 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1721 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1722 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1726 static int coroutine_fn
qcow2_co_block_status(BlockDriverState
*bs
,
1728 int64_t offset
, int64_t count
,
1729 int64_t *pnum
, int64_t *map
,
1730 BlockDriverState
**file
)
1732 BDRVQcow2State
*s
= bs
->opaque
;
1733 uint64_t cluster_offset
;
1734 int index_in_cluster
, ret
;
1738 bytes
= MIN(INT_MAX
, count
);
1739 qemu_co_mutex_lock(&s
->lock
);
1740 ret
= qcow2_get_cluster_offset(bs
, offset
, &bytes
, &cluster_offset
);
1741 qemu_co_mutex_unlock(&s
->lock
);
1748 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1750 index_in_cluster
= offset
& (s
->cluster_size
- 1);
1751 *map
= cluster_offset
| index_in_cluster
;
1752 *file
= bs
->file
->bs
;
1753 status
|= BDRV_BLOCK_OFFSET_VALID
;
1755 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1756 status
|= BDRV_BLOCK_ZERO
;
1757 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1758 status
|= BDRV_BLOCK_DATA
;
1763 static coroutine_fn
int qcow2_handle_l2meta(BlockDriverState
*bs
,
1764 QCowL2Meta
**pl2meta
,
1768 QCowL2Meta
*l2meta
= *pl2meta
;
1770 while (l2meta
!= NULL
) {
1774 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1779 qcow2_alloc_cluster_abort(bs
, l2meta
);
1782 /* Take the request off the list of running requests */
1783 if (l2meta
->nb_clusters
!= 0) {
1784 QLIST_REMOVE(l2meta
, next_in_flight
);
1787 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1789 next
= l2meta
->next
;
1798 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1799 uint64_t bytes
, QEMUIOVector
*qiov
,
1802 BDRVQcow2State
*s
= bs
->opaque
;
1803 int offset_in_cluster
;
1805 unsigned int cur_bytes
; /* number of bytes in current iteration */
1806 uint64_t cluster_offset
= 0;
1807 uint64_t bytes_done
= 0;
1808 QEMUIOVector hd_qiov
;
1809 uint8_t *cluster_data
= NULL
;
1811 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1813 qemu_co_mutex_lock(&s
->lock
);
1815 while (bytes
!= 0) {
1817 /* prepare next request */
1818 cur_bytes
= MIN(bytes
, INT_MAX
);
1820 cur_bytes
= MIN(cur_bytes
,
1821 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1824 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1829 offset_in_cluster
= offset_into_cluster(s
, offset
);
1831 qemu_iovec_reset(&hd_qiov
);
1832 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1835 case QCOW2_CLUSTER_UNALLOCATED
:
1838 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1839 qemu_co_mutex_unlock(&s
->lock
);
1840 ret
= bdrv_co_preadv(bs
->backing
, offset
, cur_bytes
,
1842 qemu_co_mutex_lock(&s
->lock
);
1847 /* Note: in this case, no need to wait */
1848 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1852 case QCOW2_CLUSTER_ZERO_PLAIN
:
1853 case QCOW2_CLUSTER_ZERO_ALLOC
:
1854 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1857 case QCOW2_CLUSTER_COMPRESSED
:
1858 /* add AIO support for compressed blocks ? */
1859 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1864 qemu_iovec_from_buf(&hd_qiov
, 0,
1865 s
->cluster_cache
+ offset_in_cluster
,
1869 case QCOW2_CLUSTER_NORMAL
:
1870 if ((cluster_offset
& 511) != 0) {
1875 if (bs
->encrypted
) {
1879 * For encrypted images, read everything into a temporary
1880 * contiguous buffer on which the AES functions can work.
1882 if (!cluster_data
) {
1884 qemu_try_blockalign(bs
->file
->bs
,
1885 QCOW_MAX_CRYPT_CLUSTERS
1887 if (cluster_data
== NULL
) {
1893 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1894 qemu_iovec_reset(&hd_qiov
);
1895 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1898 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1899 qemu_co_mutex_unlock(&s
->lock
);
1900 ret
= bdrv_co_preadv(bs
->file
,
1901 cluster_offset
+ offset_in_cluster
,
1902 cur_bytes
, &hd_qiov
, 0);
1903 qemu_co_mutex_lock(&s
->lock
);
1907 if (bs
->encrypted
) {
1909 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1910 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1911 if (qcrypto_block_decrypt(s
->crypto
,
1912 (s
->crypt_physical_offset
?
1913 cluster_offset
+ offset_in_cluster
:
1921 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1926 g_assert_not_reached();
1932 offset
+= cur_bytes
;
1933 bytes_done
+= cur_bytes
;
1938 qemu_co_mutex_unlock(&s
->lock
);
1940 qemu_iovec_destroy(&hd_qiov
);
1941 qemu_vfree(cluster_data
);
1946 /* Check if it's possible to merge a write request with the writing of
1947 * the data from the COW regions */
1948 static bool merge_cow(uint64_t offset
, unsigned bytes
,
1949 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
1953 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
1954 /* If both COW regions are empty then there's nothing to merge */
1955 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
1959 /* The data (middle) region must be immediately after the
1961 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
1965 /* The end region must be immediately after the data (middle)
1967 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
1971 /* Make sure that adding both COW regions to the QEMUIOVector
1972 * does not exceed IOV_MAX */
1973 if (hd_qiov
->niov
> IOV_MAX
- 2) {
1977 m
->data_qiov
= hd_qiov
;
1984 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1985 uint64_t bytes
, QEMUIOVector
*qiov
,
1988 BDRVQcow2State
*s
= bs
->opaque
;
1989 int offset_in_cluster
;
1991 unsigned int cur_bytes
; /* number of sectors in current iteration */
1992 uint64_t cluster_offset
;
1993 QEMUIOVector hd_qiov
;
1994 uint64_t bytes_done
= 0;
1995 uint8_t *cluster_data
= NULL
;
1996 QCowL2Meta
*l2meta
= NULL
;
1998 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
2000 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
2002 s
->cluster_cache_offset
= -1; /* disable compressed cache */
2004 qemu_co_mutex_lock(&s
->lock
);
2006 while (bytes
!= 0) {
2010 trace_qcow2_writev_start_part(qemu_coroutine_self());
2011 offset_in_cluster
= offset_into_cluster(s
, offset
);
2012 cur_bytes
= MIN(bytes
, INT_MAX
);
2013 if (bs
->encrypted
) {
2014 cur_bytes
= MIN(cur_bytes
,
2015 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
2016 - offset_in_cluster
);
2019 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2020 &cluster_offset
, &l2meta
);
2025 assert((cluster_offset
& 511) == 0);
2027 qemu_iovec_reset(&hd_qiov
);
2028 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
2030 if (bs
->encrypted
) {
2032 if (!cluster_data
) {
2033 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
2034 QCOW_MAX_CRYPT_CLUSTERS
2036 if (cluster_data
== NULL
) {
2042 assert(hd_qiov
.size
<=
2043 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2044 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
2046 if (qcrypto_block_encrypt(s
->crypto
,
2047 (s
->crypt_physical_offset
?
2048 cluster_offset
+ offset_in_cluster
:
2051 cur_bytes
, NULL
) < 0) {
2056 qemu_iovec_reset(&hd_qiov
);
2057 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
2060 ret
= qcow2_pre_write_overlap_check(bs
, 0,
2061 cluster_offset
+ offset_in_cluster
, cur_bytes
);
2066 /* If we need to do COW, check if it's possible to merge the
2067 * writing of the guest data together with that of the COW regions.
2068 * If it's not possible (or not necessary) then write the
2069 * guest data now. */
2070 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
2071 qemu_co_mutex_unlock(&s
->lock
);
2072 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
2073 trace_qcow2_writev_data(qemu_coroutine_self(),
2074 cluster_offset
+ offset_in_cluster
);
2075 ret
= bdrv_co_pwritev(bs
->file
,
2076 cluster_offset
+ offset_in_cluster
,
2077 cur_bytes
, &hd_qiov
, 0);
2078 qemu_co_mutex_lock(&s
->lock
);
2084 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
2090 offset
+= cur_bytes
;
2091 bytes_done
+= cur_bytes
;
2092 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2097 qcow2_handle_l2meta(bs
, &l2meta
, false);
2099 qemu_co_mutex_unlock(&s
->lock
);
2101 qemu_iovec_destroy(&hd_qiov
);
2102 qemu_vfree(cluster_data
);
2103 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2108 static int qcow2_inactivate(BlockDriverState
*bs
)
2110 BDRVQcow2State
*s
= bs
->opaque
;
2111 int ret
, result
= 0;
2112 Error
*local_err
= NULL
;
2114 qcow2_store_persistent_dirty_bitmaps(bs
, &local_err
);
2115 if (local_err
!= NULL
) {
2117 error_report_err(local_err
);
2118 error_report("Persistent bitmaps are lost for node '%s'",
2119 bdrv_get_device_or_node_name(bs
));
2122 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2125 error_report("Failed to flush the L2 table cache: %s",
2129 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2132 error_report("Failed to flush the refcount block cache: %s",
2137 qcow2_mark_clean(bs
);
2143 static void qcow2_close(BlockDriverState
*bs
)
2145 BDRVQcow2State
*s
= bs
->opaque
;
2146 qemu_vfree(s
->l1_table
);
2147 /* else pre-write overlap checks in cache_destroy may crash */
2150 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2151 qcow2_inactivate(bs
);
2154 cache_clean_timer_del(bs
);
2155 qcow2_cache_destroy(s
->l2_table_cache
);
2156 qcow2_cache_destroy(s
->refcount_block_cache
);
2158 qcrypto_block_free(s
->crypto
);
2161 g_free(s
->unknown_header_fields
);
2162 cleanup_unknown_header_ext(bs
);
2164 g_free(s
->image_backing_file
);
2165 g_free(s
->image_backing_format
);
2167 g_free(s
->cluster_cache
);
2168 qemu_vfree(s
->cluster_data
);
2169 qcow2_refcount_close(bs
);
2170 qcow2_free_snapshots(bs
);
2173 static void coroutine_fn
qcow2_co_invalidate_cache(BlockDriverState
*bs
,
2176 BDRVQcow2State
*s
= bs
->opaque
;
2177 int flags
= s
->flags
;
2178 QCryptoBlock
*crypto
= NULL
;
2180 Error
*local_err
= NULL
;
2184 * Backing files are read-only which makes all of their metadata immutable,
2185 * that means we don't have to worry about reopening them here.
2193 memset(s
, 0, sizeof(BDRVQcow2State
));
2194 options
= qdict_clone_shallow(bs
->options
);
2196 flags
&= ~BDRV_O_INACTIVE
;
2197 qemu_co_mutex_lock(&s
->lock
);
2198 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2199 qemu_co_mutex_unlock(&s
->lock
);
2200 qobject_unref(options
);
2202 error_propagate(errp
, local_err
);
2203 error_prepend(errp
, "Could not reopen qcow2 layer: ");
2206 } else if (ret
< 0) {
2207 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2215 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2216 size_t len
, size_t buflen
)
2218 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2219 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2221 if (buflen
< ext_len
) {
2225 *ext_backing_fmt
= (QCowExtension
) {
2226 .magic
= cpu_to_be32(magic
),
2227 .len
= cpu_to_be32(len
),
2231 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2238 * Updates the qcow2 header, including the variable length parts of it, i.e.
2239 * the backing file name and all extensions. qcow2 was not designed to allow
2240 * such changes, so if we run out of space (we can only use the first cluster)
2241 * this function may fail.
2243 * Returns 0 on success, -errno in error cases.
2245 int qcow2_update_header(BlockDriverState
*bs
)
2247 BDRVQcow2State
*s
= bs
->opaque
;
2250 size_t buflen
= s
->cluster_size
;
2252 uint64_t total_size
;
2253 uint32_t refcount_table_clusters
;
2254 size_t header_length
;
2255 Qcow2UnknownHeaderExtension
*uext
;
2257 buf
= qemu_blockalign(bs
, buflen
);
2259 /* Header structure */
2260 header
= (QCowHeader
*) buf
;
2262 if (buflen
< sizeof(*header
)) {
2267 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2268 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2269 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2271 *header
= (QCowHeader
) {
2272 /* Version 2 fields */
2273 .magic
= cpu_to_be32(QCOW_MAGIC
),
2274 .version
= cpu_to_be32(s
->qcow_version
),
2275 .backing_file_offset
= 0,
2276 .backing_file_size
= 0,
2277 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2278 .size
= cpu_to_be64(total_size
),
2279 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2280 .l1_size
= cpu_to_be32(s
->l1_size
),
2281 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2282 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2283 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2284 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2285 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2287 /* Version 3 fields */
2288 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2289 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2290 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2291 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2292 .header_length
= cpu_to_be32(header_length
),
2295 /* For older versions, write a shorter header */
2296 switch (s
->qcow_version
) {
2298 ret
= offsetof(QCowHeader
, incompatible_features
);
2301 ret
= sizeof(*header
);
2310 memset(buf
, 0, buflen
);
2312 /* Preserve any unknown field in the header */
2313 if (s
->unknown_header_fields_size
) {
2314 if (buflen
< s
->unknown_header_fields_size
) {
2319 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2320 buf
+= s
->unknown_header_fields_size
;
2321 buflen
-= s
->unknown_header_fields_size
;
2324 /* Backing file format header extension */
2325 if (s
->image_backing_format
) {
2326 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2327 s
->image_backing_format
,
2328 strlen(s
->image_backing_format
),
2338 /* Full disk encryption header pointer extension */
2339 if (s
->crypto_header
.offset
!= 0) {
2340 cpu_to_be64s(&s
->crypto_header
.offset
);
2341 cpu_to_be64s(&s
->crypto_header
.length
);
2342 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2343 &s
->crypto_header
, sizeof(s
->crypto_header
),
2345 be64_to_cpus(&s
->crypto_header
.offset
);
2346 be64_to_cpus(&s
->crypto_header
.length
);
2355 if (s
->qcow_version
>= 3) {
2356 Qcow2Feature features
[] = {
2358 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2359 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2360 .name
= "dirty bit",
2363 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2364 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2365 .name
= "corrupt bit",
2368 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2369 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2370 .name
= "lazy refcounts",
2374 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2375 features
, sizeof(features
), buflen
);
2383 /* Bitmap extension */
2384 if (s
->nb_bitmaps
> 0) {
2385 Qcow2BitmapHeaderExt bitmaps_header
= {
2386 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2387 .bitmap_directory_size
=
2388 cpu_to_be64(s
->bitmap_directory_size
),
2389 .bitmap_directory_offset
=
2390 cpu_to_be64(s
->bitmap_directory_offset
)
2392 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2393 &bitmaps_header
, sizeof(bitmaps_header
),
2402 /* Keep unknown header extensions */
2403 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2404 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2413 /* End of header extensions */
2414 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2422 /* Backing file name */
2423 if (s
->image_backing_file
) {
2424 size_t backing_file_len
= strlen(s
->image_backing_file
);
2426 if (buflen
< backing_file_len
) {
2431 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2432 strncpy(buf
, s
->image_backing_file
, buflen
);
2434 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2435 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2438 /* Write the new header */
2439 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2450 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2451 const char *backing_file
, const char *backing_fmt
)
2453 BDRVQcow2State
*s
= bs
->opaque
;
2455 if (backing_file
&& strlen(backing_file
) > 1023) {
2459 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2460 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2462 g_free(s
->image_backing_file
);
2463 g_free(s
->image_backing_format
);
2465 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2466 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2468 return qcow2_update_header(bs
);
2471 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2473 if (g_str_equal(encryptfmt
, "luks")) {
2474 return QCOW_CRYPT_LUKS
;
2475 } else if (g_str_equal(encryptfmt
, "aes")) {
2476 return QCOW_CRYPT_AES
;
2482 static int qcow2_set_up_encryption(BlockDriverState
*bs
,
2483 QCryptoBlockCreateOptions
*cryptoopts
,
2486 BDRVQcow2State
*s
= bs
->opaque
;
2487 QCryptoBlock
*crypto
= NULL
;
2490 switch (cryptoopts
->format
) {
2491 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
2492 fmt
= QCOW_CRYPT_LUKS
;
2494 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
2495 fmt
= QCOW_CRYPT_AES
;
2498 error_setg(errp
, "Crypto format not supported in qcow2");
2502 s
->crypt_method_header
= fmt
;
2504 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2505 qcow2_crypto_hdr_init_func
,
2506 qcow2_crypto_hdr_write_func
,
2512 ret
= qcow2_update_header(bs
);
2514 error_setg_errno(errp
, -ret
, "Could not write encryption header");
2520 qcrypto_block_free(crypto
);
2525 * Preallocates metadata structures for data clusters between @offset (in the
2526 * guest disk) and @new_length (which is thus generally the new guest disk
2529 * Returns: 0 on success, -errno on failure.
2531 static int coroutine_fn
preallocate_co(BlockDriverState
*bs
, uint64_t offset
,
2532 uint64_t new_length
)
2535 uint64_t host_offset
= 0;
2536 unsigned int cur_bytes
;
2540 assert(offset
<= new_length
);
2541 bytes
= new_length
- offset
;
2544 cur_bytes
= MIN(bytes
, INT_MAX
);
2545 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2546 &host_offset
, &meta
);
2552 QCowL2Meta
*next
= meta
->next
;
2554 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2556 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2557 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2561 /* There are no dependent requests, but we need to remove our
2562 * request from the list of in-flight requests */
2563 QLIST_REMOVE(meta
, next_in_flight
);
2569 /* TODO Preallocate data if requested */
2572 offset
+= cur_bytes
;
2576 * It is expected that the image file is large enough to actually contain
2577 * all of the allocated clusters (otherwise we get failing reads after
2578 * EOF). Extend the image to the last allocated sector.
2580 if (host_offset
!= 0) {
2582 ret
= bdrv_pwrite(bs
->file
, (host_offset
+ cur_bytes
) - 1,
2592 /* qcow2_refcount_metadata_size:
2593 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2594 * @cluster_size: size of a cluster, in bytes
2595 * @refcount_order: refcount bits power-of-2 exponent
2596 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2599 * Returns: Number of bytes required for refcount blocks and table metadata.
2601 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
2602 int refcount_order
, bool generous_increase
,
2603 uint64_t *refblock_count
)
2606 * Every host cluster is reference-counted, including metadata (even
2607 * refcount metadata is recursively included).
2609 * An accurate formula for the size of refcount metadata size is difficult
2610 * to derive. An easier method of calculation is finding the fixed point
2611 * where no further refcount blocks or table clusters are required to
2612 * reference count every cluster.
2614 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
2615 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
2616 int64_t table
= 0; /* number of refcount table clusters */
2617 int64_t blocks
= 0; /* number of refcount block clusters */
2623 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
2624 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
2625 n
= clusters
+ blocks
+ table
;
2627 if (n
== last
&& generous_increase
) {
2628 clusters
+= DIV_ROUND_UP(table
, 2);
2629 n
= 0; /* force another loop */
2630 generous_increase
= false;
2632 } while (n
!= last
);
2634 if (refblock_count
) {
2635 *refblock_count
= blocks
;
2638 return (blocks
+ table
) * cluster_size
;
2642 * qcow2_calc_prealloc_size:
2643 * @total_size: virtual disk size in bytes
2644 * @cluster_size: cluster size in bytes
2645 * @refcount_order: refcount bits power-of-2 exponent
2647 * Returns: Total number of bytes required for the fully allocated image
2648 * (including metadata).
2650 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
2651 size_t cluster_size
,
2654 int64_t meta_size
= 0;
2655 uint64_t nl1e
, nl2e
;
2656 int64_t aligned_total_size
= ROUND_UP(total_size
, cluster_size
);
2658 /* header: 1 cluster */
2659 meta_size
+= cluster_size
;
2661 /* total size of L2 tables */
2662 nl2e
= aligned_total_size
/ cluster_size
;
2663 nl2e
= ROUND_UP(nl2e
, cluster_size
/ sizeof(uint64_t));
2664 meta_size
+= nl2e
* sizeof(uint64_t);
2666 /* total size of L1 tables */
2667 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2668 nl1e
= ROUND_UP(nl1e
, cluster_size
/ sizeof(uint64_t));
2669 meta_size
+= nl1e
* sizeof(uint64_t);
2671 /* total size of refcount table and blocks */
2672 meta_size
+= qcow2_refcount_metadata_size(
2673 (meta_size
+ aligned_total_size
) / cluster_size
,
2674 cluster_size
, refcount_order
, false, NULL
);
2676 return meta_size
+ aligned_total_size
;
2679 static bool validate_cluster_size(size_t cluster_size
, Error
**errp
)
2681 int cluster_bits
= ctz32(cluster_size
);
2682 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2683 (1 << cluster_bits
) != cluster_size
)
2685 error_setg(errp
, "Cluster size must be a power of two between %d and "
2686 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2692 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
2694 size_t cluster_size
;
2696 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2697 DEFAULT_CLUSTER_SIZE
);
2698 if (!validate_cluster_size(cluster_size
, errp
)) {
2701 return cluster_size
;
2704 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
2709 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2711 ret
= 3; /* default */
2712 } else if (!strcmp(buf
, "0.10")) {
2714 } else if (!strcmp(buf
, "1.1")) {
2717 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2724 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
2727 uint64_t refcount_bits
;
2729 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
2730 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2731 error_setg(errp
, "Refcount width must be a power of two and may not "
2736 if (version
< 3 && refcount_bits
!= 16) {
2737 error_setg(errp
, "Different refcount widths than 16 bits require "
2738 "compatibility level 1.1 or above (use compat=1.1 or "
2743 return refcount_bits
;
2746 static int coroutine_fn
2747 qcow2_co_create(BlockdevCreateOptions
*create_options
, Error
**errp
)
2749 BlockdevCreateOptionsQcow2
*qcow2_opts
;
2753 * Open the image file and write a minimal qcow2 header.
2755 * We keep things simple and start with a zero-sized image. We also
2756 * do without refcount blocks or a L1 table for now. We'll fix the
2757 * inconsistency later.
2759 * We do need a refcount table because growing the refcount table means
2760 * allocating two new refcount blocks - the seconds of which would be at
2761 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2762 * size for any qcow2 image.
2764 BlockBackend
*blk
= NULL
;
2765 BlockDriverState
*bs
= NULL
;
2767 size_t cluster_size
;
2770 uint64_t* refcount_table
;
2771 Error
*local_err
= NULL
;
2774 assert(create_options
->driver
== BLOCKDEV_DRIVER_QCOW2
);
2775 qcow2_opts
= &create_options
->u
.qcow2
;
2777 bs
= bdrv_open_blockdev_ref(qcow2_opts
->file
, errp
);
2782 /* Validate options and set default values */
2783 if (!QEMU_IS_ALIGNED(qcow2_opts
->size
, BDRV_SECTOR_SIZE
)) {
2784 error_setg(errp
, "Image size must be a multiple of 512 bytes");
2789 if (qcow2_opts
->has_version
) {
2790 switch (qcow2_opts
->version
) {
2791 case BLOCKDEV_QCOW2_VERSION_V2
:
2794 case BLOCKDEV_QCOW2_VERSION_V3
:
2798 g_assert_not_reached();
2804 if (qcow2_opts
->has_cluster_size
) {
2805 cluster_size
= qcow2_opts
->cluster_size
;
2807 cluster_size
= DEFAULT_CLUSTER_SIZE
;
2810 if (!validate_cluster_size(cluster_size
, errp
)) {
2815 if (!qcow2_opts
->has_preallocation
) {
2816 qcow2_opts
->preallocation
= PREALLOC_MODE_OFF
;
2818 if (qcow2_opts
->has_backing_file
&&
2819 qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
)
2821 error_setg(errp
, "Backing file and preallocation cannot be used at "
2826 if (qcow2_opts
->has_backing_fmt
&& !qcow2_opts
->has_backing_file
) {
2827 error_setg(errp
, "Backing format cannot be used without backing file");
2832 if (!qcow2_opts
->has_lazy_refcounts
) {
2833 qcow2_opts
->lazy_refcounts
= false;
2835 if (version
< 3 && qcow2_opts
->lazy_refcounts
) {
2836 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2837 "level 1.1 and above (use version=v3 or greater)");
2842 if (!qcow2_opts
->has_refcount_bits
) {
2843 qcow2_opts
->refcount_bits
= 16;
2845 if (qcow2_opts
->refcount_bits
> 64 ||
2846 !is_power_of_2(qcow2_opts
->refcount_bits
))
2848 error_setg(errp
, "Refcount width must be a power of two and may not "
2853 if (version
< 3 && qcow2_opts
->refcount_bits
!= 16) {
2854 error_setg(errp
, "Different refcount widths than 16 bits require "
2855 "compatibility level 1.1 or above (use version=v3 or "
2860 refcount_order
= ctz32(qcow2_opts
->refcount_bits
);
2863 /* Create BlockBackend to write to the image */
2864 blk
= blk_new(BLK_PERM_WRITE
| BLK_PERM_RESIZE
, BLK_PERM_ALL
);
2865 ret
= blk_insert_bs(blk
, bs
, errp
);
2869 blk_set_allow_write_beyond_eof(blk
, true);
2871 /* Clear the protocol layer and preallocate it if necessary */
2872 ret
= blk_truncate(blk
, 0, PREALLOC_MODE_OFF
, errp
);
2877 if (qcow2_opts
->preallocation
== PREALLOC_MODE_FULL
||
2878 qcow2_opts
->preallocation
== PREALLOC_MODE_FALLOC
)
2880 int64_t prealloc_size
=
2881 qcow2_calc_prealloc_size(qcow2_opts
->size
, cluster_size
,
2884 ret
= blk_truncate(blk
, prealloc_size
, qcow2_opts
->preallocation
, errp
);
2890 /* Write the header */
2891 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2892 header
= g_malloc0(cluster_size
);
2893 *header
= (QCowHeader
) {
2894 .magic
= cpu_to_be32(QCOW_MAGIC
),
2895 .version
= cpu_to_be32(version
),
2896 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
2897 .size
= cpu_to_be64(0),
2898 .l1_table_offset
= cpu_to_be64(0),
2899 .l1_size
= cpu_to_be32(0),
2900 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2901 .refcount_table_clusters
= cpu_to_be32(1),
2902 .refcount_order
= cpu_to_be32(refcount_order
),
2903 .header_length
= cpu_to_be32(sizeof(*header
)),
2906 /* We'll update this to correct value later */
2907 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2909 if (qcow2_opts
->lazy_refcounts
) {
2910 header
->compatible_features
|=
2911 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2914 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2917 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2921 /* Write a refcount table with one refcount block */
2922 refcount_table
= g_malloc0(2 * cluster_size
);
2923 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2924 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2925 g_free(refcount_table
);
2928 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2936 * And now open the image and make it consistent first (i.e. increase the
2937 * refcount of the cluster that is occupied by the header and the refcount
2940 options
= qdict_new();
2941 qdict_put_str(options
, "driver", "qcow2");
2942 qdict_put_str(options
, "file", bs
->node_name
);
2943 blk
= blk_new_open(NULL
, NULL
, options
,
2944 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
2947 error_propagate(errp
, local_err
);
2952 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2954 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2955 "header and refcount table");
2958 } else if (ret
!= 0) {
2959 error_report("Huh, first cluster in empty image is already in use?");
2963 /* Create a full header (including things like feature table) */
2964 ret
= qcow2_update_header(blk_bs(blk
));
2966 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
2970 /* Okay, now that we have a valid image, let's give it the right size */
2971 ret
= blk_truncate(blk
, qcow2_opts
->size
, PREALLOC_MODE_OFF
, errp
);
2973 error_prepend(errp
, "Could not resize image: ");
2977 /* Want a backing file? There you go.*/
2978 if (qcow2_opts
->has_backing_file
) {
2979 const char *backing_format
= NULL
;
2981 if (qcow2_opts
->has_backing_fmt
) {
2982 backing_format
= BlockdevDriver_str(qcow2_opts
->backing_fmt
);
2985 ret
= bdrv_change_backing_file(blk_bs(blk
), qcow2_opts
->backing_file
,
2988 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
2989 "with format '%s'", qcow2_opts
->backing_file
,
2995 /* Want encryption? There you go. */
2996 if (qcow2_opts
->has_encrypt
) {
2997 ret
= qcow2_set_up_encryption(blk_bs(blk
), qcow2_opts
->encrypt
, errp
);
3003 /* And if we're supposed to preallocate metadata, do that now */
3004 if (qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
) {
3005 BDRVQcow2State
*s
= blk_bs(blk
)->opaque
;
3006 qemu_co_mutex_lock(&s
->lock
);
3007 ret
= preallocate_co(blk_bs(blk
), 0, qcow2_opts
->size
);
3008 qemu_co_mutex_unlock(&s
->lock
);
3011 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
3019 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3020 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3021 * have to setup decryption context. We're not doing any I/O on the top
3022 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3025 options
= qdict_new();
3026 qdict_put_str(options
, "driver", "qcow2");
3027 qdict_put_str(options
, "file", bs
->node_name
);
3028 blk
= blk_new_open(NULL
, NULL
, options
,
3029 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
3032 error_propagate(errp
, local_err
);
3044 static int coroutine_fn
qcow2_co_create_opts(const char *filename
, QemuOpts
*opts
,
3047 BlockdevCreateOptions
*create_options
= NULL
;
3050 BlockDriverState
*bs
= NULL
;
3051 Error
*local_err
= NULL
;
3055 /* Only the keyval visitor supports the dotted syntax needed for
3056 * encryption, so go through a QDict before getting a QAPI type. Ignore
3057 * options meant for the protocol layer so that the visitor doesn't
3059 qdict
= qemu_opts_to_qdict_filtered(opts
, NULL
, bdrv_qcow2
.create_opts
,
3062 /* Handle encryption options */
3063 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT
);
3064 if (val
&& !strcmp(val
, "on")) {
3065 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT
, "qcow");
3066 } else if (val
&& !strcmp(val
, "off")) {
3067 qdict_del(qdict
, BLOCK_OPT_ENCRYPT
);
3070 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
);
3071 if (val
&& !strcmp(val
, "aes")) {
3072 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
, "qcow");
3075 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3076 * version=v2/v3 below. */
3077 val
= qdict_get_try_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
);
3078 if (val
&& !strcmp(val
, "0.10")) {
3079 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v2");
3080 } else if (val
&& !strcmp(val
, "1.1")) {
3081 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v3");
3084 /* Change legacy command line options into QMP ones */
3085 static const QDictRenames opt_renames
[] = {
3086 { BLOCK_OPT_BACKING_FILE
, "backing-file" },
3087 { BLOCK_OPT_BACKING_FMT
, "backing-fmt" },
3088 { BLOCK_OPT_CLUSTER_SIZE
, "cluster-size" },
3089 { BLOCK_OPT_LAZY_REFCOUNTS
, "lazy-refcounts" },
3090 { BLOCK_OPT_REFCOUNT_BITS
, "refcount-bits" },
3091 { BLOCK_OPT_ENCRYPT
, BLOCK_OPT_ENCRYPT_FORMAT
},
3092 { BLOCK_OPT_COMPAT_LEVEL
, "version" },
3096 if (!qdict_rename_keys(qdict
, opt_renames
, errp
)) {
3101 /* Create and open the file (protocol layer) */
3102 ret
= bdrv_create_file(filename
, opts
, errp
);
3107 bs
= bdrv_open(filename
, NULL
, NULL
,
3108 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
, errp
);
3114 /* Set 'driver' and 'node' options */
3115 qdict_put_str(qdict
, "driver", "qcow2");
3116 qdict_put_str(qdict
, "file", bs
->node_name
);
3118 /* Now get the QAPI type BlockdevCreateOptions */
3119 v
= qobject_input_visitor_new_flat_confused(qdict
, errp
);
3125 visit_type_BlockdevCreateOptions(v
, NULL
, &create_options
, &local_err
);
3129 error_propagate(errp
, local_err
);
3134 /* Silently round up size */
3135 create_options
->u
.qcow2
.size
= ROUND_UP(create_options
->u
.qcow2
.size
,
3138 /* Create the qcow2 image (format layer) */
3139 ret
= qcow2_co_create(create_options
, errp
);
3146 qobject_unref(qdict
);
3148 qapi_free_BlockdevCreateOptions(create_options
);
3153 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3158 /* Clamp to image length, before checking status of underlying sectors */
3159 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3160 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3166 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3167 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3170 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3171 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3174 BDRVQcow2State
*s
= bs
->opaque
;
3176 uint32_t head
= offset
% s
->cluster_size
;
3177 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3179 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3180 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3188 assert(head
+ bytes
<= s
->cluster_size
);
3190 /* check whether remainder of cluster already reads as zero */
3191 if (!(is_zero(bs
, offset
- head
, head
) &&
3192 is_zero(bs
, offset
+ bytes
,
3193 tail
? s
->cluster_size
- tail
: 0))) {
3197 qemu_co_mutex_lock(&s
->lock
);
3198 /* We can have new write after previous check */
3199 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3200 bytes
= s
->cluster_size
;
3201 nr
= s
->cluster_size
;
3202 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3203 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3204 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3205 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3206 qemu_co_mutex_unlock(&s
->lock
);
3210 qemu_co_mutex_lock(&s
->lock
);
3213 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3215 /* Whatever is left can use real zero clusters */
3216 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3217 qemu_co_mutex_unlock(&s
->lock
);
3222 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3223 int64_t offset
, int bytes
)
3226 BDRVQcow2State
*s
= bs
->opaque
;
3228 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3229 assert(bytes
< s
->cluster_size
);
3230 /* Ignore partial clusters, except for the special case of the
3231 * complete partial cluster at the end of an unaligned file */
3232 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3233 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3238 qemu_co_mutex_lock(&s
->lock
);
3239 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3241 qemu_co_mutex_unlock(&s
->lock
);
3245 static int coroutine_fn
3246 qcow2_co_copy_range_from(BlockDriverState
*bs
,
3247 BdrvChild
*src
, uint64_t src_offset
,
3248 BdrvChild
*dst
, uint64_t dst_offset
,
3249 uint64_t bytes
, BdrvRequestFlags flags
)
3251 BDRVQcow2State
*s
= bs
->opaque
;
3253 unsigned int cur_bytes
; /* number of bytes in current iteration */
3254 BdrvChild
*child
= NULL
;
3255 BdrvRequestFlags cur_flags
;
3257 assert(!bs
->encrypted
);
3258 qemu_co_mutex_lock(&s
->lock
);
3260 while (bytes
!= 0) {
3261 uint64_t copy_offset
= 0;
3262 /* prepare next request */
3263 cur_bytes
= MIN(bytes
, INT_MAX
);
3266 ret
= qcow2_get_cluster_offset(bs
, src_offset
, &cur_bytes
, ©_offset
);
3272 case QCOW2_CLUSTER_UNALLOCATED
:
3273 if (bs
->backing
&& bs
->backing
->bs
) {
3274 int64_t backing_length
= bdrv_getlength(bs
->backing
->bs
);
3275 if (src_offset
>= backing_length
) {
3276 cur_flags
|= BDRV_REQ_ZERO_WRITE
;
3278 child
= bs
->backing
;
3279 cur_bytes
= MIN(cur_bytes
, backing_length
- src_offset
);
3280 copy_offset
= src_offset
;
3283 cur_flags
|= BDRV_REQ_ZERO_WRITE
;
3287 case QCOW2_CLUSTER_ZERO_PLAIN
:
3288 case QCOW2_CLUSTER_ZERO_ALLOC
:
3289 cur_flags
|= BDRV_REQ_ZERO_WRITE
;
3292 case QCOW2_CLUSTER_COMPRESSED
:
3297 case QCOW2_CLUSTER_NORMAL
:
3299 copy_offset
+= offset_into_cluster(s
, src_offset
);
3300 if ((copy_offset
& 511) != 0) {
3309 qemu_co_mutex_unlock(&s
->lock
);
3310 ret
= bdrv_co_copy_range_from(child
,
3313 cur_bytes
, cur_flags
);
3314 qemu_co_mutex_lock(&s
->lock
);
3320 src_offset
+= cur_bytes
;
3321 dst_offset
+= cur_bytes
;
3326 qemu_co_mutex_unlock(&s
->lock
);
3330 static int coroutine_fn
3331 qcow2_co_copy_range_to(BlockDriverState
*bs
,
3332 BdrvChild
*src
, uint64_t src_offset
,
3333 BdrvChild
*dst
, uint64_t dst_offset
,
3334 uint64_t bytes
, BdrvRequestFlags flags
)
3336 BDRVQcow2State
*s
= bs
->opaque
;
3337 int offset_in_cluster
;
3339 unsigned int cur_bytes
; /* number of sectors in current iteration */
3340 uint64_t cluster_offset
;
3341 uint8_t *cluster_data
= NULL
;
3342 QCowL2Meta
*l2meta
= NULL
;
3344 assert(!bs
->encrypted
);
3345 s
->cluster_cache_offset
= -1; /* disable compressed cache */
3347 qemu_co_mutex_lock(&s
->lock
);
3349 while (bytes
!= 0) {
3353 offset_in_cluster
= offset_into_cluster(s
, dst_offset
);
3354 cur_bytes
= MIN(bytes
, INT_MAX
);
3357 * If src->bs == dst->bs, we could simply copy by incrementing
3358 * the refcnt, without copying user data.
3359 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3360 ret
= qcow2_alloc_cluster_offset(bs
, dst_offset
, &cur_bytes
,
3361 &cluster_offset
, &l2meta
);
3366 assert((cluster_offset
& 511) == 0);
3368 ret
= qcow2_pre_write_overlap_check(bs
, 0,
3369 cluster_offset
+ offset_in_cluster
, cur_bytes
);
3374 qemu_co_mutex_unlock(&s
->lock
);
3375 ret
= bdrv_co_copy_range_to(src
, src_offset
,
3377 cluster_offset
+ offset_in_cluster
,
3379 qemu_co_mutex_lock(&s
->lock
);
3384 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
3390 src_offset
+= cur_bytes
;
3391 dst_offset
+= cur_bytes
;
3396 qcow2_handle_l2meta(bs
, &l2meta
, false);
3398 qemu_co_mutex_unlock(&s
->lock
);
3400 qemu_vfree(cluster_data
);
3401 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
3406 static int coroutine_fn
qcow2_co_truncate(BlockDriverState
*bs
, int64_t offset
,
3407 PreallocMode prealloc
, Error
**errp
)
3409 BDRVQcow2State
*s
= bs
->opaque
;
3410 uint64_t old_length
;
3411 int64_t new_l1_size
;
3414 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3415 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3417 error_setg(errp
, "Unsupported preallocation mode '%s'",
3418 PreallocMode_str(prealloc
));
3423 error_setg(errp
, "The new size must be a multiple of 512");
3427 qemu_co_mutex_lock(&s
->lock
);
3429 /* cannot proceed if image has snapshots */
3430 if (s
->nb_snapshots
) {
3431 error_setg(errp
, "Can't resize an image which has snapshots");
3436 /* cannot proceed if image has bitmaps */
3437 if (s
->nb_bitmaps
) {
3438 /* TODO: resize bitmaps in the image */
3439 error_setg(errp
, "Can't resize an image which has bitmaps");
3444 old_length
= bs
->total_sectors
* 512;
3445 new_l1_size
= size_to_l1(s
, offset
);
3447 if (offset
< old_length
) {
3448 int64_t last_cluster
, old_file_size
;
3449 if (prealloc
!= PREALLOC_MODE_OFF
) {
3451 "Preallocation can't be used for shrinking an image");
3456 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3457 old_length
- ROUND_UP(offset
,
3459 QCOW2_DISCARD_ALWAYS
, true);
3461 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3465 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
3467 error_setg_errno(errp
, -ret
,
3468 "Failed to reduce the number of L2 tables");
3472 ret
= qcow2_shrink_reftable(bs
);
3474 error_setg_errno(errp
, -ret
,
3475 "Failed to discard unused refblocks");
3479 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3480 if (old_file_size
< 0) {
3481 error_setg_errno(errp
, -old_file_size
,
3482 "Failed to inquire current file length");
3483 ret
= old_file_size
;
3486 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
3487 if (last_cluster
< 0) {
3488 error_setg_errno(errp
, -last_cluster
,
3489 "Failed to find the last cluster");
3493 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
3494 Error
*local_err
= NULL
;
3496 bdrv_co_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
3497 PREALLOC_MODE_OFF
, &local_err
);
3499 warn_reportf_err(local_err
,
3500 "Failed to truncate the tail of the image: ");
3504 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
3506 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
3512 case PREALLOC_MODE_OFF
:
3515 case PREALLOC_MODE_METADATA
:
3516 ret
= preallocate_co(bs
, old_length
, offset
);
3518 error_setg_errno(errp
, -ret
, "Preallocation failed");
3523 case PREALLOC_MODE_FALLOC
:
3524 case PREALLOC_MODE_FULL
:
3526 int64_t allocation_start
, host_offset
, guest_offset
;
3527 int64_t clusters_allocated
;
3528 int64_t old_file_size
, new_file_size
;
3529 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
3531 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3532 if (old_file_size
< 0) {
3533 error_setg_errno(errp
, -old_file_size
,
3534 "Failed to inquire current file length");
3535 ret
= old_file_size
;
3538 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
3540 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
3543 /* This is an overestimation; we will not actually allocate space for
3544 * these in the file but just make sure the new refcount structures are
3545 * able to cover them so we will not have to allocate new refblocks
3546 * while entering the data blocks in the potentially new L2 tables.
3547 * (We do not actually care where the L2 tables are placed. Maybe they
3548 * are already allocated or they can be placed somewhere before
3549 * @old_file_size. It does not matter because they will be fully
3550 * allocated automatically, so they do not need to be covered by the
3551 * preallocation. All that matters is that we will not have to allocate
3552 * new refcount structures for them.) */
3553 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
3554 s
->cluster_size
/ sizeof(uint64_t));
3555 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3556 * table for a potential head/tail */
3559 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
3560 nb_new_data_clusters
+
3563 if (allocation_start
< 0) {
3564 error_setg_errno(errp
, -allocation_start
,
3565 "Failed to resize refcount structures");
3566 ret
= allocation_start
;
3570 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
3571 nb_new_data_clusters
);
3572 if (clusters_allocated
< 0) {
3573 error_setg_errno(errp
, -clusters_allocated
,
3574 "Failed to allocate data clusters");
3575 ret
= clusters_allocated
;
3579 assert(clusters_allocated
== nb_new_data_clusters
);
3581 /* Allocate the data area */
3582 new_file_size
= allocation_start
+
3583 nb_new_data_clusters
* s
->cluster_size
;
3584 ret
= bdrv_co_truncate(bs
->file
, new_file_size
, prealloc
, errp
);
3586 error_prepend(errp
, "Failed to resize underlying file: ");
3587 qcow2_free_clusters(bs
, allocation_start
,
3588 nb_new_data_clusters
* s
->cluster_size
,
3589 QCOW2_DISCARD_OTHER
);
3593 /* Create the necessary L2 entries */
3594 host_offset
= allocation_start
;
3595 guest_offset
= old_length
;
3596 while (nb_new_data_clusters
) {
3597 int64_t nb_clusters
= MIN(
3598 nb_new_data_clusters
,
3599 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
3600 QCowL2Meta allocation
= {
3601 .offset
= guest_offset
,
3602 .alloc_offset
= host_offset
,
3603 .nb_clusters
= nb_clusters
,
3605 qemu_co_queue_init(&allocation
.dependent_requests
);
3607 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
3609 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
3610 qcow2_free_clusters(bs
, host_offset
,
3611 nb_new_data_clusters
* s
->cluster_size
,
3612 QCOW2_DISCARD_OTHER
);
3616 guest_offset
+= nb_clusters
* s
->cluster_size
;
3617 host_offset
+= nb_clusters
* s
->cluster_size
;
3618 nb_new_data_clusters
-= nb_clusters
;
3624 g_assert_not_reached();
3627 if (prealloc
!= PREALLOC_MODE_OFF
) {
3628 /* Flush metadata before actually changing the image size */
3629 ret
= qcow2_write_caches(bs
);
3631 error_setg_errno(errp
, -ret
,
3632 "Failed to flush the preallocated area to disk");
3637 /* write updated header.size */
3638 offset
= cpu_to_be64(offset
);
3639 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
3640 &offset
, sizeof(uint64_t));
3642 error_setg_errno(errp
, -ret
, "Failed to update the image size");
3646 s
->l1_vm_state_index
= new_l1_size
;
3649 qemu_co_mutex_unlock(&s
->lock
);
3653 /* XXX: put compressed sectors first, then all the cluster aligned
3654 tables to avoid losing bytes in alignment */
3655 static coroutine_fn
int
3656 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
3657 uint64_t bytes
, QEMUIOVector
*qiov
)
3659 BDRVQcow2State
*s
= bs
->opaque
;
3660 QEMUIOVector hd_qiov
;
3664 uint8_t *buf
, *out_buf
;
3665 int64_t cluster_offset
;
3668 /* align end of file to a sector boundary to ease reading with
3669 sector based I/Os */
3670 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
3671 if (cluster_offset
< 0) {
3672 return cluster_offset
;
3674 return bdrv_co_truncate(bs
->file
, cluster_offset
, PREALLOC_MODE_OFF
,
3678 if (offset_into_cluster(s
, offset
)) {
3682 buf
= qemu_blockalign(bs
, s
->cluster_size
);
3683 if (bytes
!= s
->cluster_size
) {
3684 if (bytes
> s
->cluster_size
||
3685 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
3690 /* Zero-pad last write if image size is not cluster aligned */
3691 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
3693 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
3695 out_buf
= g_malloc(s
->cluster_size
);
3697 /* best compression, small window, no zlib header */
3698 memset(&strm
, 0, sizeof(strm
));
3699 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
3701 9, Z_DEFAULT_STRATEGY
);
3707 strm
.avail_in
= s
->cluster_size
;
3708 strm
.next_in
= (uint8_t *)buf
;
3709 strm
.avail_out
= s
->cluster_size
;
3710 strm
.next_out
= out_buf
;
3712 ret
= deflate(&strm
, Z_FINISH
);
3713 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
3718 out_len
= strm
.next_out
- out_buf
;
3722 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
3723 /* could not compress: write normal cluster */
3724 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
3731 qemu_co_mutex_lock(&s
->lock
);
3733 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
3734 if (!cluster_offset
) {
3735 qemu_co_mutex_unlock(&s
->lock
);
3739 cluster_offset
&= s
->cluster_offset_mask
;
3741 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
3742 qemu_co_mutex_unlock(&s
->lock
);
3747 iov
= (struct iovec
) {
3748 .iov_base
= out_buf
,
3751 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
3753 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
3754 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
3766 static int make_completely_empty(BlockDriverState
*bs
)
3768 BDRVQcow2State
*s
= bs
->opaque
;
3769 Error
*local_err
= NULL
;
3770 int ret
, l1_clusters
;
3772 uint64_t *new_reftable
= NULL
;
3773 uint64_t rt_entry
, l1_size2
;
3776 uint64_t reftable_offset
;
3777 uint32_t reftable_clusters
;
3778 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
3780 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
3785 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
3790 /* Refcounts will be broken utterly */
3791 ret
= qcow2_mark_dirty(bs
);
3796 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3798 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3799 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
3801 /* After this call, neither the in-memory nor the on-disk refcount
3802 * information accurately describe the actual references */
3804 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
3805 l1_clusters
* s
->cluster_size
, 0);
3807 goto fail_broken_refcounts
;
3809 memset(s
->l1_table
, 0, l1_size2
);
3811 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
3813 /* Overwrite enough clusters at the beginning of the sectors to place
3814 * the refcount table, a refcount block and the L1 table in; this may
3815 * overwrite parts of the existing refcount and L1 table, which is not
3816 * an issue because the dirty flag is set, complete data loss is in fact
3817 * desired and partial data loss is consequently fine as well */
3818 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
3819 (2 + l1_clusters
) * s
->cluster_size
, 0);
3820 /* This call (even if it failed overall) may have overwritten on-disk
3821 * refcount structures; in that case, the in-memory refcount information
3822 * will probably differ from the on-disk information which makes the BDS
3825 goto fail_broken_refcounts
;
3828 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3829 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
3831 /* "Create" an empty reftable (one cluster) directly after the image
3832 * header and an empty L1 table three clusters after the image header;
3833 * the cluster between those two will be used as the first refblock */
3834 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
3835 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
3836 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
3837 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
3838 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
3840 goto fail_broken_refcounts
;
3843 s
->l1_table_offset
= 3 * s
->cluster_size
;
3845 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
3846 if (!new_reftable
) {
3848 goto fail_broken_refcounts
;
3851 s
->refcount_table_offset
= s
->cluster_size
;
3852 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
3853 s
->max_refcount_table_index
= 0;
3855 g_free(s
->refcount_table
);
3856 s
->refcount_table
= new_reftable
;
3857 new_reftable
= NULL
;
3859 /* Now the in-memory refcount information again corresponds to the on-disk
3860 * information (reftable is empty and no refblocks (the refblock cache is
3861 * empty)); however, this means some clusters (e.g. the image header) are
3862 * referenced, but not refcounted, but the normal qcow2 code assumes that
3863 * the in-memory information is always correct */
3865 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
3867 /* Enter the first refblock into the reftable */
3868 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
3869 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
3870 &rt_entry
, sizeof(rt_entry
));
3872 goto fail_broken_refcounts
;
3874 s
->refcount_table
[0] = 2 * s
->cluster_size
;
3876 s
->free_cluster_index
= 0;
3877 assert(3 + l1_clusters
<= s
->refcount_block_size
);
3878 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
3881 goto fail_broken_refcounts
;
3882 } else if (offset
> 0) {
3883 error_report("First cluster in emptied image is in use");
3887 /* Now finally the in-memory information corresponds to the on-disk
3888 * structures and is correct */
3889 ret
= qcow2_mark_clean(bs
);
3894 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
3895 PREALLOC_MODE_OFF
, &local_err
);
3897 error_report_err(local_err
);
3903 fail_broken_refcounts
:
3904 /* The BDS is unusable at this point. If we wanted to make it usable, we
3905 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3906 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3907 * again. However, because the functions which could have caused this error
3908 * path to be taken are used by those functions as well, it's very likely
3909 * that that sequence will fail as well. Therefore, just eject the BDS. */
3913 g_free(new_reftable
);
3917 static int qcow2_make_empty(BlockDriverState
*bs
)
3919 BDRVQcow2State
*s
= bs
->opaque
;
3920 uint64_t offset
, end_offset
;
3921 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
3922 int l1_clusters
, ret
= 0;
3924 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3926 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
3927 3 + l1_clusters
<= s
->refcount_block_size
&&
3928 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
3929 /* The following function only works for qcow2 v3 images (it
3930 * requires the dirty flag) and only as long as there are no
3931 * features that reserve extra clusters (such as snapshots,
3932 * LUKS header, or persistent bitmaps), because it completely
3933 * empties the image. Furthermore, the L1 table and three
3934 * additional clusters (image header, refcount table, one
3935 * refcount block) have to fit inside one refcount block. */
3936 return make_completely_empty(bs
);
3939 /* This fallback code simply discards every active cluster; this is slow,
3940 * but works in all cases */
3941 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3942 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
3943 /* As this function is generally used after committing an external
3944 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3945 * default action for this kind of discard is to pass the discard,
3946 * which will ideally result in an actually smaller image file, as
3947 * is probably desired. */
3948 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
3949 QCOW2_DISCARD_SNAPSHOT
, true);
3958 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
3960 BDRVQcow2State
*s
= bs
->opaque
;
3963 qemu_co_mutex_lock(&s
->lock
);
3964 ret
= qcow2_write_caches(bs
);
3965 qemu_co_mutex_unlock(&s
->lock
);
3970 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
3973 Error
*local_err
= NULL
;
3974 BlockMeasureInfo
*info
;
3975 uint64_t required
= 0; /* bytes that contribute to required size */
3976 uint64_t virtual_size
; /* disk size as seen by guest */
3977 uint64_t refcount_bits
;
3979 size_t cluster_size
;
3982 PreallocMode prealloc
;
3983 bool has_backing_file
;
3985 /* Parse image creation options */
3986 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
3991 version
= qcow2_opt_get_version_del(opts
, &local_err
);
3996 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
4001 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
4002 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
4003 PREALLOC_MODE_OFF
, &local_err
);
4009 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
4010 has_backing_file
= !!optstr
;
4013 virtual_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
4014 virtual_size
= ROUND_UP(virtual_size
, cluster_size
);
4016 /* Check that virtual disk size is valid */
4017 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
4018 cluster_size
/ sizeof(uint64_t));
4019 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
4020 error_setg(&local_err
, "The image size is too large "
4021 "(try using a larger cluster size)");
4025 /* Account for input image */
4027 int64_t ssize
= bdrv_getlength(in_bs
);
4029 error_setg_errno(&local_err
, -ssize
,
4030 "Unable to get image virtual_size");
4034 virtual_size
= ROUND_UP(ssize
, cluster_size
);
4036 if (has_backing_file
) {
4037 /* We don't how much of the backing chain is shared by the input
4038 * image and the new image file. In the worst case the new image's
4039 * backing file has nothing in common with the input image. Be
4040 * conservative and assume all clusters need to be written.
4042 required
= virtual_size
;
4047 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
4050 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
4051 ssize
- offset
, &pnum
, NULL
,
4054 error_setg_errno(&local_err
, -ret
,
4055 "Unable to get block status");
4059 if (ret
& BDRV_BLOCK_ZERO
) {
4060 /* Skip zero regions (safe with no backing file) */
4061 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
4062 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
4063 /* Extend pnum to end of cluster for next iteration */
4064 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
4066 /* Count clusters we've seen */
4067 required
+= offset
% cluster_size
+ pnum
;
4073 /* Take into account preallocation. Nothing special is needed for
4074 * PREALLOC_MODE_METADATA since metadata is always counted.
4076 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
4077 required
= virtual_size
;
4080 info
= g_new(BlockMeasureInfo
, 1);
4081 info
->fully_allocated
=
4082 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
4083 ctz32(refcount_bits
));
4085 /* Remove data clusters that are not required. This overestimates the
4086 * required size because metadata needed for the fully allocated file is
4089 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
4093 error_propagate(errp
, local_err
);
4097 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
4099 BDRVQcow2State
*s
= bs
->opaque
;
4100 bdi
->unallocated_blocks_are_zero
= true;
4101 bdi
->cluster_size
= s
->cluster_size
;
4102 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
4106 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
4108 BDRVQcow2State
*s
= bs
->opaque
;
4109 ImageInfoSpecific
*spec_info
;
4110 QCryptoBlockInfo
*encrypt_info
= NULL
;
4112 if (s
->crypto
!= NULL
) {
4113 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &error_abort
);
4116 spec_info
= g_new(ImageInfoSpecific
, 1);
4117 *spec_info
= (ImageInfoSpecific
){
4118 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
4119 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
4121 if (s
->qcow_version
== 2) {
4122 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4123 .compat
= g_strdup("0.10"),
4124 .refcount_bits
= s
->refcount_bits
,
4126 } else if (s
->qcow_version
== 3) {
4127 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4128 .compat
= g_strdup("1.1"),
4129 .lazy_refcounts
= s
->compatible_features
&
4130 QCOW2_COMPAT_LAZY_REFCOUNTS
,
4131 .has_lazy_refcounts
= true,
4132 .corrupt
= s
->incompatible_features
&
4133 QCOW2_INCOMPAT_CORRUPT
,
4134 .has_corrupt
= true,
4135 .refcount_bits
= s
->refcount_bits
,
4138 /* if this assertion fails, this probably means a new version was
4139 * added without having it covered here */
4144 ImageInfoSpecificQCow2Encryption
*qencrypt
=
4145 g_new(ImageInfoSpecificQCow2Encryption
, 1);
4146 switch (encrypt_info
->format
) {
4147 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
4148 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
4150 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
4151 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
4152 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
4157 /* Since we did shallow copy above, erase any pointers
4158 * in the original info */
4159 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
4160 qapi_free_QCryptoBlockInfo(encrypt_info
);
4162 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
4163 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
4169 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4172 BDRVQcow2State
*s
= bs
->opaque
;
4174 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
4175 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
4176 qiov
->size
, qiov
, 0);
4179 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4182 BDRVQcow2State
*s
= bs
->opaque
;
4184 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
4185 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
4186 qiov
->size
, qiov
, 0);
4190 * Downgrades an image's version. To achieve this, any incompatible features
4191 * have to be removed.
4193 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
4194 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
4197 BDRVQcow2State
*s
= bs
->opaque
;
4198 int current_version
= s
->qcow_version
;
4201 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4202 assert(target_version
< current_version
);
4204 /* There are no other versions (now) that you can downgrade to */
4205 assert(target_version
== 2);
4207 if (s
->refcount_order
!= 4) {
4208 error_setg(errp
, "compat=0.10 requires refcount_bits=16");
4212 /* clear incompatible features */
4213 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
4214 ret
= qcow2_mark_clean(bs
);
4216 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
4221 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4222 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4223 * best thing to do anyway */
4225 if (s
->incompatible_features
) {
4226 error_setg(errp
, "Cannot downgrade an image with incompatible features "
4227 "%#" PRIx64
" set", s
->incompatible_features
);
4231 /* since we can ignore compatible features, we can set them to 0 as well */
4232 s
->compatible_features
= 0;
4233 /* if lazy refcounts have been used, they have already been fixed through
4234 * clearing the dirty flag */
4236 /* clearing autoclear features is trivial */
4237 s
->autoclear_features
= 0;
4239 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
4241 error_setg_errno(errp
, -ret
, "Failed to turn zero into data clusters");
4245 s
->qcow_version
= target_version
;
4246 ret
= qcow2_update_header(bs
);
4248 s
->qcow_version
= current_version
;
4249 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4255 typedef enum Qcow2AmendOperation
{
4256 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4257 * statically initialized to so that the helper CB can discern the first
4258 * invocation from an operation change */
4259 QCOW2_NO_OPERATION
= 0,
4261 QCOW2_CHANGING_REFCOUNT_ORDER
,
4263 } Qcow2AmendOperation
;
4265 typedef struct Qcow2AmendHelperCBInfo
{
4266 /* The code coordinating the amend operations should only modify
4267 * these four fields; the rest will be managed by the CB */
4268 BlockDriverAmendStatusCB
*original_status_cb
;
4269 void *original_cb_opaque
;
4271 Qcow2AmendOperation current_operation
;
4273 /* Total number of operations to perform (only set once) */
4274 int total_operations
;
4276 /* The following fields are managed by the CB */
4278 /* Number of operations completed */
4279 int operations_completed
;
4281 /* Cumulative offset of all completed operations */
4282 int64_t offset_completed
;
4284 Qcow2AmendOperation last_operation
;
4285 int64_t last_work_size
;
4286 } Qcow2AmendHelperCBInfo
;
4288 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
4289 int64_t operation_offset
,
4290 int64_t operation_work_size
, void *opaque
)
4292 Qcow2AmendHelperCBInfo
*info
= opaque
;
4293 int64_t current_work_size
;
4294 int64_t projected_work_size
;
4296 if (info
->current_operation
!= info
->last_operation
) {
4297 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
4298 info
->offset_completed
+= info
->last_work_size
;
4299 info
->operations_completed
++;
4302 info
->last_operation
= info
->current_operation
;
4305 assert(info
->total_operations
> 0);
4306 assert(info
->operations_completed
< info
->total_operations
);
4308 info
->last_work_size
= operation_work_size
;
4310 current_work_size
= info
->offset_completed
+ operation_work_size
;
4312 /* current_work_size is the total work size for (operations_completed + 1)
4313 * operations (which includes this one), so multiply it by the number of
4314 * operations not covered and divide it by the number of operations
4315 * covered to get a projection for the operations not covered */
4316 projected_work_size
= current_work_size
* (info
->total_operations
-
4317 info
->operations_completed
- 1)
4318 / (info
->operations_completed
+ 1);
4320 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
4321 current_work_size
+ projected_work_size
,
4322 info
->original_cb_opaque
);
4325 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
4326 BlockDriverAmendStatusCB
*status_cb
,
4330 BDRVQcow2State
*s
= bs
->opaque
;
4331 int old_version
= s
->qcow_version
, new_version
= old_version
;
4332 uint64_t new_size
= 0;
4333 const char *backing_file
= NULL
, *backing_format
= NULL
;
4334 bool lazy_refcounts
= s
->use_lazy_refcounts
;
4335 const char *compat
= NULL
;
4336 uint64_t cluster_size
= s
->cluster_size
;
4339 int refcount_bits
= s
->refcount_bits
;
4341 QemuOptDesc
*desc
= opts
->list
->desc
;
4342 Qcow2AmendHelperCBInfo helper_cb_info
;
4344 while (desc
&& desc
->name
) {
4345 if (!qemu_opt_find(opts
, desc
->name
)) {
4346 /* only change explicitly defined options */
4351 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
4352 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
4354 /* preserve default */
4355 } else if (!strcmp(compat
, "0.10")) {
4357 } else if (!strcmp(compat
, "1.1")) {
4360 error_setg(errp
, "Unknown compatibility level %s", compat
);
4363 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
4364 error_setg(errp
, "Cannot change preallocation mode");
4366 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
4367 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
4368 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
4369 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
4370 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
4371 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
4372 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
4373 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
4376 if (encrypt
!= !!s
->crypto
) {
4378 "Changing the encryption flag is not supported");
4381 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
4382 encformat
= qcow2_crypt_method_from_format(
4383 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
4385 if (encformat
!= s
->crypt_method_header
) {
4387 "Changing the encryption format is not supported");
4390 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
4392 "Changing the encryption parameters is not supported");
4394 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
4395 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
4397 if (cluster_size
!= s
->cluster_size
) {
4398 error_setg(errp
, "Changing the cluster size is not supported");
4401 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
4402 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
4404 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
4405 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
4408 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
4409 !is_power_of_2(refcount_bits
))
4411 error_setg(errp
, "Refcount width must be a power of two and "
4412 "may not exceed 64 bits");
4416 /* if this point is reached, this probably means a new option was
4417 * added without having it covered here */
4424 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
4425 .original_status_cb
= status_cb
,
4426 .original_cb_opaque
= cb_opaque
,
4427 .total_operations
= (new_version
< old_version
)
4428 + (s
->refcount_bits
!= refcount_bits
)
4431 /* Upgrade first (some features may require compat=1.1) */
4432 if (new_version
> old_version
) {
4433 s
->qcow_version
= new_version
;
4434 ret
= qcow2_update_header(bs
);
4436 s
->qcow_version
= old_version
;
4437 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4442 if (s
->refcount_bits
!= refcount_bits
) {
4443 int refcount_order
= ctz32(refcount_bits
);
4445 if (new_version
< 3 && refcount_bits
!= 16) {
4446 error_setg(errp
, "Refcount widths other than 16 bits require "
4447 "compatibility level 1.1 or above (use compat=1.1 or "
4452 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
4453 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
4454 &qcow2_amend_helper_cb
,
4455 &helper_cb_info
, errp
);
4461 if (backing_file
|| backing_format
) {
4462 ret
= qcow2_change_backing_file(bs
,
4463 backing_file
?: s
->image_backing_file
,
4464 backing_format
?: s
->image_backing_format
);
4466 error_setg_errno(errp
, -ret
, "Failed to change the backing file");
4471 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
4472 if (lazy_refcounts
) {
4473 if (new_version
< 3) {
4474 error_setg(errp
, "Lazy refcounts only supported with "
4475 "compatibility level 1.1 and above (use compat=1.1 "
4479 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4480 ret
= qcow2_update_header(bs
);
4482 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4483 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4486 s
->use_lazy_refcounts
= true;
4488 /* make image clean first */
4489 ret
= qcow2_mark_clean(bs
);
4491 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
4494 /* now disallow lazy refcounts */
4495 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4496 ret
= qcow2_update_header(bs
);
4498 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4499 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4502 s
->use_lazy_refcounts
= false;
4507 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
4508 ret
= blk_insert_bs(blk
, bs
, errp
);
4514 ret
= blk_truncate(blk
, new_size
, PREALLOC_MODE_OFF
, errp
);
4521 /* Downgrade last (so unsupported features can be removed before) */
4522 if (new_version
< old_version
) {
4523 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
4524 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
4525 &helper_cb_info
, errp
);
4535 * If offset or size are negative, respectively, they will not be included in
4536 * the BLOCK_IMAGE_CORRUPTED event emitted.
4537 * fatal will be ignored for read-only BDS; corruptions found there will always
4538 * be considered non-fatal.
4540 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
4541 int64_t size
, const char *message_format
, ...)
4543 BDRVQcow2State
*s
= bs
->opaque
;
4544 const char *node_name
;
4548 fatal
= fatal
&& bdrv_is_writable(bs
);
4550 if (s
->signaled_corruption
&&
4551 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
4556 va_start(ap
, message_format
);
4557 message
= g_strdup_vprintf(message_format
, ap
);
4561 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
4562 "corruption events will be suppressed\n", message
);
4564 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
4565 "corruption events will be suppressed\n", message
);
4568 node_name
= bdrv_get_node_name(bs
);
4569 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
4570 *node_name
!= '\0', node_name
,
4571 message
, offset
>= 0, offset
,
4573 fatal
, &error_abort
);
4577 qcow2_mark_corrupt(bs
);
4578 bs
->drv
= NULL
; /* make BDS unusable */
4581 s
->signaled_corruption
= true;
4584 static QemuOptsList qcow2_create_opts
= {
4585 .name
= "qcow2-create-opts",
4586 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
4589 .name
= BLOCK_OPT_SIZE
,
4590 .type
= QEMU_OPT_SIZE
,
4591 .help
= "Virtual disk size"
4594 .name
= BLOCK_OPT_COMPAT_LEVEL
,
4595 .type
= QEMU_OPT_STRING
,
4596 .help
= "Compatibility level (0.10 or 1.1)"
4599 .name
= BLOCK_OPT_BACKING_FILE
,
4600 .type
= QEMU_OPT_STRING
,
4601 .help
= "File name of a base image"
4604 .name
= BLOCK_OPT_BACKING_FMT
,
4605 .type
= QEMU_OPT_STRING
,
4606 .help
= "Image format of the base image"
4609 .name
= BLOCK_OPT_ENCRYPT
,
4610 .type
= QEMU_OPT_BOOL
,
4611 .help
= "Encrypt the image with format 'aes'. (Deprecated "
4612 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
4615 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
4616 .type
= QEMU_OPT_STRING
,
4617 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
4619 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4620 "ID of secret providing qcow AES key or LUKS passphrase"),
4621 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4622 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4623 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4624 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4625 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4626 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4628 .name
= BLOCK_OPT_CLUSTER_SIZE
,
4629 .type
= QEMU_OPT_SIZE
,
4630 .help
= "qcow2 cluster size",
4631 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
4634 .name
= BLOCK_OPT_PREALLOC
,
4635 .type
= QEMU_OPT_STRING
,
4636 .help
= "Preallocation mode (allowed values: off, metadata, "
4640 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
4641 .type
= QEMU_OPT_BOOL
,
4642 .help
= "Postpone refcount updates",
4643 .def_value_str
= "off"
4646 .name
= BLOCK_OPT_REFCOUNT_BITS
,
4647 .type
= QEMU_OPT_NUMBER
,
4648 .help
= "Width of a reference count entry in bits",
4649 .def_value_str
= "16"
4651 { /* end of list */ }
4655 BlockDriver bdrv_qcow2
= {
4656 .format_name
= "qcow2",
4657 .instance_size
= sizeof(BDRVQcow2State
),
4658 .bdrv_probe
= qcow2_probe
,
4659 .bdrv_open
= qcow2_open
,
4660 .bdrv_close
= qcow2_close
,
4661 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
4662 .bdrv_reopen_commit
= qcow2_reopen_commit
,
4663 .bdrv_reopen_abort
= qcow2_reopen_abort
,
4664 .bdrv_join_options
= qcow2_join_options
,
4665 .bdrv_child_perm
= bdrv_format_default_perms
,
4666 .bdrv_co_create_opts
= qcow2_co_create_opts
,
4667 .bdrv_co_create
= qcow2_co_create
,
4668 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
4669 .bdrv_co_block_status
= qcow2_co_block_status
,
4671 .bdrv_co_preadv
= qcow2_co_preadv
,
4672 .bdrv_co_pwritev
= qcow2_co_pwritev
,
4673 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
4675 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
4676 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
4677 .bdrv_co_copy_range_from
= qcow2_co_copy_range_from
,
4678 .bdrv_co_copy_range_to
= qcow2_co_copy_range_to
,
4679 .bdrv_co_truncate
= qcow2_co_truncate
,
4680 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
4681 .bdrv_make_empty
= qcow2_make_empty
,
4683 .bdrv_snapshot_create
= qcow2_snapshot_create
,
4684 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
4685 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
4686 .bdrv_snapshot_list
= qcow2_snapshot_list
,
4687 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
4688 .bdrv_measure
= qcow2_measure
,
4689 .bdrv_get_info
= qcow2_get_info
,
4690 .bdrv_get_specific_info
= qcow2_get_specific_info
,
4692 .bdrv_save_vmstate
= qcow2_save_vmstate
,
4693 .bdrv_load_vmstate
= qcow2_load_vmstate
,
4695 .supports_backing
= true,
4696 .bdrv_change_backing_file
= qcow2_change_backing_file
,
4698 .bdrv_refresh_limits
= qcow2_refresh_limits
,
4699 .bdrv_co_invalidate_cache
= qcow2_co_invalidate_cache
,
4700 .bdrv_inactivate
= qcow2_inactivate
,
4702 .create_opts
= &qcow2_create_opts
,
4703 .bdrv_co_check
= qcow2_co_check
,
4704 .bdrv_amend_options
= qcow2_amend_options
,
4706 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
4707 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
4709 .bdrv_reopen_bitmaps_rw
= qcow2_reopen_bitmaps_rw
,
4710 .bdrv_can_store_new_dirty_bitmap
= qcow2_can_store_new_dirty_bitmap
,
4711 .bdrv_remove_persistent_dirty_bitmap
= qcow2_remove_persistent_dirty_bitmap
,
4714 static void bdrv_qcow2_init(void)
4716 bdrv_register(&bdrv_qcow2
);
4719 block_init(bdrv_qcow2_init
);