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
24 #include "qemu/osdep.h"
25 #include "block/block_int.h"
26 #include "sysemu/block-backend.h"
27 #include "qemu/module.h"
29 #include "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qbool.h"
33 #include "qapi/util.h"
34 #include "qapi/qmp/types.h"
35 #include "qapi-event.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
42 Differences with QCOW:
44 - Support for multiple incremental snapshots.
45 - Memory management by reference counts.
46 - Clusters which have a reference count of one have the bit
47 QCOW_OFLAG_COPIED to optimize write performance.
48 - Size of compressed clusters is stored in sectors to reduce bit usage
49 in the cluster offsets.
50 - Support for storing additional data (such as the VM state) in the
52 - If a backing store is used, the cluster size is not constrained
53 (could be backported to QCOW).
54 - L2 tables have always a size of one cluster.
61 } QEMU_PACKED QCowExtension
;
63 #define QCOW2_EXT_MAGIC_END 0
64 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
65 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
67 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
69 const QCowHeader
*cow_header
= (const void *)buf
;
71 if (buf_size
>= sizeof(QCowHeader
) &&
72 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
73 be32_to_cpu(cow_header
->version
) >= 2)
81 * read qcow2 extension and fill bs
82 * start reading from start_offset
83 * finish reading upon magic of value 0 or when end_offset reached
84 * unknown magic is skipped (future extension this version knows nothing about)
85 * return 0 upon success, non-0 otherwise
87 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
88 uint64_t end_offset
, void **p_feature_table
,
91 BDRVQcow2State
*s
= bs
->opaque
;
97 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
99 offset
= start_offset
;
100 while (offset
< end_offset
) {
104 if (offset
> s
->cluster_size
)
105 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
107 printf("attempting to read extended header in offset %lu\n", offset
);
110 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
112 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
113 "pread fail from offset %" PRIu64
, offset
);
116 be32_to_cpus(&ext
.magic
);
117 be32_to_cpus(&ext
.len
);
118 offset
+= sizeof(ext
);
120 printf("ext.magic = 0x%x\n", ext
.magic
);
122 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
123 error_setg(errp
, "Header extension too large");
128 case QCOW2_EXT_MAGIC_END
:
131 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
132 if (ext
.len
>= sizeof(bs
->backing_format
)) {
133 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
134 " too large (>=%zu)", ext
.len
,
135 sizeof(bs
->backing_format
));
138 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
140 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
141 "Could not read format name");
144 bs
->backing_format
[ext
.len
] = '\0';
145 s
->image_backing_format
= g_strdup(bs
->backing_format
);
147 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
151 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
152 if (p_feature_table
!= NULL
) {
153 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
154 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
156 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
157 "Could not read table");
161 *p_feature_table
= feature_table
;
166 /* unknown magic - save it in case we need to rewrite the header */
168 Qcow2UnknownHeaderExtension
*uext
;
170 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
171 uext
->magic
= ext
.magic
;
173 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
175 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
177 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
178 "Could not read data");
185 offset
+= ((ext
.len
+ 7) & ~7);
191 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
193 BDRVQcow2State
*s
= bs
->opaque
;
194 Qcow2UnknownHeaderExtension
*uext
, *next
;
196 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
197 QLIST_REMOVE(uext
, next
);
202 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
205 char *features
= g_strdup("");
208 while (table
&& table
->name
[0] != '\0') {
209 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
210 if (mask
& (1ULL << table
->bit
)) {
212 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
215 mask
&= ~(1ULL << table
->bit
);
223 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
224 old
, *old
? ", " : "", mask
);
228 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
233 * Sets the dirty bit and flushes afterwards if necessary.
235 * The incompatible_features bit is only set if the image file header was
236 * updated successfully. Therefore it is not required to check the return
237 * value of this function.
239 int qcow2_mark_dirty(BlockDriverState
*bs
)
241 BDRVQcow2State
*s
= bs
->opaque
;
245 assert(s
->qcow_version
>= 3);
247 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
248 return 0; /* already dirty */
251 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
252 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
257 ret
= bdrv_flush(bs
->file
->bs
);
262 /* Only treat image as dirty if the header was updated successfully */
263 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
268 * Clears the dirty bit and flushes before if necessary. Only call this
269 * function when there are no pending requests, it does not guard against
270 * concurrent requests dirtying the image.
272 static int qcow2_mark_clean(BlockDriverState
*bs
)
274 BDRVQcow2State
*s
= bs
->opaque
;
276 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
279 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
281 ret
= bdrv_flush(bs
);
286 return qcow2_update_header(bs
);
292 * Marks the image as corrupt.
294 int qcow2_mark_corrupt(BlockDriverState
*bs
)
296 BDRVQcow2State
*s
= bs
->opaque
;
298 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
299 return qcow2_update_header(bs
);
303 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
304 * before if necessary.
306 int qcow2_mark_consistent(BlockDriverState
*bs
)
308 BDRVQcow2State
*s
= bs
->opaque
;
310 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
311 int ret
= bdrv_flush(bs
);
316 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
317 return qcow2_update_header(bs
);
322 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
325 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
330 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
331 ret
= qcow2_mark_clean(bs
);
335 return qcow2_mark_consistent(bs
);
340 static int validate_table_offset(BlockDriverState
*bs
, uint64_t offset
,
341 uint64_t entries
, size_t entry_len
)
343 BDRVQcow2State
*s
= bs
->opaque
;
346 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
347 * because values will be passed to qemu functions taking int64_t. */
348 if (entries
> INT64_MAX
/ entry_len
) {
352 size
= entries
* entry_len
;
354 if (INT64_MAX
- size
< offset
) {
358 /* Tables must be cluster aligned */
359 if (offset
& (s
->cluster_size
- 1)) {
366 static QemuOptsList qcow2_runtime_opts
= {
368 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
371 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
372 .type
= QEMU_OPT_BOOL
,
373 .help
= "Postpone refcount updates",
376 .name
= QCOW2_OPT_DISCARD_REQUEST
,
377 .type
= QEMU_OPT_BOOL
,
378 .help
= "Pass guest discard requests to the layer below",
381 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
382 .type
= QEMU_OPT_BOOL
,
383 .help
= "Generate discard requests when snapshot related space "
387 .name
= QCOW2_OPT_DISCARD_OTHER
,
388 .type
= QEMU_OPT_BOOL
,
389 .help
= "Generate discard requests when other clusters are freed",
392 .name
= QCOW2_OPT_OVERLAP
,
393 .type
= QEMU_OPT_STRING
,
394 .help
= "Selects which overlap checks to perform from a range of "
395 "templates (none, constant, cached, all)",
398 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
399 .type
= QEMU_OPT_STRING
,
400 .help
= "Selects which overlap checks to perform from a range of "
401 "templates (none, constant, cached, all)",
404 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
405 .type
= QEMU_OPT_BOOL
,
406 .help
= "Check for unintended writes into the main qcow2 header",
409 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
410 .type
= QEMU_OPT_BOOL
,
411 .help
= "Check for unintended writes into the active L1 table",
414 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
415 .type
= QEMU_OPT_BOOL
,
416 .help
= "Check for unintended writes into an active L2 table",
419 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
420 .type
= QEMU_OPT_BOOL
,
421 .help
= "Check for unintended writes into the refcount table",
424 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
425 .type
= QEMU_OPT_BOOL
,
426 .help
= "Check for unintended writes into a refcount block",
429 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
430 .type
= QEMU_OPT_BOOL
,
431 .help
= "Check for unintended writes into the snapshot table",
434 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
435 .type
= QEMU_OPT_BOOL
,
436 .help
= "Check for unintended writes into an inactive L1 table",
439 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
440 .type
= QEMU_OPT_BOOL
,
441 .help
= "Check for unintended writes into an inactive L2 table",
444 .name
= QCOW2_OPT_CACHE_SIZE
,
445 .type
= QEMU_OPT_SIZE
,
446 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
450 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
451 .type
= QEMU_OPT_SIZE
,
452 .help
= "Maximum L2 table cache size",
455 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
456 .type
= QEMU_OPT_SIZE
,
457 .help
= "Maximum refcount block cache size",
460 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
461 .type
= QEMU_OPT_NUMBER
,
462 .help
= "Clean unused cache entries after this time (in seconds)",
464 { /* end of list */ }
468 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
469 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
470 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
471 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
472 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
473 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
474 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
475 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
476 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
479 static void cache_clean_timer_cb(void *opaque
)
481 BlockDriverState
*bs
= opaque
;
482 BDRVQcow2State
*s
= bs
->opaque
;
483 qcow2_cache_clean_unused(bs
, s
->l2_table_cache
);
484 qcow2_cache_clean_unused(bs
, s
->refcount_block_cache
);
485 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
486 (int64_t) s
->cache_clean_interval
* 1000);
489 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
491 BDRVQcow2State
*s
= bs
->opaque
;
492 if (s
->cache_clean_interval
> 0) {
493 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
494 SCALE_MS
, cache_clean_timer_cb
,
496 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
497 (int64_t) s
->cache_clean_interval
* 1000);
501 static void cache_clean_timer_del(BlockDriverState
*bs
)
503 BDRVQcow2State
*s
= bs
->opaque
;
504 if (s
->cache_clean_timer
) {
505 timer_del(s
->cache_clean_timer
);
506 timer_free(s
->cache_clean_timer
);
507 s
->cache_clean_timer
= NULL
;
511 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
513 cache_clean_timer_del(bs
);
516 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
517 AioContext
*new_context
)
519 cache_clean_timer_init(bs
, new_context
);
522 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
523 uint64_t *l2_cache_size
,
524 uint64_t *refcount_cache_size
, Error
**errp
)
526 BDRVQcow2State
*s
= bs
->opaque
;
527 uint64_t combined_cache_size
;
528 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
530 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
531 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
532 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
534 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
535 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
536 *refcount_cache_size
= qemu_opt_get_size(opts
,
537 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
539 if (combined_cache_size_set
) {
540 if (l2_cache_size_set
&& refcount_cache_size_set
) {
541 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
542 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
545 } else if (*l2_cache_size
> combined_cache_size
) {
546 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
547 QCOW2_OPT_CACHE_SIZE
);
549 } else if (*refcount_cache_size
> combined_cache_size
) {
550 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
551 QCOW2_OPT_CACHE_SIZE
);
555 if (l2_cache_size_set
) {
556 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
557 } else if (refcount_cache_size_set
) {
558 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
560 *refcount_cache_size
= combined_cache_size
561 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO
+ 1);
562 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
565 if (!l2_cache_size_set
&& !refcount_cache_size_set
) {
566 *l2_cache_size
= MAX(DEFAULT_L2_CACHE_BYTE_SIZE
,
567 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
569 *refcount_cache_size
= *l2_cache_size
570 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
571 } else if (!l2_cache_size_set
) {
572 *l2_cache_size
= *refcount_cache_size
573 * DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
574 } else if (!refcount_cache_size_set
) {
575 *refcount_cache_size
= *l2_cache_size
576 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
581 typedef struct Qcow2ReopenState
{
582 Qcow2Cache
*l2_table_cache
;
583 Qcow2Cache
*refcount_block_cache
;
584 bool use_lazy_refcounts
;
586 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
587 uint64_t cache_clean_interval
;
590 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
592 QDict
*options
, int flags
,
595 BDRVQcow2State
*s
= bs
->opaque
;
596 QemuOpts
*opts
= NULL
;
597 const char *opt_overlap_check
, *opt_overlap_check_template
;
598 int overlap_check_template
= 0;
599 uint64_t l2_cache_size
, refcount_cache_size
;
601 Error
*local_err
= NULL
;
604 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
605 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
607 error_propagate(errp
, local_err
);
612 /* get L2 table/refcount block cache size from command line options */
613 read_cache_sizes(bs
, opts
, &l2_cache_size
, &refcount_cache_size
,
616 error_propagate(errp
, local_err
);
621 l2_cache_size
/= s
->cluster_size
;
622 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
623 l2_cache_size
= MIN_L2_CACHE_SIZE
;
625 if (l2_cache_size
> INT_MAX
) {
626 error_setg(errp
, "L2 cache size too big");
631 refcount_cache_size
/= s
->cluster_size
;
632 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
633 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
635 if (refcount_cache_size
> INT_MAX
) {
636 error_setg(errp
, "Refcount cache size too big");
641 /* alloc new L2 table/refcount block cache, flush old one */
642 if (s
->l2_table_cache
) {
643 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
645 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
650 if (s
->refcount_block_cache
) {
651 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
653 error_setg_errno(errp
, -ret
,
654 "Failed to flush the refcount block cache");
659 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
);
660 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
);
661 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
662 error_setg(errp
, "Could not allocate metadata caches");
667 /* New interval for cache cleanup timer */
668 r
->cache_clean_interval
=
669 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
670 s
->cache_clean_interval
);
671 if (r
->cache_clean_interval
> UINT_MAX
) {
672 error_setg(errp
, "Cache clean interval too big");
677 /* lazy-refcounts; flush if going from enabled to disabled */
678 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
679 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
680 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
681 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
682 "qemu 1.1 compatibility level");
687 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
688 ret
= qcow2_mark_clean(bs
);
690 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
695 /* Overlap check options */
696 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
697 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
698 if (opt_overlap_check_template
&& opt_overlap_check
&&
699 strcmp(opt_overlap_check_template
, opt_overlap_check
))
701 error_setg(errp
, "Conflicting values for qcow2 options '"
702 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
703 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
707 if (!opt_overlap_check
) {
708 opt_overlap_check
= opt_overlap_check_template
?: "cached";
711 if (!strcmp(opt_overlap_check
, "none")) {
712 overlap_check_template
= 0;
713 } else if (!strcmp(opt_overlap_check
, "constant")) {
714 overlap_check_template
= QCOW2_OL_CONSTANT
;
715 } else if (!strcmp(opt_overlap_check
, "cached")) {
716 overlap_check_template
= QCOW2_OL_CACHED
;
717 } else if (!strcmp(opt_overlap_check
, "all")) {
718 overlap_check_template
= QCOW2_OL_ALL
;
720 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
721 "'overlap-check'. Allowed are any of the following: "
722 "none, constant, cached, all", opt_overlap_check
);
727 r
->overlap_check
= 0;
728 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
729 /* overlap-check defines a template bitmask, but every flag may be
730 * overwritten through the associated boolean option */
732 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
733 overlap_check_template
& (1 << i
)) << i
;
736 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
737 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
738 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
739 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
740 flags
& BDRV_O_UNMAP
);
741 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
742 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
743 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
744 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
753 static void qcow2_update_options_commit(BlockDriverState
*bs
,
756 BDRVQcow2State
*s
= bs
->opaque
;
759 if (s
->l2_table_cache
) {
760 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
762 if (s
->refcount_block_cache
) {
763 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
765 s
->l2_table_cache
= r
->l2_table_cache
;
766 s
->refcount_block_cache
= r
->refcount_block_cache
;
768 s
->overlap_check
= r
->overlap_check
;
769 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
771 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
772 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
775 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
776 cache_clean_timer_del(bs
);
777 s
->cache_clean_interval
= r
->cache_clean_interval
;
778 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
782 static void qcow2_update_options_abort(BlockDriverState
*bs
,
785 if (r
->l2_table_cache
) {
786 qcow2_cache_destroy(bs
, r
->l2_table_cache
);
788 if (r
->refcount_block_cache
) {
789 qcow2_cache_destroy(bs
, r
->refcount_block_cache
);
793 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
794 int flags
, Error
**errp
)
796 Qcow2ReopenState r
= {};
799 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
801 qcow2_update_options_commit(bs
, &r
);
803 qcow2_update_options_abort(bs
, &r
);
809 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
812 BDRVQcow2State
*s
= bs
->opaque
;
816 Error
*local_err
= NULL
;
818 uint64_t l1_vm_state_index
;
820 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
822 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
825 be32_to_cpus(&header
.magic
);
826 be32_to_cpus(&header
.version
);
827 be64_to_cpus(&header
.backing_file_offset
);
828 be32_to_cpus(&header
.backing_file_size
);
829 be64_to_cpus(&header
.size
);
830 be32_to_cpus(&header
.cluster_bits
);
831 be32_to_cpus(&header
.crypt_method
);
832 be64_to_cpus(&header
.l1_table_offset
);
833 be32_to_cpus(&header
.l1_size
);
834 be64_to_cpus(&header
.refcount_table_offset
);
835 be32_to_cpus(&header
.refcount_table_clusters
);
836 be64_to_cpus(&header
.snapshots_offset
);
837 be32_to_cpus(&header
.nb_snapshots
);
839 if (header
.magic
!= QCOW_MAGIC
) {
840 error_setg(errp
, "Image is not in qcow2 format");
844 if (header
.version
< 2 || header
.version
> 3) {
845 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
850 s
->qcow_version
= header
.version
;
852 /* Initialise cluster size */
853 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
854 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
855 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
856 header
.cluster_bits
);
861 s
->cluster_bits
= header
.cluster_bits
;
862 s
->cluster_size
= 1 << s
->cluster_bits
;
863 s
->cluster_sectors
= 1 << (s
->cluster_bits
- 9);
865 /* Initialise version 3 header fields */
866 if (header
.version
== 2) {
867 header
.incompatible_features
= 0;
868 header
.compatible_features
= 0;
869 header
.autoclear_features
= 0;
870 header
.refcount_order
= 4;
871 header
.header_length
= 72;
873 be64_to_cpus(&header
.incompatible_features
);
874 be64_to_cpus(&header
.compatible_features
);
875 be64_to_cpus(&header
.autoclear_features
);
876 be32_to_cpus(&header
.refcount_order
);
877 be32_to_cpus(&header
.header_length
);
879 if (header
.header_length
< 104) {
880 error_setg(errp
, "qcow2 header too short");
886 if (header
.header_length
> s
->cluster_size
) {
887 error_setg(errp
, "qcow2 header exceeds cluster size");
892 if (header
.header_length
> sizeof(header
)) {
893 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
894 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
895 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
896 s
->unknown_header_fields_size
);
898 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
904 if (header
.backing_file_offset
> s
->cluster_size
) {
905 error_setg(errp
, "Invalid backing file offset");
910 if (header
.backing_file_offset
) {
911 ext_end
= header
.backing_file_offset
;
913 ext_end
= 1 << header
.cluster_bits
;
916 /* Handle feature bits */
917 s
->incompatible_features
= header
.incompatible_features
;
918 s
->compatible_features
= header
.compatible_features
;
919 s
->autoclear_features
= header
.autoclear_features
;
921 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
922 void *feature_table
= NULL
;
923 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
924 &feature_table
, NULL
);
925 report_unsupported_feature(errp
, feature_table
,
926 s
->incompatible_features
&
927 ~QCOW2_INCOMPAT_MASK
);
929 g_free(feature_table
);
933 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
934 /* Corrupt images may not be written to unless they are being repaired
936 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
937 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
944 /* Check support for various header values */
945 if (header
.refcount_order
> 6) {
946 error_setg(errp
, "Reference count entry width too large; may not "
951 s
->refcount_order
= header
.refcount_order
;
952 s
->refcount_bits
= 1 << s
->refcount_order
;
953 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
954 s
->refcount_max
+= s
->refcount_max
- 1;
956 if (header
.crypt_method
> QCOW_CRYPT_AES
) {
957 error_setg(errp
, "Unsupported encryption method: %" PRIu32
,
958 header
.crypt_method
);
962 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128
,
963 QCRYPTO_CIPHER_MODE_CBC
)) {
964 error_setg(errp
, "AES cipher not available");
968 s
->crypt_method_header
= header
.crypt_method
;
969 if (s
->crypt_method_header
) {
970 if (bdrv_uses_whitelist() &&
971 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
973 "Use of AES-CBC encrypted qcow2 images is no longer "
974 "supported in system emulators");
975 error_append_hint(errp
,
976 "You can use 'qemu-img convert' to convert your "
977 "image to an alternative supported format, such "
978 "as unencrypted qcow2, or raw with the LUKS "
979 "format instead.\n");
984 bs
->encrypted
= true;
987 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
988 s
->l2_size
= 1 << s
->l2_bits
;
989 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
990 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
991 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
992 bs
->total_sectors
= header
.size
/ 512;
993 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
994 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
995 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
997 s
->refcount_table_offset
= header
.refcount_table_offset
;
998 s
->refcount_table_size
=
999 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1001 if (header
.refcount_table_clusters
> qcow2_max_refcount_clusters(s
)) {
1002 error_setg(errp
, "Reference count table too large");
1007 ret
= validate_table_offset(bs
, s
->refcount_table_offset
,
1008 s
->refcount_table_size
, sizeof(uint64_t));
1010 error_setg(errp
, "Invalid reference count table offset");
1014 /* Snapshot table offset/length */
1015 if (header
.nb_snapshots
> QCOW_MAX_SNAPSHOTS
) {
1016 error_setg(errp
, "Too many snapshots");
1021 ret
= validate_table_offset(bs
, header
.snapshots_offset
,
1022 header
.nb_snapshots
,
1023 sizeof(QCowSnapshotHeader
));
1025 error_setg(errp
, "Invalid snapshot table offset");
1029 /* read the level 1 table */
1030 if (header
.l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
1031 error_setg(errp
, "Active L1 table too large");
1035 s
->l1_size
= header
.l1_size
;
1037 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1038 if (l1_vm_state_index
> INT_MAX
) {
1039 error_setg(errp
, "Image is too big");
1043 s
->l1_vm_state_index
= l1_vm_state_index
;
1045 /* the L1 table must contain at least enough entries to put
1046 header.size bytes */
1047 if (s
->l1_size
< s
->l1_vm_state_index
) {
1048 error_setg(errp
, "L1 table is too small");
1053 ret
= validate_table_offset(bs
, header
.l1_table_offset
,
1054 header
.l1_size
, sizeof(uint64_t));
1056 error_setg(errp
, "Invalid L1 table offset");
1059 s
->l1_table_offset
= header
.l1_table_offset
;
1062 if (s
->l1_size
> 0) {
1063 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1064 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
1065 if (s
->l1_table
== NULL
) {
1066 error_setg(errp
, "Could not allocate L1 table");
1070 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1071 s
->l1_size
* sizeof(uint64_t));
1073 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1076 for(i
= 0;i
< s
->l1_size
; i
++) {
1077 be64_to_cpus(&s
->l1_table
[i
]);
1081 /* Parse driver-specific options */
1082 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1087 s
->cluster_cache
= g_malloc(s
->cluster_size
);
1088 /* one more sector for decompressed data alignment */
1089 s
->cluster_data
= qemu_try_blockalign(bs
->file
->bs
, QCOW_MAX_CRYPT_CLUSTERS
1090 * s
->cluster_size
+ 512);
1091 if (s
->cluster_data
== NULL
) {
1092 error_setg(errp
, "Could not allocate temporary cluster buffer");
1097 s
->cluster_cache_offset
= -1;
1100 ret
= qcow2_refcount_init(bs
);
1102 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1106 QLIST_INIT(&s
->cluster_allocs
);
1107 QTAILQ_INIT(&s
->discards
);
1109 /* read qcow2 extensions */
1110 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1112 error_propagate(errp
, local_err
);
1117 /* read the backing file name */
1118 if (header
.backing_file_offset
!= 0) {
1119 len
= header
.backing_file_size
;
1120 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1121 len
>= sizeof(bs
->backing_file
)) {
1122 error_setg(errp
, "Backing file name too long");
1126 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1127 bs
->backing_file
, len
);
1129 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1132 bs
->backing_file
[len
] = '\0';
1133 s
->image_backing_file
= g_strdup(bs
->backing_file
);
1136 /* Internal snapshots */
1137 s
->snapshots_offset
= header
.snapshots_offset
;
1138 s
->nb_snapshots
= header
.nb_snapshots
;
1140 ret
= qcow2_read_snapshots(bs
);
1142 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1146 /* Clear unknown autoclear feature bits */
1147 if (!bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
) && s
->autoclear_features
) {
1148 s
->autoclear_features
= 0;
1149 ret
= qcow2_update_header(bs
);
1151 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1156 /* Initialise locks */
1157 qemu_co_mutex_init(&s
->lock
);
1159 /* Repair image if dirty */
1160 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1161 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1162 BdrvCheckResult result
= {0};
1164 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1166 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1173 BdrvCheckResult result
= {0};
1174 qcow2_check_refcounts(bs
, &result
, 0);
1180 g_free(s
->unknown_header_fields
);
1181 cleanup_unknown_header_ext(bs
);
1182 qcow2_free_snapshots(bs
);
1183 qcow2_refcount_close(bs
);
1184 qemu_vfree(s
->l1_table
);
1185 /* else pre-write overlap checks in cache_destroy may crash */
1187 cache_clean_timer_del(bs
);
1188 if (s
->l2_table_cache
) {
1189 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1191 if (s
->refcount_block_cache
) {
1192 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1194 g_free(s
->cluster_cache
);
1195 qemu_vfree(s
->cluster_data
);
1199 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1201 BDRVQcow2State
*s
= bs
->opaque
;
1203 if (bs
->encrypted
) {
1204 /* Encryption works on a sector granularity */
1205 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1207 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1210 static int qcow2_set_key(BlockDriverState
*bs
, const char *key
)
1212 BDRVQcow2State
*s
= bs
->opaque
;
1217 memset(keybuf
, 0, 16);
1221 /* XXX: we could compress the chars to 7 bits to increase
1223 for(i
= 0;i
< len
;i
++) {
1226 assert(bs
->encrypted
);
1228 qcrypto_cipher_free(s
->cipher
);
1229 s
->cipher
= qcrypto_cipher_new(
1230 QCRYPTO_CIPHER_ALG_AES_128
,
1231 QCRYPTO_CIPHER_MODE_CBC
,
1232 keybuf
, G_N_ELEMENTS(keybuf
),
1236 /* XXX would be nice if errors in this method could
1237 * be properly propagate to the caller. Would need
1238 * the bdrv_set_key() API signature to be fixed. */
1245 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1246 BlockReopenQueue
*queue
, Error
**errp
)
1248 Qcow2ReopenState
*r
;
1251 r
= g_new0(Qcow2ReopenState
, 1);
1254 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1255 state
->flags
, errp
);
1260 /* We need to write out any unwritten data if we reopen read-only. */
1261 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1262 ret
= bdrv_flush(state
->bs
);
1267 ret
= qcow2_mark_clean(state
->bs
);
1276 qcow2_update_options_abort(state
->bs
, r
);
1281 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1283 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1284 g_free(state
->opaque
);
1287 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1289 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1290 g_free(state
->opaque
);
1293 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1295 bool has_new_overlap_template
=
1296 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1297 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1298 bool has_new_total_cache_size
=
1299 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1300 bool has_all_cache_options
;
1302 /* New overlap template overrides all old overlap options */
1303 if (has_new_overlap_template
) {
1304 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1305 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1306 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1307 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1308 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1309 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1310 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1311 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1312 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1313 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1316 /* New total cache size overrides all old options */
1317 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1318 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1319 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1322 qdict_join(options
, old_options
, false);
1325 * If after merging all cache size options are set, an old total size is
1326 * overwritten. Do keep all options, however, if all three are new. The
1327 * resulting error message is what we want to happen.
1329 has_all_cache_options
=
1330 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1331 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1332 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1334 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1335 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1339 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
1340 int64_t sector_num
, int nb_sectors
, int *pnum
, BlockDriverState
**file
)
1342 BDRVQcow2State
*s
= bs
->opaque
;
1343 uint64_t cluster_offset
;
1344 int index_in_cluster
, ret
;
1348 bytes
= MIN(INT_MAX
, nb_sectors
* BDRV_SECTOR_SIZE
);
1349 qemu_co_mutex_lock(&s
->lock
);
1350 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9, &bytes
,
1352 qemu_co_mutex_unlock(&s
->lock
);
1357 *pnum
= bytes
>> BDRV_SECTOR_BITS
;
1359 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1361 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1362 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
1363 *file
= bs
->file
->bs
;
1364 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
1366 if (ret
== QCOW2_CLUSTER_ZERO
) {
1367 status
|= BDRV_BLOCK_ZERO
;
1368 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1369 status
|= BDRV_BLOCK_DATA
;
1374 /* handle reading after the end of the backing file */
1375 int qcow2_backing_read1(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
1376 int64_t offset
, int bytes
)
1378 uint64_t bs_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1381 if ((offset
+ bytes
) <= bs_size
) {
1385 if (offset
>= bs_size
) {
1388 n1
= bs_size
- offset
;
1391 qemu_iovec_memset(qiov
, n1
, 0, bytes
- n1
);
1396 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1397 uint64_t bytes
, QEMUIOVector
*qiov
,
1400 BDRVQcow2State
*s
= bs
->opaque
;
1401 int offset_in_cluster
, n1
;
1403 unsigned int cur_bytes
; /* number of bytes in current iteration */
1404 uint64_t cluster_offset
= 0;
1405 uint64_t bytes_done
= 0;
1406 QEMUIOVector hd_qiov
;
1407 uint8_t *cluster_data
= NULL
;
1409 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1411 qemu_co_mutex_lock(&s
->lock
);
1413 while (bytes
!= 0) {
1415 /* prepare next request */
1416 cur_bytes
= MIN(bytes
, INT_MAX
);
1418 cur_bytes
= MIN(cur_bytes
,
1419 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1422 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1427 offset_in_cluster
= offset_into_cluster(s
, offset
);
1429 qemu_iovec_reset(&hd_qiov
);
1430 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1433 case QCOW2_CLUSTER_UNALLOCATED
:
1436 /* read from the base image */
1437 n1
= qcow2_backing_read1(bs
->backing
->bs
, &hd_qiov
,
1440 QEMUIOVector local_qiov
;
1442 qemu_iovec_init(&local_qiov
, hd_qiov
.niov
);
1443 qemu_iovec_concat(&local_qiov
, &hd_qiov
, 0, n1
);
1445 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1446 qemu_co_mutex_unlock(&s
->lock
);
1447 ret
= bdrv_co_preadv(bs
->backing
, offset
, n1
,
1449 qemu_co_mutex_lock(&s
->lock
);
1451 qemu_iovec_destroy(&local_qiov
);
1458 /* Note: in this case, no need to wait */
1459 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1463 case QCOW2_CLUSTER_ZERO
:
1464 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1467 case QCOW2_CLUSTER_COMPRESSED
:
1468 /* add AIO support for compressed blocks ? */
1469 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1474 qemu_iovec_from_buf(&hd_qiov
, 0,
1475 s
->cluster_cache
+ offset_in_cluster
,
1479 case QCOW2_CLUSTER_NORMAL
:
1480 if ((cluster_offset
& 511) != 0) {
1485 if (bs
->encrypted
) {
1489 * For encrypted images, read everything into a temporary
1490 * contiguous buffer on which the AES functions can work.
1492 if (!cluster_data
) {
1494 qemu_try_blockalign(bs
->file
->bs
,
1495 QCOW_MAX_CRYPT_CLUSTERS
1497 if (cluster_data
== NULL
) {
1503 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1504 qemu_iovec_reset(&hd_qiov
);
1505 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1508 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1509 qemu_co_mutex_unlock(&s
->lock
);
1510 ret
= bdrv_co_preadv(bs
->file
,
1511 cluster_offset
+ offset_in_cluster
,
1512 cur_bytes
, &hd_qiov
, 0);
1513 qemu_co_mutex_lock(&s
->lock
);
1517 if (bs
->encrypted
) {
1519 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1520 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1522 if (qcow2_encrypt_sectors(s
, offset
>> BDRV_SECTOR_BITS
,
1523 cluster_data
, cluster_data
,
1524 cur_bytes
>> BDRV_SECTOR_BITS
,
1530 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1535 g_assert_not_reached();
1541 offset
+= cur_bytes
;
1542 bytes_done
+= cur_bytes
;
1547 qemu_co_mutex_unlock(&s
->lock
);
1549 qemu_iovec_destroy(&hd_qiov
);
1550 qemu_vfree(cluster_data
);
1555 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1556 uint64_t bytes
, QEMUIOVector
*qiov
,
1559 BDRVQcow2State
*s
= bs
->opaque
;
1560 int offset_in_cluster
;
1562 unsigned int cur_bytes
; /* number of sectors in current iteration */
1563 uint64_t cluster_offset
;
1564 QEMUIOVector hd_qiov
;
1565 uint64_t bytes_done
= 0;
1566 uint8_t *cluster_data
= NULL
;
1567 QCowL2Meta
*l2meta
= NULL
;
1569 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
1571 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1573 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1575 qemu_co_mutex_lock(&s
->lock
);
1577 while (bytes
!= 0) {
1581 trace_qcow2_writev_start_part(qemu_coroutine_self());
1582 offset_in_cluster
= offset_into_cluster(s
, offset
);
1583 cur_bytes
= MIN(bytes
, INT_MAX
);
1584 if (bs
->encrypted
) {
1585 cur_bytes
= MIN(cur_bytes
,
1586 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
1587 - offset_in_cluster
);
1590 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
1591 &cluster_offset
, &l2meta
);
1596 assert((cluster_offset
& 511) == 0);
1598 qemu_iovec_reset(&hd_qiov
);
1599 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1601 if (bs
->encrypted
) {
1604 if (!cluster_data
) {
1605 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
1606 QCOW_MAX_CRYPT_CLUSTERS
1608 if (cluster_data
== NULL
) {
1614 assert(hd_qiov
.size
<=
1615 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1616 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
1618 if (qcow2_encrypt_sectors(s
, offset
>> BDRV_SECTOR_BITS
,
1619 cluster_data
, cluster_data
,
1620 cur_bytes
>>BDRV_SECTOR_BITS
,
1627 qemu_iovec_reset(&hd_qiov
);
1628 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1631 ret
= qcow2_pre_write_overlap_check(bs
, 0,
1632 cluster_offset
+ offset_in_cluster
, cur_bytes
);
1637 qemu_co_mutex_unlock(&s
->lock
);
1638 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
1639 trace_qcow2_writev_data(qemu_coroutine_self(),
1640 cluster_offset
+ offset_in_cluster
);
1641 ret
= bdrv_co_pwritev(bs
->file
,
1642 cluster_offset
+ offset_in_cluster
,
1643 cur_bytes
, &hd_qiov
, 0);
1644 qemu_co_mutex_lock(&s
->lock
);
1649 while (l2meta
!= NULL
) {
1652 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1657 /* Take the request off the list of running requests */
1658 if (l2meta
->nb_clusters
!= 0) {
1659 QLIST_REMOVE(l2meta
, next_in_flight
);
1662 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1664 next
= l2meta
->next
;
1670 offset
+= cur_bytes
;
1671 bytes_done
+= cur_bytes
;
1672 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
1677 qemu_co_mutex_unlock(&s
->lock
);
1679 while (l2meta
!= NULL
) {
1682 if (l2meta
->nb_clusters
!= 0) {
1683 QLIST_REMOVE(l2meta
, next_in_flight
);
1685 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1687 next
= l2meta
->next
;
1692 qemu_iovec_destroy(&hd_qiov
);
1693 qemu_vfree(cluster_data
);
1694 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
1699 static int qcow2_inactivate(BlockDriverState
*bs
)
1701 BDRVQcow2State
*s
= bs
->opaque
;
1702 int ret
, result
= 0;
1704 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
1707 error_report("Failed to flush the L2 table cache: %s",
1711 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1714 error_report("Failed to flush the refcount block cache: %s",
1719 qcow2_mark_clean(bs
);
1725 static void qcow2_close(BlockDriverState
*bs
)
1727 BDRVQcow2State
*s
= bs
->opaque
;
1728 qemu_vfree(s
->l1_table
);
1729 /* else pre-write overlap checks in cache_destroy may crash */
1732 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
1733 qcow2_inactivate(bs
);
1736 cache_clean_timer_del(bs
);
1737 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1738 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1740 qcrypto_cipher_free(s
->cipher
);
1743 g_free(s
->unknown_header_fields
);
1744 cleanup_unknown_header_ext(bs
);
1746 g_free(s
->image_backing_file
);
1747 g_free(s
->image_backing_format
);
1749 g_free(s
->cluster_cache
);
1750 qemu_vfree(s
->cluster_data
);
1751 qcow2_refcount_close(bs
);
1752 qcow2_free_snapshots(bs
);
1755 static void qcow2_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
1757 BDRVQcow2State
*s
= bs
->opaque
;
1758 int flags
= s
->flags
;
1759 QCryptoCipher
*cipher
= NULL
;
1761 Error
*local_err
= NULL
;
1765 * Backing files are read-only which makes all of their metadata immutable,
1766 * that means we don't have to worry about reopening them here.
1774 memset(s
, 0, sizeof(BDRVQcow2State
));
1775 options
= qdict_clone_shallow(bs
->options
);
1777 flags
&= ~BDRV_O_INACTIVE
;
1778 ret
= qcow2_open(bs
, options
, flags
, &local_err
);
1781 error_propagate(errp
, local_err
);
1782 error_prepend(errp
, "Could not reopen qcow2 layer: ");
1785 } else if (ret
< 0) {
1786 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
1794 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
1795 size_t len
, size_t buflen
)
1797 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
1798 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
1800 if (buflen
< ext_len
) {
1804 *ext_backing_fmt
= (QCowExtension
) {
1805 .magic
= cpu_to_be32(magic
),
1806 .len
= cpu_to_be32(len
),
1810 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
1817 * Updates the qcow2 header, including the variable length parts of it, i.e.
1818 * the backing file name and all extensions. qcow2 was not designed to allow
1819 * such changes, so if we run out of space (we can only use the first cluster)
1820 * this function may fail.
1822 * Returns 0 on success, -errno in error cases.
1824 int qcow2_update_header(BlockDriverState
*bs
)
1826 BDRVQcow2State
*s
= bs
->opaque
;
1829 size_t buflen
= s
->cluster_size
;
1831 uint64_t total_size
;
1832 uint32_t refcount_table_clusters
;
1833 size_t header_length
;
1834 Qcow2UnknownHeaderExtension
*uext
;
1836 buf
= qemu_blockalign(bs
, buflen
);
1838 /* Header structure */
1839 header
= (QCowHeader
*) buf
;
1841 if (buflen
< sizeof(*header
)) {
1846 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
1847 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1848 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
1850 *header
= (QCowHeader
) {
1851 /* Version 2 fields */
1852 .magic
= cpu_to_be32(QCOW_MAGIC
),
1853 .version
= cpu_to_be32(s
->qcow_version
),
1854 .backing_file_offset
= 0,
1855 .backing_file_size
= 0,
1856 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
1857 .size
= cpu_to_be64(total_size
),
1858 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
1859 .l1_size
= cpu_to_be32(s
->l1_size
),
1860 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
1861 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
1862 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
1863 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
1864 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
1866 /* Version 3 fields */
1867 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
1868 .compatible_features
= cpu_to_be64(s
->compatible_features
),
1869 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
1870 .refcount_order
= cpu_to_be32(s
->refcount_order
),
1871 .header_length
= cpu_to_be32(header_length
),
1874 /* For older versions, write a shorter header */
1875 switch (s
->qcow_version
) {
1877 ret
= offsetof(QCowHeader
, incompatible_features
);
1880 ret
= sizeof(*header
);
1889 memset(buf
, 0, buflen
);
1891 /* Preserve any unknown field in the header */
1892 if (s
->unknown_header_fields_size
) {
1893 if (buflen
< s
->unknown_header_fields_size
) {
1898 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
1899 buf
+= s
->unknown_header_fields_size
;
1900 buflen
-= s
->unknown_header_fields_size
;
1903 /* Backing file format header extension */
1904 if (s
->image_backing_format
) {
1905 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
1906 s
->image_backing_format
,
1907 strlen(s
->image_backing_format
),
1918 if (s
->qcow_version
>= 3) {
1919 Qcow2Feature features
[] = {
1921 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1922 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
1923 .name
= "dirty bit",
1926 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1927 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
1928 .name
= "corrupt bit",
1931 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
1932 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
1933 .name
= "lazy refcounts",
1937 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
1938 features
, sizeof(features
), buflen
);
1946 /* Keep unknown header extensions */
1947 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
1948 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
1957 /* End of header extensions */
1958 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
1966 /* Backing file name */
1967 if (s
->image_backing_file
) {
1968 size_t backing_file_len
= strlen(s
->image_backing_file
);
1970 if (buflen
< backing_file_len
) {
1975 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1976 strncpy(buf
, s
->image_backing_file
, buflen
);
1978 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
1979 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
1982 /* Write the new header */
1983 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
1994 static int qcow2_change_backing_file(BlockDriverState
*bs
,
1995 const char *backing_file
, const char *backing_fmt
)
1997 BDRVQcow2State
*s
= bs
->opaque
;
1999 if (backing_file
&& strlen(backing_file
) > 1023) {
2003 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2004 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2006 g_free(s
->image_backing_file
);
2007 g_free(s
->image_backing_format
);
2009 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2010 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2012 return qcow2_update_header(bs
);
2015 static int preallocate(BlockDriverState
*bs
)
2019 uint64_t host_offset
= 0;
2020 unsigned int cur_bytes
;
2024 bytes
= bdrv_getlength(bs
);
2028 cur_bytes
= MIN(bytes
, INT_MAX
);
2029 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2030 &host_offset
, &meta
);
2036 QCowL2Meta
*next
= meta
->next
;
2038 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2040 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2041 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2045 /* There are no dependent requests, but we need to remove our
2046 * request from the list of in-flight requests */
2047 QLIST_REMOVE(meta
, next_in_flight
);
2053 /* TODO Preallocate data if requested */
2056 offset
+= cur_bytes
;
2060 * It is expected that the image file is large enough to actually contain
2061 * all of the allocated clusters (otherwise we get failing reads after
2062 * EOF). Extend the image to the last allocated sector.
2064 if (host_offset
!= 0) {
2066 ret
= bdrv_pwrite(bs
->file
, (host_offset
+ cur_bytes
) - 1,
2076 static int qcow2_create2(const char *filename
, int64_t total_size
,
2077 const char *backing_file
, const char *backing_format
,
2078 int flags
, size_t cluster_size
, PreallocMode prealloc
,
2079 QemuOpts
*opts
, int version
, int refcount_order
,
2085 /* Calculate cluster_bits */
2086 cluster_bits
= ctz32(cluster_size
);
2087 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2088 (1 << cluster_bits
) != cluster_size
)
2090 error_setg(errp
, "Cluster size must be a power of two between %d and "
2091 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2096 * Open the image file and write a minimal qcow2 header.
2098 * We keep things simple and start with a zero-sized image. We also
2099 * do without refcount blocks or a L1 table for now. We'll fix the
2100 * inconsistency later.
2102 * We do need a refcount table because growing the refcount table means
2103 * allocating two new refcount blocks - the seconds of which would be at
2104 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2105 * size for any qcow2 image.
2109 uint64_t* refcount_table
;
2110 Error
*local_err
= NULL
;
2113 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
2114 /* Note: The following calculation does not need to be exact; if it is a
2115 * bit off, either some bytes will be "leaked" (which is fine) or we
2116 * will need to increase the file size by some bytes (which is fine,
2117 * too, as long as the bulk is allocated here). Therefore, using
2118 * floating point arithmetic is fine. */
2119 int64_t meta_size
= 0;
2120 uint64_t nreftablee
, nrefblocke
, nl1e
, nl2e
;
2121 int64_t aligned_total_size
= align_offset(total_size
, cluster_size
);
2122 int refblock_bits
, refblock_size
;
2123 /* refcount entry size in bytes */
2124 double rces
= (1 << refcount_order
) / 8.;
2126 /* see qcow2_open() */
2127 refblock_bits
= cluster_bits
- (refcount_order
- 3);
2128 refblock_size
= 1 << refblock_bits
;
2130 /* header: 1 cluster */
2131 meta_size
+= cluster_size
;
2133 /* total size of L2 tables */
2134 nl2e
= aligned_total_size
/ cluster_size
;
2135 nl2e
= align_offset(nl2e
, cluster_size
/ sizeof(uint64_t));
2136 meta_size
+= nl2e
* sizeof(uint64_t);
2138 /* total size of L1 tables */
2139 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2140 nl1e
= align_offset(nl1e
, cluster_size
/ sizeof(uint64_t));
2141 meta_size
+= nl1e
* sizeof(uint64_t);
2143 /* total size of refcount blocks
2145 * note: every host cluster is reference-counted, including metadata
2146 * (even refcount blocks are recursively included).
2148 * a = total_size (this is the guest disk size)
2149 * m = meta size not including refcount blocks and refcount tables
2151 * y1 = number of refcount blocks entries
2152 * y2 = meta size including everything
2153 * rces = refcount entry size in bytes
2156 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2158 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2160 nrefblocke
= (aligned_total_size
+ meta_size
+ cluster_size
)
2161 / (cluster_size
- rces
- rces
* sizeof(uint64_t)
2163 meta_size
+= DIV_ROUND_UP(nrefblocke
, refblock_size
) * cluster_size
;
2165 /* total size of refcount tables */
2166 nreftablee
= nrefblocke
/ refblock_size
;
2167 nreftablee
= align_offset(nreftablee
, cluster_size
/ sizeof(uint64_t));
2168 meta_size
+= nreftablee
* sizeof(uint64_t);
2170 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2171 aligned_total_size
+ meta_size
, &error_abort
);
2172 qemu_opt_set(opts
, BLOCK_OPT_PREALLOC
, PreallocMode_lookup
[prealloc
],
2176 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2178 error_propagate(errp
, local_err
);
2182 blk
= blk_new_open(filename
, NULL
, NULL
,
2183 BDRV_O_RDWR
| BDRV_O_PROTOCOL
, &local_err
);
2185 error_propagate(errp
, local_err
);
2189 blk_set_allow_write_beyond_eof(blk
, true);
2191 /* Write the header */
2192 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2193 header
= g_malloc0(cluster_size
);
2194 *header
= (QCowHeader
) {
2195 .magic
= cpu_to_be32(QCOW_MAGIC
),
2196 .version
= cpu_to_be32(version
),
2197 .cluster_bits
= cpu_to_be32(cluster_bits
),
2198 .size
= cpu_to_be64(0),
2199 .l1_table_offset
= cpu_to_be64(0),
2200 .l1_size
= cpu_to_be32(0),
2201 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2202 .refcount_table_clusters
= cpu_to_be32(1),
2203 .refcount_order
= cpu_to_be32(refcount_order
),
2204 .header_length
= cpu_to_be32(sizeof(*header
)),
2207 if (flags
& BLOCK_FLAG_ENCRYPT
) {
2208 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_AES
);
2210 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2213 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
2214 header
->compatible_features
|=
2215 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2218 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2221 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2225 /* Write a refcount table with one refcount block */
2226 refcount_table
= g_malloc0(2 * cluster_size
);
2227 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2228 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2229 g_free(refcount_table
);
2232 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2240 * And now open the image and make it consistent first (i.e. increase the
2241 * refcount of the cluster that is occupied by the header and the refcount
2244 options
= qdict_new();
2245 qdict_put(options
, "driver", qstring_from_str("qcow2"));
2246 blk
= blk_new_open(filename
, NULL
, options
,
2247 BDRV_O_RDWR
| BDRV_O_NO_FLUSH
, &local_err
);
2249 error_propagate(errp
, local_err
);
2254 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2256 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2257 "header and refcount table");
2260 } else if (ret
!= 0) {
2261 error_report("Huh, first cluster in empty image is already in use?");
2265 /* Create a full header (including things like feature table) */
2266 ret
= qcow2_update_header(blk_bs(blk
));
2268 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
2272 /* Okay, now that we have a valid image, let's give it the right size */
2273 ret
= blk_truncate(blk
, total_size
);
2275 error_setg_errno(errp
, -ret
, "Could not resize image");
2279 /* Want a backing file? There you go.*/
2281 ret
= bdrv_change_backing_file(blk_bs(blk
), backing_file
, backing_format
);
2283 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
2284 "with format '%s'", backing_file
, backing_format
);
2289 /* And if we're supposed to preallocate metadata, do that now */
2290 if (prealloc
!= PREALLOC_MODE_OFF
) {
2291 BDRVQcow2State
*s
= blk_bs(blk
)->opaque
;
2292 qemu_co_mutex_lock(&s
->lock
);
2293 ret
= preallocate(blk_bs(blk
));
2294 qemu_co_mutex_unlock(&s
->lock
);
2296 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
2304 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2305 options
= qdict_new();
2306 qdict_put(options
, "driver", qstring_from_str("qcow2"));
2307 blk
= blk_new_open(filename
, NULL
, options
,
2308 BDRV_O_RDWR
| BDRV_O_NO_BACKING
, &local_err
);
2310 error_propagate(errp
, local_err
);
2323 static int qcow2_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
2325 char *backing_file
= NULL
;
2326 char *backing_fmt
= NULL
;
2330 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
2331 PreallocMode prealloc
;
2333 uint64_t refcount_bits
= 16;
2335 Error
*local_err
= NULL
;
2338 /* Read out options */
2339 size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2341 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
2342 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
2343 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ENCRYPT
, false)) {
2344 flags
|= BLOCK_FLAG_ENCRYPT
;
2346 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2347 DEFAULT_CLUSTER_SIZE
);
2348 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2349 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
2350 PREALLOC_MODE__MAX
, PREALLOC_MODE_OFF
,
2353 error_propagate(errp
, local_err
);
2358 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2360 /* keep the default */
2361 } else if (!strcmp(buf
, "0.10")) {
2363 } else if (!strcmp(buf
, "1.1")) {
2366 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2371 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_LAZY_REFCOUNTS
, false)) {
2372 flags
|= BLOCK_FLAG_LAZY_REFCOUNTS
;
2375 if (backing_file
&& prealloc
!= PREALLOC_MODE_OFF
) {
2376 error_setg(errp
, "Backing file and preallocation cannot be used at "
2382 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
2383 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2384 "level 1.1 and above (use compat=1.1 or greater)");
2389 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
,
2391 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2392 error_setg(errp
, "Refcount width must be a power of two and may not "
2398 if (version
< 3 && refcount_bits
!= 16) {
2399 error_setg(errp
, "Different refcount widths than 16 bits require "
2400 "compatibility level 1.1 or above (use compat=1.1 or "
2406 refcount_order
= ctz32(refcount_bits
);
2408 ret
= qcow2_create2(filename
, size
, backing_file
, backing_fmt
, flags
,
2409 cluster_size
, prealloc
, opts
, version
, refcount_order
,
2411 error_propagate(errp
, local_err
);
2414 g_free(backing_file
);
2415 g_free(backing_fmt
);
2421 static bool is_zero_sectors(BlockDriverState
*bs
, int64_t start
,
2425 BlockDriverState
*file
;
2431 res
= bdrv_get_block_status_above(bs
, NULL
, start
, count
,
2433 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== count
;
2436 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
2437 int64_t offset
, int count
, BdrvRequestFlags flags
)
2440 BDRVQcow2State
*s
= bs
->opaque
;
2442 uint32_t head
= offset
% s
->cluster_size
;
2443 uint32_t tail
= (offset
+ count
) % s
->cluster_size
;
2445 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, count
);
2448 int64_t cl_start
= (offset
- head
) >> BDRV_SECTOR_BITS
;
2452 assert(head
+ count
<= s
->cluster_size
);
2454 /* check whether remainder of cluster already reads as zero */
2455 if (!(is_zero_sectors(bs
, cl_start
,
2456 DIV_ROUND_UP(head
, BDRV_SECTOR_SIZE
)) &&
2457 is_zero_sectors(bs
, (offset
+ count
) >> BDRV_SECTOR_BITS
,
2458 DIV_ROUND_UP(-tail
& (s
->cluster_size
- 1),
2459 BDRV_SECTOR_SIZE
)))) {
2463 qemu_co_mutex_lock(&s
->lock
);
2464 /* We can have new write after previous check */
2465 offset
= cl_start
<< BDRV_SECTOR_BITS
;
2466 count
= s
->cluster_size
;
2467 nr
= s
->cluster_size
;
2468 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
2469 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&& ret
!= QCOW2_CLUSTER_ZERO
) {
2470 qemu_co_mutex_unlock(&s
->lock
);
2474 qemu_co_mutex_lock(&s
->lock
);
2477 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, count
);
2479 /* Whatever is left can use real zero clusters */
2480 ret
= qcow2_zero_clusters(bs
, offset
, count
>> BDRV_SECTOR_BITS
);
2481 qemu_co_mutex_unlock(&s
->lock
);
2486 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
2487 int64_t offset
, int count
)
2490 BDRVQcow2State
*s
= bs
->opaque
;
2492 qemu_co_mutex_lock(&s
->lock
);
2493 ret
= qcow2_discard_clusters(bs
, offset
, count
>> BDRV_SECTOR_BITS
,
2494 QCOW2_DISCARD_REQUEST
, false);
2495 qemu_co_mutex_unlock(&s
->lock
);
2499 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
)
2501 BDRVQcow2State
*s
= bs
->opaque
;
2502 int64_t new_l1_size
;
2506 error_report("The new size must be a multiple of 512");
2510 /* cannot proceed if image has snapshots */
2511 if (s
->nb_snapshots
) {
2512 error_report("Can't resize an image which has snapshots");
2516 /* shrinking is currently not supported */
2517 if (offset
< bs
->total_sectors
* 512) {
2518 error_report("qcow2 doesn't support shrinking images yet");
2522 new_l1_size
= size_to_l1(s
, offset
);
2523 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
2528 /* write updated header.size */
2529 offset
= cpu_to_be64(offset
);
2530 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
2531 &offset
, sizeof(uint64_t));
2536 s
->l1_vm_state_index
= new_l1_size
;
2540 /* XXX: put compressed sectors first, then all the cluster aligned
2541 tables to avoid losing bytes in alignment */
2542 static coroutine_fn
int
2543 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
2544 uint64_t bytes
, QEMUIOVector
*qiov
)
2546 BDRVQcow2State
*s
= bs
->opaque
;
2547 QEMUIOVector hd_qiov
;
2551 uint8_t *buf
, *out_buf
;
2552 uint64_t cluster_offset
;
2555 /* align end of file to a sector boundary to ease reading with
2556 sector based I/Os */
2557 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
2558 return bdrv_truncate(bs
->file
->bs
, cluster_offset
);
2561 buf
= qemu_blockalign(bs
, s
->cluster_size
);
2562 if (bytes
!= s
->cluster_size
) {
2563 if (bytes
> s
->cluster_size
||
2564 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
2569 /* Zero-pad last write if image size is not cluster aligned */
2570 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
2572 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
2574 out_buf
= g_malloc(s
->cluster_size
);
2576 /* best compression, small window, no zlib header */
2577 memset(&strm
, 0, sizeof(strm
));
2578 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
2580 9, Z_DEFAULT_STRATEGY
);
2586 strm
.avail_in
= s
->cluster_size
;
2587 strm
.next_in
= (uint8_t *)buf
;
2588 strm
.avail_out
= s
->cluster_size
;
2589 strm
.next_out
= out_buf
;
2591 ret
= deflate(&strm
, Z_FINISH
);
2592 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
2597 out_len
= strm
.next_out
- out_buf
;
2601 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
2602 /* could not compress: write normal cluster */
2603 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
2610 qemu_co_mutex_lock(&s
->lock
);
2612 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
2613 if (!cluster_offset
) {
2614 qemu_co_mutex_unlock(&s
->lock
);
2618 cluster_offset
&= s
->cluster_offset_mask
;
2620 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
2621 qemu_co_mutex_unlock(&s
->lock
);
2626 iov
= (struct iovec
) {
2627 .iov_base
= out_buf
,
2630 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
2632 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
2633 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
2645 static int make_completely_empty(BlockDriverState
*bs
)
2647 BDRVQcow2State
*s
= bs
->opaque
;
2648 int ret
, l1_clusters
;
2650 uint64_t *new_reftable
= NULL
;
2651 uint64_t rt_entry
, l1_size2
;
2654 uint64_t reftable_offset
;
2655 uint32_t reftable_clusters
;
2656 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
2658 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
2663 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
2668 /* Refcounts will be broken utterly */
2669 ret
= qcow2_mark_dirty(bs
);
2674 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
2676 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
2677 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
2679 /* After this call, neither the in-memory nor the on-disk refcount
2680 * information accurately describe the actual references */
2682 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
2683 l1_clusters
* s
->cluster_size
, 0);
2685 goto fail_broken_refcounts
;
2687 memset(s
->l1_table
, 0, l1_size2
);
2689 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
2691 /* Overwrite enough clusters at the beginning of the sectors to place
2692 * the refcount table, a refcount block and the L1 table in; this may
2693 * overwrite parts of the existing refcount and L1 table, which is not
2694 * an issue because the dirty flag is set, complete data loss is in fact
2695 * desired and partial data loss is consequently fine as well */
2696 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
2697 (2 + l1_clusters
) * s
->cluster_size
, 0);
2698 /* This call (even if it failed overall) may have overwritten on-disk
2699 * refcount structures; in that case, the in-memory refcount information
2700 * will probably differ from the on-disk information which makes the BDS
2703 goto fail_broken_refcounts
;
2706 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
2707 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
2709 /* "Create" an empty reftable (one cluster) directly after the image
2710 * header and an empty L1 table three clusters after the image header;
2711 * the cluster between those two will be used as the first refblock */
2712 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
2713 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
2714 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
2715 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
2716 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
2718 goto fail_broken_refcounts
;
2721 s
->l1_table_offset
= 3 * s
->cluster_size
;
2723 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
2724 if (!new_reftable
) {
2726 goto fail_broken_refcounts
;
2729 s
->refcount_table_offset
= s
->cluster_size
;
2730 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
2732 g_free(s
->refcount_table
);
2733 s
->refcount_table
= new_reftable
;
2734 new_reftable
= NULL
;
2736 /* Now the in-memory refcount information again corresponds to the on-disk
2737 * information (reftable is empty and no refblocks (the refblock cache is
2738 * empty)); however, this means some clusters (e.g. the image header) are
2739 * referenced, but not refcounted, but the normal qcow2 code assumes that
2740 * the in-memory information is always correct */
2742 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
2744 /* Enter the first refblock into the reftable */
2745 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
2746 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
2747 &rt_entry
, sizeof(rt_entry
));
2749 goto fail_broken_refcounts
;
2751 s
->refcount_table
[0] = 2 * s
->cluster_size
;
2753 s
->free_cluster_index
= 0;
2754 assert(3 + l1_clusters
<= s
->refcount_block_size
);
2755 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
2758 goto fail_broken_refcounts
;
2759 } else if (offset
> 0) {
2760 error_report("First cluster in emptied image is in use");
2764 /* Now finally the in-memory information corresponds to the on-disk
2765 * structures and is correct */
2766 ret
= qcow2_mark_clean(bs
);
2771 ret
= bdrv_truncate(bs
->file
->bs
, (3 + l1_clusters
) * s
->cluster_size
);
2778 fail_broken_refcounts
:
2779 /* The BDS is unusable at this point. If we wanted to make it usable, we
2780 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2781 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2782 * again. However, because the functions which could have caused this error
2783 * path to be taken are used by those functions as well, it's very likely
2784 * that that sequence will fail as well. Therefore, just eject the BDS. */
2788 g_free(new_reftable
);
2792 static int qcow2_make_empty(BlockDriverState
*bs
)
2794 BDRVQcow2State
*s
= bs
->opaque
;
2795 uint64_t start_sector
;
2796 int sector_step
= INT_MAX
/ BDRV_SECTOR_SIZE
;
2797 int l1_clusters
, ret
= 0;
2799 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
2801 if (s
->qcow_version
>= 3 && !s
->snapshots
&&
2802 3 + l1_clusters
<= s
->refcount_block_size
) {
2803 /* The following function only works for qcow2 v3 images (it requires
2804 * the dirty flag) and only as long as there are no snapshots (because
2805 * it completely empties the image). Furthermore, the L1 table and three
2806 * additional clusters (image header, refcount table, one refcount
2807 * block) have to fit inside one refcount block. */
2808 return make_completely_empty(bs
);
2811 /* This fallback code simply discards every active cluster; this is slow,
2812 * but works in all cases */
2813 for (start_sector
= 0; start_sector
< bs
->total_sectors
;
2814 start_sector
+= sector_step
)
2816 /* As this function is generally used after committing an external
2817 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2818 * default action for this kind of discard is to pass the discard,
2819 * which will ideally result in an actually smaller image file, as
2820 * is probably desired. */
2821 ret
= qcow2_discard_clusters(bs
, start_sector
* BDRV_SECTOR_SIZE
,
2823 bs
->total_sectors
- start_sector
),
2824 QCOW2_DISCARD_SNAPSHOT
, true);
2833 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
2835 BDRVQcow2State
*s
= bs
->opaque
;
2838 qemu_co_mutex_lock(&s
->lock
);
2839 ret
= qcow2_cache_write(bs
, s
->l2_table_cache
);
2841 qemu_co_mutex_unlock(&s
->lock
);
2845 if (qcow2_need_accurate_refcounts(s
)) {
2846 ret
= qcow2_cache_write(bs
, s
->refcount_block_cache
);
2848 qemu_co_mutex_unlock(&s
->lock
);
2852 qemu_co_mutex_unlock(&s
->lock
);
2857 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2859 BDRVQcow2State
*s
= bs
->opaque
;
2860 bdi
->unallocated_blocks_are_zero
= true;
2861 bdi
->can_write_zeroes_with_unmap
= (s
->qcow_version
>= 3);
2862 bdi
->cluster_size
= s
->cluster_size
;
2863 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
2867 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
2869 BDRVQcow2State
*s
= bs
->opaque
;
2870 ImageInfoSpecific
*spec_info
= g_new(ImageInfoSpecific
, 1);
2872 *spec_info
= (ImageInfoSpecific
){
2873 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
2874 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
2876 if (s
->qcow_version
== 2) {
2877 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
2878 .compat
= g_strdup("0.10"),
2879 .refcount_bits
= s
->refcount_bits
,
2881 } else if (s
->qcow_version
== 3) {
2882 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
2883 .compat
= g_strdup("1.1"),
2884 .lazy_refcounts
= s
->compatible_features
&
2885 QCOW2_COMPAT_LAZY_REFCOUNTS
,
2886 .has_lazy_refcounts
= true,
2887 .corrupt
= s
->incompatible_features
&
2888 QCOW2_INCOMPAT_CORRUPT
,
2889 .has_corrupt
= true,
2890 .refcount_bits
= s
->refcount_bits
,
2893 /* if this assertion fails, this probably means a new version was
2894 * added without having it covered here */
2902 static void dump_refcounts(BlockDriverState
*bs
)
2904 BDRVQcow2State
*s
= bs
->opaque
;
2905 int64_t nb_clusters
, k
, k1
, size
;
2908 size
= bdrv_getlength(bs
->file
->bs
);
2909 nb_clusters
= size_to_clusters(s
, size
);
2910 for(k
= 0; k
< nb_clusters
;) {
2912 refcount
= get_refcount(bs
, k
);
2914 while (k
< nb_clusters
&& get_refcount(bs
, k
) == refcount
)
2916 printf("%" PRId64
": refcount=%d nb=%" PRId64
"\n", k
, refcount
,
2922 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
2925 BDRVQcow2State
*s
= bs
->opaque
;
2927 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
2928 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
2929 qiov
->size
, qiov
, 0);
2932 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
2935 BDRVQcow2State
*s
= bs
->opaque
;
2937 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
2938 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
2939 qiov
->size
, qiov
, 0);
2943 * Downgrades an image's version. To achieve this, any incompatible features
2944 * have to be removed.
2946 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
2947 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
)
2949 BDRVQcow2State
*s
= bs
->opaque
;
2950 int current_version
= s
->qcow_version
;
2953 if (target_version
== current_version
) {
2955 } else if (target_version
> current_version
) {
2957 } else if (target_version
!= 2) {
2961 if (s
->refcount_order
!= 4) {
2962 error_report("compat=0.10 requires refcount_bits=16");
2966 /* clear incompatible features */
2967 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
2968 ret
= qcow2_mark_clean(bs
);
2974 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2975 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2976 * best thing to do anyway */
2978 if (s
->incompatible_features
) {
2982 /* since we can ignore compatible features, we can set them to 0 as well */
2983 s
->compatible_features
= 0;
2984 /* if lazy refcounts have been used, they have already been fixed through
2985 * clearing the dirty flag */
2987 /* clearing autoclear features is trivial */
2988 s
->autoclear_features
= 0;
2990 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
2995 s
->qcow_version
= target_version
;
2996 ret
= qcow2_update_header(bs
);
2998 s
->qcow_version
= current_version
;
3004 typedef enum Qcow2AmendOperation
{
3005 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3006 * statically initialized to so that the helper CB can discern the first
3007 * invocation from an operation change */
3008 QCOW2_NO_OPERATION
= 0,
3010 QCOW2_CHANGING_REFCOUNT_ORDER
,
3012 } Qcow2AmendOperation
;
3014 typedef struct Qcow2AmendHelperCBInfo
{
3015 /* The code coordinating the amend operations should only modify
3016 * these four fields; the rest will be managed by the CB */
3017 BlockDriverAmendStatusCB
*original_status_cb
;
3018 void *original_cb_opaque
;
3020 Qcow2AmendOperation current_operation
;
3022 /* Total number of operations to perform (only set once) */
3023 int total_operations
;
3025 /* The following fields are managed by the CB */
3027 /* Number of operations completed */
3028 int operations_completed
;
3030 /* Cumulative offset of all completed operations */
3031 int64_t offset_completed
;
3033 Qcow2AmendOperation last_operation
;
3034 int64_t last_work_size
;
3035 } Qcow2AmendHelperCBInfo
;
3037 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
3038 int64_t operation_offset
,
3039 int64_t operation_work_size
, void *opaque
)
3041 Qcow2AmendHelperCBInfo
*info
= opaque
;
3042 int64_t current_work_size
;
3043 int64_t projected_work_size
;
3045 if (info
->current_operation
!= info
->last_operation
) {
3046 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
3047 info
->offset_completed
+= info
->last_work_size
;
3048 info
->operations_completed
++;
3051 info
->last_operation
= info
->current_operation
;
3054 assert(info
->total_operations
> 0);
3055 assert(info
->operations_completed
< info
->total_operations
);
3057 info
->last_work_size
= operation_work_size
;
3059 current_work_size
= info
->offset_completed
+ operation_work_size
;
3061 /* current_work_size is the total work size for (operations_completed + 1)
3062 * operations (which includes this one), so multiply it by the number of
3063 * operations not covered and divide it by the number of operations
3064 * covered to get a projection for the operations not covered */
3065 projected_work_size
= current_work_size
* (info
->total_operations
-
3066 info
->operations_completed
- 1)
3067 / (info
->operations_completed
+ 1);
3069 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
3070 current_work_size
+ projected_work_size
,
3071 info
->original_cb_opaque
);
3074 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
3075 BlockDriverAmendStatusCB
*status_cb
,
3078 BDRVQcow2State
*s
= bs
->opaque
;
3079 int old_version
= s
->qcow_version
, new_version
= old_version
;
3080 uint64_t new_size
= 0;
3081 const char *backing_file
= NULL
, *backing_format
= NULL
;
3082 bool lazy_refcounts
= s
->use_lazy_refcounts
;
3083 const char *compat
= NULL
;
3084 uint64_t cluster_size
= s
->cluster_size
;
3086 int refcount_bits
= s
->refcount_bits
;
3088 QemuOptDesc
*desc
= opts
->list
->desc
;
3089 Qcow2AmendHelperCBInfo helper_cb_info
;
3091 while (desc
&& desc
->name
) {
3092 if (!qemu_opt_find(opts
, desc
->name
)) {
3093 /* only change explicitly defined options */
3098 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
3099 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
3101 /* preserve default */
3102 } else if (!strcmp(compat
, "0.10")) {
3104 } else if (!strcmp(compat
, "1.1")) {
3107 error_report("Unknown compatibility level %s", compat
);
3110 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
3111 error_report("Cannot change preallocation mode");
3113 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
3114 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
3115 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
3116 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
3117 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
3118 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
3119 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
3120 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
3123 if (encrypt
!= !!s
->cipher
) {
3124 error_report("Changing the encryption flag is not supported");
3127 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
3128 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
3130 if (cluster_size
!= s
->cluster_size
) {
3131 error_report("Changing the cluster size is not supported");
3134 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
3135 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
3137 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
3138 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
3141 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
3142 !is_power_of_2(refcount_bits
))
3144 error_report("Refcount width must be a power of two and may "
3145 "not exceed 64 bits");
3149 /* if this point is reached, this probably means a new option was
3150 * added without having it covered here */
3157 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
3158 .original_status_cb
= status_cb
,
3159 .original_cb_opaque
= cb_opaque
,
3160 .total_operations
= (new_version
< old_version
)
3161 + (s
->refcount_bits
!= refcount_bits
)
3164 /* Upgrade first (some features may require compat=1.1) */
3165 if (new_version
> old_version
) {
3166 s
->qcow_version
= new_version
;
3167 ret
= qcow2_update_header(bs
);
3169 s
->qcow_version
= old_version
;
3174 if (s
->refcount_bits
!= refcount_bits
) {
3175 int refcount_order
= ctz32(refcount_bits
);
3176 Error
*local_error
= NULL
;
3178 if (new_version
< 3 && refcount_bits
!= 16) {
3179 error_report("Different refcount widths than 16 bits require "
3180 "compatibility level 1.1 or above (use compat=1.1 or "
3185 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
3186 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
3187 &qcow2_amend_helper_cb
,
3188 &helper_cb_info
, &local_error
);
3190 error_report_err(local_error
);
3195 if (backing_file
|| backing_format
) {
3196 ret
= qcow2_change_backing_file(bs
,
3197 backing_file
?: s
->image_backing_file
,
3198 backing_format
?: s
->image_backing_format
);
3204 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
3205 if (lazy_refcounts
) {
3206 if (new_version
< 3) {
3207 error_report("Lazy refcounts only supported with compatibility "
3208 "level 1.1 and above (use compat=1.1 or greater)");
3211 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
3212 ret
= qcow2_update_header(bs
);
3214 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
3217 s
->use_lazy_refcounts
= true;
3219 /* make image clean first */
3220 ret
= qcow2_mark_clean(bs
);
3224 /* now disallow lazy refcounts */
3225 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
3226 ret
= qcow2_update_header(bs
);
3228 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
3231 s
->use_lazy_refcounts
= false;
3236 ret
= bdrv_truncate(bs
, new_size
);
3242 /* Downgrade last (so unsupported features can be removed before) */
3243 if (new_version
< old_version
) {
3244 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
3245 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
3256 * If offset or size are negative, respectively, they will not be included in
3257 * the BLOCK_IMAGE_CORRUPTED event emitted.
3258 * fatal will be ignored for read-only BDS; corruptions found there will always
3259 * be considered non-fatal.
3261 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
3262 int64_t size
, const char *message_format
, ...)
3264 BDRVQcow2State
*s
= bs
->opaque
;
3265 const char *node_name
;
3269 fatal
= fatal
&& !bs
->read_only
;
3271 if (s
->signaled_corruption
&&
3272 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
3277 va_start(ap
, message_format
);
3278 message
= g_strdup_vprintf(message_format
, ap
);
3282 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
3283 "corruption events will be suppressed\n", message
);
3285 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
3286 "corruption events will be suppressed\n", message
);
3289 node_name
= bdrv_get_node_name(bs
);
3290 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
3291 *node_name
!= '\0', node_name
,
3292 message
, offset
>= 0, offset
,
3294 fatal
, &error_abort
);
3298 qcow2_mark_corrupt(bs
);
3299 bs
->drv
= NULL
; /* make BDS unusable */
3302 s
->signaled_corruption
= true;
3305 static QemuOptsList qcow2_create_opts
= {
3306 .name
= "qcow2-create-opts",
3307 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
3310 .name
= BLOCK_OPT_SIZE
,
3311 .type
= QEMU_OPT_SIZE
,
3312 .help
= "Virtual disk size"
3315 .name
= BLOCK_OPT_COMPAT_LEVEL
,
3316 .type
= QEMU_OPT_STRING
,
3317 .help
= "Compatibility level (0.10 or 1.1)"
3320 .name
= BLOCK_OPT_BACKING_FILE
,
3321 .type
= QEMU_OPT_STRING
,
3322 .help
= "File name of a base image"
3325 .name
= BLOCK_OPT_BACKING_FMT
,
3326 .type
= QEMU_OPT_STRING
,
3327 .help
= "Image format of the base image"
3330 .name
= BLOCK_OPT_ENCRYPT
,
3331 .type
= QEMU_OPT_BOOL
,
3332 .help
= "Encrypt the image",
3333 .def_value_str
= "off"
3336 .name
= BLOCK_OPT_CLUSTER_SIZE
,
3337 .type
= QEMU_OPT_SIZE
,
3338 .help
= "qcow2 cluster size",
3339 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
3342 .name
= BLOCK_OPT_PREALLOC
,
3343 .type
= QEMU_OPT_STRING
,
3344 .help
= "Preallocation mode (allowed values: off, metadata, "
3348 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
3349 .type
= QEMU_OPT_BOOL
,
3350 .help
= "Postpone refcount updates",
3351 .def_value_str
= "off"
3354 .name
= BLOCK_OPT_REFCOUNT_BITS
,
3355 .type
= QEMU_OPT_NUMBER
,
3356 .help
= "Width of a reference count entry in bits",
3357 .def_value_str
= "16"
3359 { /* end of list */ }
3363 BlockDriver bdrv_qcow2
= {
3364 .format_name
= "qcow2",
3365 .instance_size
= sizeof(BDRVQcow2State
),
3366 .bdrv_probe
= qcow2_probe
,
3367 .bdrv_open
= qcow2_open
,
3368 .bdrv_close
= qcow2_close
,
3369 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
3370 .bdrv_reopen_commit
= qcow2_reopen_commit
,
3371 .bdrv_reopen_abort
= qcow2_reopen_abort
,
3372 .bdrv_join_options
= qcow2_join_options
,
3373 .bdrv_create
= qcow2_create
,
3374 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3375 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
3376 .bdrv_set_key
= qcow2_set_key
,
3378 .bdrv_co_preadv
= qcow2_co_preadv
,
3379 .bdrv_co_pwritev
= qcow2_co_pwritev
,
3380 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
3382 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
3383 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
3384 .bdrv_truncate
= qcow2_truncate
,
3385 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
3386 .bdrv_make_empty
= qcow2_make_empty
,
3388 .bdrv_snapshot_create
= qcow2_snapshot_create
,
3389 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
3390 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
3391 .bdrv_snapshot_list
= qcow2_snapshot_list
,
3392 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
3393 .bdrv_get_info
= qcow2_get_info
,
3394 .bdrv_get_specific_info
= qcow2_get_specific_info
,
3396 .bdrv_save_vmstate
= qcow2_save_vmstate
,
3397 .bdrv_load_vmstate
= qcow2_load_vmstate
,
3399 .supports_backing
= true,
3400 .bdrv_change_backing_file
= qcow2_change_backing_file
,
3402 .bdrv_refresh_limits
= qcow2_refresh_limits
,
3403 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
3404 .bdrv_inactivate
= qcow2_inactivate
,
3406 .create_opts
= &qcow2_create_opts
,
3407 .bdrv_check
= qcow2_check
,
3408 .bdrv_amend_options
= qcow2_amend_options
,
3410 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
3411 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
3414 static void bdrv_qcow2_init(void)
3416 bdrv_register(&bdrv_qcow2
);
3419 block_init(bdrv_qcow2_init
);