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_into_cluster(s
, offset
) != 0) {
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
);
672 if (r
->cache_clean_interval
!= 0) {
673 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
674 " not supported on this host");
679 if (r
->cache_clean_interval
> UINT_MAX
) {
680 error_setg(errp
, "Cache clean interval too big");
685 /* lazy-refcounts; flush if going from enabled to disabled */
686 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
687 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
688 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
689 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
690 "qemu 1.1 compatibility level");
695 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
696 ret
= qcow2_mark_clean(bs
);
698 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
703 /* Overlap check options */
704 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
705 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
706 if (opt_overlap_check_template
&& opt_overlap_check
&&
707 strcmp(opt_overlap_check_template
, opt_overlap_check
))
709 error_setg(errp
, "Conflicting values for qcow2 options '"
710 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
711 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
715 if (!opt_overlap_check
) {
716 opt_overlap_check
= opt_overlap_check_template
?: "cached";
719 if (!strcmp(opt_overlap_check
, "none")) {
720 overlap_check_template
= 0;
721 } else if (!strcmp(opt_overlap_check
, "constant")) {
722 overlap_check_template
= QCOW2_OL_CONSTANT
;
723 } else if (!strcmp(opt_overlap_check
, "cached")) {
724 overlap_check_template
= QCOW2_OL_CACHED
;
725 } else if (!strcmp(opt_overlap_check
, "all")) {
726 overlap_check_template
= QCOW2_OL_ALL
;
728 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
729 "'overlap-check'. Allowed are any of the following: "
730 "none, constant, cached, all", opt_overlap_check
);
735 r
->overlap_check
= 0;
736 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
737 /* overlap-check defines a template bitmask, but every flag may be
738 * overwritten through the associated boolean option */
740 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
741 overlap_check_template
& (1 << i
)) << i
;
744 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
745 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
746 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
747 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
748 flags
& BDRV_O_UNMAP
);
749 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
750 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
751 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
752 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
761 static void qcow2_update_options_commit(BlockDriverState
*bs
,
764 BDRVQcow2State
*s
= bs
->opaque
;
767 if (s
->l2_table_cache
) {
768 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
770 if (s
->refcount_block_cache
) {
771 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
773 s
->l2_table_cache
= r
->l2_table_cache
;
774 s
->refcount_block_cache
= r
->refcount_block_cache
;
776 s
->overlap_check
= r
->overlap_check
;
777 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
779 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
780 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
783 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
784 cache_clean_timer_del(bs
);
785 s
->cache_clean_interval
= r
->cache_clean_interval
;
786 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
790 static void qcow2_update_options_abort(BlockDriverState
*bs
,
793 if (r
->l2_table_cache
) {
794 qcow2_cache_destroy(bs
, r
->l2_table_cache
);
796 if (r
->refcount_block_cache
) {
797 qcow2_cache_destroy(bs
, r
->refcount_block_cache
);
801 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
802 int flags
, Error
**errp
)
804 Qcow2ReopenState r
= {};
807 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
809 qcow2_update_options_commit(bs
, &r
);
811 qcow2_update_options_abort(bs
, &r
);
817 static int qcow2_do_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
820 BDRVQcow2State
*s
= bs
->opaque
;
824 Error
*local_err
= NULL
;
826 uint64_t l1_vm_state_index
;
828 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
830 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
833 be32_to_cpus(&header
.magic
);
834 be32_to_cpus(&header
.version
);
835 be64_to_cpus(&header
.backing_file_offset
);
836 be32_to_cpus(&header
.backing_file_size
);
837 be64_to_cpus(&header
.size
);
838 be32_to_cpus(&header
.cluster_bits
);
839 be32_to_cpus(&header
.crypt_method
);
840 be64_to_cpus(&header
.l1_table_offset
);
841 be32_to_cpus(&header
.l1_size
);
842 be64_to_cpus(&header
.refcount_table_offset
);
843 be32_to_cpus(&header
.refcount_table_clusters
);
844 be64_to_cpus(&header
.snapshots_offset
);
845 be32_to_cpus(&header
.nb_snapshots
);
847 if (header
.magic
!= QCOW_MAGIC
) {
848 error_setg(errp
, "Image is not in qcow2 format");
852 if (header
.version
< 2 || header
.version
> 3) {
853 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
858 s
->qcow_version
= header
.version
;
860 /* Initialise cluster size */
861 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
862 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
863 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
864 header
.cluster_bits
);
869 s
->cluster_bits
= header
.cluster_bits
;
870 s
->cluster_size
= 1 << s
->cluster_bits
;
871 s
->cluster_sectors
= 1 << (s
->cluster_bits
- 9);
873 /* Initialise version 3 header fields */
874 if (header
.version
== 2) {
875 header
.incompatible_features
= 0;
876 header
.compatible_features
= 0;
877 header
.autoclear_features
= 0;
878 header
.refcount_order
= 4;
879 header
.header_length
= 72;
881 be64_to_cpus(&header
.incompatible_features
);
882 be64_to_cpus(&header
.compatible_features
);
883 be64_to_cpus(&header
.autoclear_features
);
884 be32_to_cpus(&header
.refcount_order
);
885 be32_to_cpus(&header
.header_length
);
887 if (header
.header_length
< 104) {
888 error_setg(errp
, "qcow2 header too short");
894 if (header
.header_length
> s
->cluster_size
) {
895 error_setg(errp
, "qcow2 header exceeds cluster size");
900 if (header
.header_length
> sizeof(header
)) {
901 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
902 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
903 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
904 s
->unknown_header_fields_size
);
906 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
912 if (header
.backing_file_offset
> s
->cluster_size
) {
913 error_setg(errp
, "Invalid backing file offset");
918 if (header
.backing_file_offset
) {
919 ext_end
= header
.backing_file_offset
;
921 ext_end
= 1 << header
.cluster_bits
;
924 /* Handle feature bits */
925 s
->incompatible_features
= header
.incompatible_features
;
926 s
->compatible_features
= header
.compatible_features
;
927 s
->autoclear_features
= header
.autoclear_features
;
929 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
930 void *feature_table
= NULL
;
931 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
932 &feature_table
, NULL
);
933 report_unsupported_feature(errp
, feature_table
,
934 s
->incompatible_features
&
935 ~QCOW2_INCOMPAT_MASK
);
937 g_free(feature_table
);
941 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
942 /* Corrupt images may not be written to unless they are being repaired
944 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
945 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
952 /* Check support for various header values */
953 if (header
.refcount_order
> 6) {
954 error_setg(errp
, "Reference count entry width too large; may not "
959 s
->refcount_order
= header
.refcount_order
;
960 s
->refcount_bits
= 1 << s
->refcount_order
;
961 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
962 s
->refcount_max
+= s
->refcount_max
- 1;
964 if (header
.crypt_method
> QCOW_CRYPT_AES
) {
965 error_setg(errp
, "Unsupported encryption method: %" PRIu32
,
966 header
.crypt_method
);
970 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128
,
971 QCRYPTO_CIPHER_MODE_CBC
)) {
972 error_setg(errp
, "AES cipher not available");
976 s
->crypt_method_header
= header
.crypt_method
;
977 if (s
->crypt_method_header
) {
978 if (bdrv_uses_whitelist() &&
979 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
981 "Use of AES-CBC encrypted qcow2 images is no longer "
982 "supported in system emulators");
983 error_append_hint(errp
,
984 "You can use 'qemu-img convert' to convert your "
985 "image to an alternative supported format, such "
986 "as unencrypted qcow2, or raw with the LUKS "
987 "format instead.\n");
992 bs
->encrypted
= true;
995 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
996 s
->l2_size
= 1 << s
->l2_bits
;
997 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
998 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
999 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1000 bs
->total_sectors
= header
.size
/ 512;
1001 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1002 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1003 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1005 s
->refcount_table_offset
= header
.refcount_table_offset
;
1006 s
->refcount_table_size
=
1007 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1009 if (header
.refcount_table_clusters
> qcow2_max_refcount_clusters(s
)) {
1010 error_setg(errp
, "Reference count table too large");
1015 ret
= validate_table_offset(bs
, s
->refcount_table_offset
,
1016 s
->refcount_table_size
, sizeof(uint64_t));
1018 error_setg(errp
, "Invalid reference count table offset");
1022 /* Snapshot table offset/length */
1023 if (header
.nb_snapshots
> QCOW_MAX_SNAPSHOTS
) {
1024 error_setg(errp
, "Too many snapshots");
1029 ret
= validate_table_offset(bs
, header
.snapshots_offset
,
1030 header
.nb_snapshots
,
1031 sizeof(QCowSnapshotHeader
));
1033 error_setg(errp
, "Invalid snapshot table offset");
1037 /* read the level 1 table */
1038 if (header
.l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
1039 error_setg(errp
, "Active L1 table too large");
1043 s
->l1_size
= header
.l1_size
;
1045 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1046 if (l1_vm_state_index
> INT_MAX
) {
1047 error_setg(errp
, "Image is too big");
1051 s
->l1_vm_state_index
= l1_vm_state_index
;
1053 /* the L1 table must contain at least enough entries to put
1054 header.size bytes */
1055 if (s
->l1_size
< s
->l1_vm_state_index
) {
1056 error_setg(errp
, "L1 table is too small");
1061 ret
= validate_table_offset(bs
, header
.l1_table_offset
,
1062 header
.l1_size
, sizeof(uint64_t));
1064 error_setg(errp
, "Invalid L1 table offset");
1067 s
->l1_table_offset
= header
.l1_table_offset
;
1070 if (s
->l1_size
> 0) {
1071 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1072 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
1073 if (s
->l1_table
== NULL
) {
1074 error_setg(errp
, "Could not allocate L1 table");
1078 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1079 s
->l1_size
* sizeof(uint64_t));
1081 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1084 for(i
= 0;i
< s
->l1_size
; i
++) {
1085 be64_to_cpus(&s
->l1_table
[i
]);
1089 /* Parse driver-specific options */
1090 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1095 s
->cluster_cache
= g_malloc(s
->cluster_size
);
1096 /* one more sector for decompressed data alignment */
1097 s
->cluster_data
= qemu_try_blockalign(bs
->file
->bs
, QCOW_MAX_CRYPT_CLUSTERS
1098 * s
->cluster_size
+ 512);
1099 if (s
->cluster_data
== NULL
) {
1100 error_setg(errp
, "Could not allocate temporary cluster buffer");
1105 s
->cluster_cache_offset
= -1;
1108 ret
= qcow2_refcount_init(bs
);
1110 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1114 QLIST_INIT(&s
->cluster_allocs
);
1115 QTAILQ_INIT(&s
->discards
);
1117 /* read qcow2 extensions */
1118 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1120 error_propagate(errp
, local_err
);
1125 /* read the backing file name */
1126 if (header
.backing_file_offset
!= 0) {
1127 len
= header
.backing_file_size
;
1128 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1129 len
>= sizeof(bs
->backing_file
)) {
1130 error_setg(errp
, "Backing file name too long");
1134 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1135 bs
->backing_file
, len
);
1137 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1140 bs
->backing_file
[len
] = '\0';
1141 s
->image_backing_file
= g_strdup(bs
->backing_file
);
1144 /* Internal snapshots */
1145 s
->snapshots_offset
= header
.snapshots_offset
;
1146 s
->nb_snapshots
= header
.nb_snapshots
;
1148 ret
= qcow2_read_snapshots(bs
);
1150 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1154 /* Clear unknown autoclear feature bits */
1155 if (!bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
) && s
->autoclear_features
) {
1156 s
->autoclear_features
= 0;
1157 ret
= qcow2_update_header(bs
);
1159 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1164 /* Initialise locks */
1165 qemu_co_mutex_init(&s
->lock
);
1166 bs
->supported_zero_flags
= BDRV_REQ_MAY_UNMAP
;
1168 /* Repair image if dirty */
1169 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1170 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1171 BdrvCheckResult result
= {0};
1173 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1175 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1182 BdrvCheckResult result
= {0};
1183 qcow2_check_refcounts(bs
, &result
, 0);
1189 g_free(s
->unknown_header_fields
);
1190 cleanup_unknown_header_ext(bs
);
1191 qcow2_free_snapshots(bs
);
1192 qcow2_refcount_close(bs
);
1193 qemu_vfree(s
->l1_table
);
1194 /* else pre-write overlap checks in cache_destroy may crash */
1196 cache_clean_timer_del(bs
);
1197 if (s
->l2_table_cache
) {
1198 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1200 if (s
->refcount_block_cache
) {
1201 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1203 g_free(s
->cluster_cache
);
1204 qemu_vfree(s
->cluster_data
);
1208 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1211 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1217 return qcow2_do_open(bs
, options
, flags
, errp
);
1220 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1222 BDRVQcow2State
*s
= bs
->opaque
;
1224 if (bs
->encrypted
) {
1225 /* Encryption works on a sector granularity */
1226 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1228 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1229 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1232 static int qcow2_set_key(BlockDriverState
*bs
, const char *key
)
1234 BDRVQcow2State
*s
= bs
->opaque
;
1239 memset(keybuf
, 0, 16);
1243 /* XXX: we could compress the chars to 7 bits to increase
1245 for(i
= 0;i
< len
;i
++) {
1248 assert(bs
->encrypted
);
1250 qcrypto_cipher_free(s
->cipher
);
1251 s
->cipher
= qcrypto_cipher_new(
1252 QCRYPTO_CIPHER_ALG_AES_128
,
1253 QCRYPTO_CIPHER_MODE_CBC
,
1254 keybuf
, G_N_ELEMENTS(keybuf
),
1258 /* XXX would be nice if errors in this method could
1259 * be properly propagate to the caller. Would need
1260 * the bdrv_set_key() API signature to be fixed. */
1267 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1268 BlockReopenQueue
*queue
, Error
**errp
)
1270 Qcow2ReopenState
*r
;
1273 r
= g_new0(Qcow2ReopenState
, 1);
1276 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1277 state
->flags
, errp
);
1282 /* We need to write out any unwritten data if we reopen read-only. */
1283 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1284 ret
= bdrv_flush(state
->bs
);
1289 ret
= qcow2_mark_clean(state
->bs
);
1298 qcow2_update_options_abort(state
->bs
, r
);
1303 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1305 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1306 g_free(state
->opaque
);
1309 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1311 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1312 g_free(state
->opaque
);
1315 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1317 bool has_new_overlap_template
=
1318 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1319 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1320 bool has_new_total_cache_size
=
1321 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1322 bool has_all_cache_options
;
1324 /* New overlap template overrides all old overlap options */
1325 if (has_new_overlap_template
) {
1326 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1327 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1328 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1329 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1330 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1331 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1332 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1333 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1334 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1335 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1338 /* New total cache size overrides all old options */
1339 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1340 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1341 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1344 qdict_join(options
, old_options
, false);
1347 * If after merging all cache size options are set, an old total size is
1348 * overwritten. Do keep all options, however, if all three are new. The
1349 * resulting error message is what we want to happen.
1351 has_all_cache_options
=
1352 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1353 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1354 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1356 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1357 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1361 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
1362 int64_t sector_num
, int nb_sectors
, int *pnum
, BlockDriverState
**file
)
1364 BDRVQcow2State
*s
= bs
->opaque
;
1365 uint64_t cluster_offset
;
1366 int index_in_cluster
, ret
;
1370 bytes
= MIN(INT_MAX
, nb_sectors
* BDRV_SECTOR_SIZE
);
1371 qemu_co_mutex_lock(&s
->lock
);
1372 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9, &bytes
,
1374 qemu_co_mutex_unlock(&s
->lock
);
1379 *pnum
= bytes
>> BDRV_SECTOR_BITS
;
1381 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1383 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1384 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
1385 *file
= bs
->file
->bs
;
1386 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
1388 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1389 status
|= BDRV_BLOCK_ZERO
;
1390 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1391 status
|= BDRV_BLOCK_DATA
;
1396 /* handle reading after the end of the backing file */
1397 int qcow2_backing_read1(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
1398 int64_t offset
, int bytes
)
1400 uint64_t bs_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1403 if ((offset
+ bytes
) <= bs_size
) {
1407 if (offset
>= bs_size
) {
1410 n1
= bs_size
- offset
;
1413 qemu_iovec_memset(qiov
, n1
, 0, bytes
- n1
);
1418 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1419 uint64_t bytes
, QEMUIOVector
*qiov
,
1422 BDRVQcow2State
*s
= bs
->opaque
;
1423 int offset_in_cluster
, n1
;
1425 unsigned int cur_bytes
; /* number of bytes in current iteration */
1426 uint64_t cluster_offset
= 0;
1427 uint64_t bytes_done
= 0;
1428 QEMUIOVector hd_qiov
;
1429 uint8_t *cluster_data
= NULL
;
1431 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1433 qemu_co_mutex_lock(&s
->lock
);
1435 while (bytes
!= 0) {
1437 /* prepare next request */
1438 cur_bytes
= MIN(bytes
, INT_MAX
);
1440 cur_bytes
= MIN(cur_bytes
,
1441 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1444 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1449 offset_in_cluster
= offset_into_cluster(s
, offset
);
1451 qemu_iovec_reset(&hd_qiov
);
1452 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1455 case QCOW2_CLUSTER_UNALLOCATED
:
1458 /* read from the base image */
1459 n1
= qcow2_backing_read1(bs
->backing
->bs
, &hd_qiov
,
1462 QEMUIOVector local_qiov
;
1464 qemu_iovec_init(&local_qiov
, hd_qiov
.niov
);
1465 qemu_iovec_concat(&local_qiov
, &hd_qiov
, 0, n1
);
1467 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1468 qemu_co_mutex_unlock(&s
->lock
);
1469 ret
= bdrv_co_preadv(bs
->backing
, offset
, n1
,
1471 qemu_co_mutex_lock(&s
->lock
);
1473 qemu_iovec_destroy(&local_qiov
);
1480 /* Note: in this case, no need to wait */
1481 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1485 case QCOW2_CLUSTER_ZERO_PLAIN
:
1486 case QCOW2_CLUSTER_ZERO_ALLOC
:
1487 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1490 case QCOW2_CLUSTER_COMPRESSED
:
1491 /* add AIO support for compressed blocks ? */
1492 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1497 qemu_iovec_from_buf(&hd_qiov
, 0,
1498 s
->cluster_cache
+ offset_in_cluster
,
1502 case QCOW2_CLUSTER_NORMAL
:
1503 if ((cluster_offset
& 511) != 0) {
1508 if (bs
->encrypted
) {
1512 * For encrypted images, read everything into a temporary
1513 * contiguous buffer on which the AES functions can work.
1515 if (!cluster_data
) {
1517 qemu_try_blockalign(bs
->file
->bs
,
1518 QCOW_MAX_CRYPT_CLUSTERS
1520 if (cluster_data
== NULL
) {
1526 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1527 qemu_iovec_reset(&hd_qiov
);
1528 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1531 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1532 qemu_co_mutex_unlock(&s
->lock
);
1533 ret
= bdrv_co_preadv(bs
->file
,
1534 cluster_offset
+ offset_in_cluster
,
1535 cur_bytes
, &hd_qiov
, 0);
1536 qemu_co_mutex_lock(&s
->lock
);
1540 if (bs
->encrypted
) {
1542 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1543 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1545 if (qcow2_encrypt_sectors(s
, offset
>> BDRV_SECTOR_BITS
,
1546 cluster_data
, cluster_data
,
1547 cur_bytes
>> BDRV_SECTOR_BITS
,
1553 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1558 g_assert_not_reached();
1564 offset
+= cur_bytes
;
1565 bytes_done
+= cur_bytes
;
1570 qemu_co_mutex_unlock(&s
->lock
);
1572 qemu_iovec_destroy(&hd_qiov
);
1573 qemu_vfree(cluster_data
);
1578 /* Check if it's possible to merge a write request with the writing of
1579 * the data from the COW regions */
1580 static bool merge_cow(uint64_t offset
, unsigned bytes
,
1581 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
1585 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
1586 /* If both COW regions are empty then there's nothing to merge */
1587 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
1591 /* The data (middle) region must be immediately after the
1593 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
1597 /* The end region must be immediately after the data (middle)
1599 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
1603 /* Make sure that adding both COW regions to the QEMUIOVector
1604 * does not exceed IOV_MAX */
1605 if (hd_qiov
->niov
> IOV_MAX
- 2) {
1609 m
->data_qiov
= hd_qiov
;
1616 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1617 uint64_t bytes
, QEMUIOVector
*qiov
,
1620 BDRVQcow2State
*s
= bs
->opaque
;
1621 int offset_in_cluster
;
1623 unsigned int cur_bytes
; /* number of sectors in current iteration */
1624 uint64_t cluster_offset
;
1625 QEMUIOVector hd_qiov
;
1626 uint64_t bytes_done
= 0;
1627 uint8_t *cluster_data
= NULL
;
1628 QCowL2Meta
*l2meta
= NULL
;
1630 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
1632 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1634 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1636 qemu_co_mutex_lock(&s
->lock
);
1638 while (bytes
!= 0) {
1642 trace_qcow2_writev_start_part(qemu_coroutine_self());
1643 offset_in_cluster
= offset_into_cluster(s
, offset
);
1644 cur_bytes
= MIN(bytes
, INT_MAX
);
1645 if (bs
->encrypted
) {
1646 cur_bytes
= MIN(cur_bytes
,
1647 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
1648 - offset_in_cluster
);
1651 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
1652 &cluster_offset
, &l2meta
);
1657 assert((cluster_offset
& 511) == 0);
1659 qemu_iovec_reset(&hd_qiov
);
1660 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1662 if (bs
->encrypted
) {
1665 if (!cluster_data
) {
1666 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
1667 QCOW_MAX_CRYPT_CLUSTERS
1669 if (cluster_data
== NULL
) {
1675 assert(hd_qiov
.size
<=
1676 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1677 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
1679 if (qcow2_encrypt_sectors(s
, offset
>> BDRV_SECTOR_BITS
,
1680 cluster_data
, cluster_data
,
1681 cur_bytes
>>BDRV_SECTOR_BITS
,
1688 qemu_iovec_reset(&hd_qiov
);
1689 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1692 ret
= qcow2_pre_write_overlap_check(bs
, 0,
1693 cluster_offset
+ offset_in_cluster
, cur_bytes
);
1698 /* If we need to do COW, check if it's possible to merge the
1699 * writing of the guest data together with that of the COW regions.
1700 * If it's not possible (or not necessary) then write the
1701 * guest data now. */
1702 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
1703 qemu_co_mutex_unlock(&s
->lock
);
1704 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
1705 trace_qcow2_writev_data(qemu_coroutine_self(),
1706 cluster_offset
+ offset_in_cluster
);
1707 ret
= bdrv_co_pwritev(bs
->file
,
1708 cluster_offset
+ offset_in_cluster
,
1709 cur_bytes
, &hd_qiov
, 0);
1710 qemu_co_mutex_lock(&s
->lock
);
1716 while (l2meta
!= NULL
) {
1719 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1724 /* Take the request off the list of running requests */
1725 if (l2meta
->nb_clusters
!= 0) {
1726 QLIST_REMOVE(l2meta
, next_in_flight
);
1729 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1731 next
= l2meta
->next
;
1737 offset
+= cur_bytes
;
1738 bytes_done
+= cur_bytes
;
1739 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
1744 qemu_co_mutex_unlock(&s
->lock
);
1746 while (l2meta
!= NULL
) {
1749 if (l2meta
->nb_clusters
!= 0) {
1750 QLIST_REMOVE(l2meta
, next_in_flight
);
1752 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1754 next
= l2meta
->next
;
1759 qemu_iovec_destroy(&hd_qiov
);
1760 qemu_vfree(cluster_data
);
1761 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
1766 static int qcow2_inactivate(BlockDriverState
*bs
)
1768 BDRVQcow2State
*s
= bs
->opaque
;
1769 int ret
, result
= 0;
1771 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
1774 error_report("Failed to flush the L2 table cache: %s",
1778 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1781 error_report("Failed to flush the refcount block cache: %s",
1786 qcow2_mark_clean(bs
);
1792 static void qcow2_close(BlockDriverState
*bs
)
1794 BDRVQcow2State
*s
= bs
->opaque
;
1795 qemu_vfree(s
->l1_table
);
1796 /* else pre-write overlap checks in cache_destroy may crash */
1799 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
1800 qcow2_inactivate(bs
);
1803 cache_clean_timer_del(bs
);
1804 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1805 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1807 qcrypto_cipher_free(s
->cipher
);
1810 g_free(s
->unknown_header_fields
);
1811 cleanup_unknown_header_ext(bs
);
1813 g_free(s
->image_backing_file
);
1814 g_free(s
->image_backing_format
);
1816 g_free(s
->cluster_cache
);
1817 qemu_vfree(s
->cluster_data
);
1818 qcow2_refcount_close(bs
);
1819 qcow2_free_snapshots(bs
);
1822 static void qcow2_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
1824 BDRVQcow2State
*s
= bs
->opaque
;
1825 int flags
= s
->flags
;
1826 QCryptoCipher
*cipher
= NULL
;
1828 Error
*local_err
= NULL
;
1832 * Backing files are read-only which makes all of their metadata immutable,
1833 * that means we don't have to worry about reopening them here.
1841 memset(s
, 0, sizeof(BDRVQcow2State
));
1842 options
= qdict_clone_shallow(bs
->options
);
1844 flags
&= ~BDRV_O_INACTIVE
;
1845 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
1848 error_propagate(errp
, local_err
);
1849 error_prepend(errp
, "Could not reopen qcow2 layer: ");
1852 } else if (ret
< 0) {
1853 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
1861 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
1862 size_t len
, size_t buflen
)
1864 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
1865 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
1867 if (buflen
< ext_len
) {
1871 *ext_backing_fmt
= (QCowExtension
) {
1872 .magic
= cpu_to_be32(magic
),
1873 .len
= cpu_to_be32(len
),
1877 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
1884 * Updates the qcow2 header, including the variable length parts of it, i.e.
1885 * the backing file name and all extensions. qcow2 was not designed to allow
1886 * such changes, so if we run out of space (we can only use the first cluster)
1887 * this function may fail.
1889 * Returns 0 on success, -errno in error cases.
1891 int qcow2_update_header(BlockDriverState
*bs
)
1893 BDRVQcow2State
*s
= bs
->opaque
;
1896 size_t buflen
= s
->cluster_size
;
1898 uint64_t total_size
;
1899 uint32_t refcount_table_clusters
;
1900 size_t header_length
;
1901 Qcow2UnknownHeaderExtension
*uext
;
1903 buf
= qemu_blockalign(bs
, buflen
);
1905 /* Header structure */
1906 header
= (QCowHeader
*) buf
;
1908 if (buflen
< sizeof(*header
)) {
1913 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
1914 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1915 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
1917 *header
= (QCowHeader
) {
1918 /* Version 2 fields */
1919 .magic
= cpu_to_be32(QCOW_MAGIC
),
1920 .version
= cpu_to_be32(s
->qcow_version
),
1921 .backing_file_offset
= 0,
1922 .backing_file_size
= 0,
1923 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
1924 .size
= cpu_to_be64(total_size
),
1925 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
1926 .l1_size
= cpu_to_be32(s
->l1_size
),
1927 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
1928 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
1929 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
1930 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
1931 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
1933 /* Version 3 fields */
1934 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
1935 .compatible_features
= cpu_to_be64(s
->compatible_features
),
1936 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
1937 .refcount_order
= cpu_to_be32(s
->refcount_order
),
1938 .header_length
= cpu_to_be32(header_length
),
1941 /* For older versions, write a shorter header */
1942 switch (s
->qcow_version
) {
1944 ret
= offsetof(QCowHeader
, incompatible_features
);
1947 ret
= sizeof(*header
);
1956 memset(buf
, 0, buflen
);
1958 /* Preserve any unknown field in the header */
1959 if (s
->unknown_header_fields_size
) {
1960 if (buflen
< s
->unknown_header_fields_size
) {
1965 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
1966 buf
+= s
->unknown_header_fields_size
;
1967 buflen
-= s
->unknown_header_fields_size
;
1970 /* Backing file format header extension */
1971 if (s
->image_backing_format
) {
1972 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
1973 s
->image_backing_format
,
1974 strlen(s
->image_backing_format
),
1985 if (s
->qcow_version
>= 3) {
1986 Qcow2Feature features
[] = {
1988 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1989 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
1990 .name
= "dirty bit",
1993 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1994 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
1995 .name
= "corrupt bit",
1998 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
1999 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2000 .name
= "lazy refcounts",
2004 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2005 features
, sizeof(features
), buflen
);
2013 /* Keep unknown header extensions */
2014 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2015 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2024 /* End of header extensions */
2025 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2033 /* Backing file name */
2034 if (s
->image_backing_file
) {
2035 size_t backing_file_len
= strlen(s
->image_backing_file
);
2037 if (buflen
< backing_file_len
) {
2042 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2043 strncpy(buf
, s
->image_backing_file
, buflen
);
2045 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2046 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2049 /* Write the new header */
2050 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2061 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2062 const char *backing_file
, const char *backing_fmt
)
2064 BDRVQcow2State
*s
= bs
->opaque
;
2066 if (backing_file
&& strlen(backing_file
) > 1023) {
2070 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2071 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2073 g_free(s
->image_backing_file
);
2074 g_free(s
->image_backing_format
);
2076 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2077 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2079 return qcow2_update_header(bs
);
2082 static int preallocate(BlockDriverState
*bs
)
2086 uint64_t host_offset
= 0;
2087 unsigned int cur_bytes
;
2091 bytes
= bdrv_getlength(bs
);
2095 cur_bytes
= MIN(bytes
, INT_MAX
);
2096 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2097 &host_offset
, &meta
);
2103 QCowL2Meta
*next
= meta
->next
;
2105 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2107 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2108 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2112 /* There are no dependent requests, but we need to remove our
2113 * request from the list of in-flight requests */
2114 QLIST_REMOVE(meta
, next_in_flight
);
2120 /* TODO Preallocate data if requested */
2123 offset
+= cur_bytes
;
2127 * It is expected that the image file is large enough to actually contain
2128 * all of the allocated clusters (otherwise we get failing reads after
2129 * EOF). Extend the image to the last allocated sector.
2131 if (host_offset
!= 0) {
2133 ret
= bdrv_pwrite(bs
->file
, (host_offset
+ cur_bytes
) - 1,
2143 static int qcow2_create2(const char *filename
, int64_t total_size
,
2144 const char *backing_file
, const char *backing_format
,
2145 int flags
, size_t cluster_size
, PreallocMode prealloc
,
2146 QemuOpts
*opts
, int version
, int refcount_order
,
2152 /* Calculate cluster_bits */
2153 cluster_bits
= ctz32(cluster_size
);
2154 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2155 (1 << cluster_bits
) != cluster_size
)
2157 error_setg(errp
, "Cluster size must be a power of two between %d and "
2158 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2163 * Open the image file and write a minimal qcow2 header.
2165 * We keep things simple and start with a zero-sized image. We also
2166 * do without refcount blocks or a L1 table for now. We'll fix the
2167 * inconsistency later.
2169 * We do need a refcount table because growing the refcount table means
2170 * allocating two new refcount blocks - the seconds of which would be at
2171 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2172 * size for any qcow2 image.
2176 uint64_t* refcount_table
;
2177 Error
*local_err
= NULL
;
2180 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
2181 /* Note: The following calculation does not need to be exact; if it is a
2182 * bit off, either some bytes will be "leaked" (which is fine) or we
2183 * will need to increase the file size by some bytes (which is fine,
2184 * too, as long as the bulk is allocated here). Therefore, using
2185 * floating point arithmetic is fine. */
2186 int64_t meta_size
= 0;
2187 uint64_t nreftablee
, nrefblocke
, nl1e
, nl2e
, refblock_count
;
2188 int64_t aligned_total_size
= align_offset(total_size
, cluster_size
);
2189 int refblock_bits
, refblock_size
;
2190 /* refcount entry size in bytes */
2191 double rces
= (1 << refcount_order
) / 8.;
2193 /* see qcow2_open() */
2194 refblock_bits
= cluster_bits
- (refcount_order
- 3);
2195 refblock_size
= 1 << refblock_bits
;
2197 /* header: 1 cluster */
2198 meta_size
+= cluster_size
;
2200 /* total size of L2 tables */
2201 nl2e
= aligned_total_size
/ cluster_size
;
2202 nl2e
= align_offset(nl2e
, cluster_size
/ sizeof(uint64_t));
2203 meta_size
+= nl2e
* sizeof(uint64_t);
2205 /* total size of L1 tables */
2206 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2207 nl1e
= align_offset(nl1e
, cluster_size
/ sizeof(uint64_t));
2208 meta_size
+= nl1e
* sizeof(uint64_t);
2210 /* total size of refcount blocks
2212 * note: every host cluster is reference-counted, including metadata
2213 * (even refcount blocks are recursively included).
2215 * a = total_size (this is the guest disk size)
2216 * m = meta size not including refcount blocks and refcount tables
2218 * y1 = number of refcount blocks entries
2219 * y2 = meta size including everything
2220 * rces = refcount entry size in bytes
2223 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2225 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2227 nrefblocke
= (aligned_total_size
+ meta_size
+ cluster_size
)
2228 / (cluster_size
- rces
- rces
* sizeof(uint64_t)
2230 refblock_count
= DIV_ROUND_UP(nrefblocke
, refblock_size
);
2231 meta_size
+= refblock_count
* cluster_size
;
2233 /* total size of refcount tables */
2234 nreftablee
= align_offset(refblock_count
,
2235 cluster_size
/ sizeof(uint64_t));
2236 meta_size
+= nreftablee
* sizeof(uint64_t);
2238 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2239 aligned_total_size
+ meta_size
, &error_abort
);
2240 qemu_opt_set(opts
, BLOCK_OPT_PREALLOC
, PreallocMode_lookup
[prealloc
],
2244 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2246 error_propagate(errp
, local_err
);
2250 blk
= blk_new_open(filename
, NULL
, NULL
,
2251 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2254 error_propagate(errp
, local_err
);
2258 blk_set_allow_write_beyond_eof(blk
, true);
2260 /* Write the header */
2261 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2262 header
= g_malloc0(cluster_size
);
2263 *header
= (QCowHeader
) {
2264 .magic
= cpu_to_be32(QCOW_MAGIC
),
2265 .version
= cpu_to_be32(version
),
2266 .cluster_bits
= cpu_to_be32(cluster_bits
),
2267 .size
= cpu_to_be64(0),
2268 .l1_table_offset
= cpu_to_be64(0),
2269 .l1_size
= cpu_to_be32(0),
2270 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2271 .refcount_table_clusters
= cpu_to_be32(1),
2272 .refcount_order
= cpu_to_be32(refcount_order
),
2273 .header_length
= cpu_to_be32(sizeof(*header
)),
2276 if (flags
& BLOCK_FLAG_ENCRYPT
) {
2277 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_AES
);
2279 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2282 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
2283 header
->compatible_features
|=
2284 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2287 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2290 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2294 /* Write a refcount table with one refcount block */
2295 refcount_table
= g_malloc0(2 * cluster_size
);
2296 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2297 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2298 g_free(refcount_table
);
2301 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2309 * And now open the image and make it consistent first (i.e. increase the
2310 * refcount of the cluster that is occupied by the header and the refcount
2313 options
= qdict_new();
2314 qdict_put_str(options
, "driver", "qcow2");
2315 blk
= blk_new_open(filename
, NULL
, options
,
2316 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
2319 error_propagate(errp
, local_err
);
2324 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2326 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2327 "header and refcount table");
2330 } else if (ret
!= 0) {
2331 error_report("Huh, first cluster in empty image is already in use?");
2335 /* Create a full header (including things like feature table) */
2336 ret
= qcow2_update_header(blk_bs(blk
));
2338 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
2342 /* Okay, now that we have a valid image, let's give it the right size */
2343 ret
= blk_truncate(blk
, total_size
, errp
);
2345 error_prepend(errp
, "Could not resize image: ");
2349 /* Want a backing file? There you go.*/
2351 ret
= bdrv_change_backing_file(blk_bs(blk
), backing_file
, backing_format
);
2353 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
2354 "with format '%s'", backing_file
, backing_format
);
2359 /* And if we're supposed to preallocate metadata, do that now */
2360 if (prealloc
!= PREALLOC_MODE_OFF
) {
2361 BDRVQcow2State
*s
= blk_bs(blk
)->opaque
;
2362 qemu_co_mutex_lock(&s
->lock
);
2363 ret
= preallocate(blk_bs(blk
));
2364 qemu_co_mutex_unlock(&s
->lock
);
2366 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
2374 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2375 options
= qdict_new();
2376 qdict_put_str(options
, "driver", "qcow2");
2377 blk
= blk_new_open(filename
, NULL
, options
,
2378 BDRV_O_RDWR
| BDRV_O_NO_BACKING
, &local_err
);
2380 error_propagate(errp
, local_err
);
2393 static int qcow2_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
2395 char *backing_file
= NULL
;
2396 char *backing_fmt
= NULL
;
2400 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
2401 PreallocMode prealloc
;
2403 uint64_t refcount_bits
= 16;
2405 Error
*local_err
= NULL
;
2408 /* Read out options */
2409 size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2411 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
2412 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
2413 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ENCRYPT
, false)) {
2414 flags
|= BLOCK_FLAG_ENCRYPT
;
2416 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2417 DEFAULT_CLUSTER_SIZE
);
2418 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2419 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
2420 PREALLOC_MODE__MAX
, PREALLOC_MODE_OFF
,
2423 error_propagate(errp
, local_err
);
2428 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2430 /* keep the default */
2431 } else if (!strcmp(buf
, "0.10")) {
2433 } else if (!strcmp(buf
, "1.1")) {
2436 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2441 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_LAZY_REFCOUNTS
, false)) {
2442 flags
|= BLOCK_FLAG_LAZY_REFCOUNTS
;
2445 if (backing_file
&& prealloc
!= PREALLOC_MODE_OFF
) {
2446 error_setg(errp
, "Backing file and preallocation cannot be used at "
2452 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
2453 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2454 "level 1.1 and above (use compat=1.1 or greater)");
2459 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
,
2461 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2462 error_setg(errp
, "Refcount width must be a power of two and may not "
2468 if (version
< 3 && refcount_bits
!= 16) {
2469 error_setg(errp
, "Different refcount widths than 16 bits require "
2470 "compatibility level 1.1 or above (use compat=1.1 or "
2476 refcount_order
= ctz32(refcount_bits
);
2478 ret
= qcow2_create2(filename
, size
, backing_file
, backing_fmt
, flags
,
2479 cluster_size
, prealloc
, opts
, version
, refcount_order
,
2481 error_propagate(errp
, local_err
);
2484 g_free(backing_file
);
2485 g_free(backing_fmt
);
2491 static bool is_zero_sectors(BlockDriverState
*bs
, int64_t start
,
2495 BlockDriverState
*file
;
2498 if (start
+ count
> bs
->total_sectors
) {
2499 count
= bs
->total_sectors
- start
;
2505 res
= bdrv_get_block_status_above(bs
, NULL
, start
, count
,
2507 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== count
;
2510 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
2511 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
2514 BDRVQcow2State
*s
= bs
->opaque
;
2516 uint32_t head
= offset
% s
->cluster_size
;
2517 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
2519 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
2520 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
2525 int64_t cl_start
= (offset
- head
) >> BDRV_SECTOR_BITS
;
2529 assert(head
+ bytes
<= s
->cluster_size
);
2531 /* check whether remainder of cluster already reads as zero */
2532 if (!(is_zero_sectors(bs
, cl_start
,
2533 DIV_ROUND_UP(head
, BDRV_SECTOR_SIZE
)) &&
2534 is_zero_sectors(bs
, (offset
+ bytes
) >> BDRV_SECTOR_BITS
,
2535 DIV_ROUND_UP(-tail
& (s
->cluster_size
- 1),
2536 BDRV_SECTOR_SIZE
)))) {
2540 qemu_co_mutex_lock(&s
->lock
);
2541 /* We can have new write after previous check */
2542 offset
= cl_start
<< BDRV_SECTOR_BITS
;
2543 bytes
= s
->cluster_size
;
2544 nr
= s
->cluster_size
;
2545 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
2546 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
2547 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
2548 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
2549 qemu_co_mutex_unlock(&s
->lock
);
2553 qemu_co_mutex_lock(&s
->lock
);
2556 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
2558 /* Whatever is left can use real zero clusters */
2559 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
2560 qemu_co_mutex_unlock(&s
->lock
);
2565 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
2566 int64_t offset
, int bytes
)
2569 BDRVQcow2State
*s
= bs
->opaque
;
2571 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
2572 assert(bytes
< s
->cluster_size
);
2573 /* Ignore partial clusters, except for the special case of the
2574 * complete partial cluster at the end of an unaligned file */
2575 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
2576 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
2581 qemu_co_mutex_lock(&s
->lock
);
2582 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
2584 qemu_co_mutex_unlock(&s
->lock
);
2588 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
, Error
**errp
)
2590 BDRVQcow2State
*s
= bs
->opaque
;
2591 int64_t new_l1_size
;
2595 error_setg(errp
, "The new size must be a multiple of 512");
2599 /* cannot proceed if image has snapshots */
2600 if (s
->nb_snapshots
) {
2601 error_setg(errp
, "Can't resize an image which has snapshots");
2605 /* shrinking is currently not supported */
2606 if (offset
< bs
->total_sectors
* 512) {
2607 error_setg(errp
, "qcow2 doesn't support shrinking images yet");
2611 new_l1_size
= size_to_l1(s
, offset
);
2612 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
2614 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
2618 /* write updated header.size */
2619 offset
= cpu_to_be64(offset
);
2620 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
2621 &offset
, sizeof(uint64_t));
2623 error_setg_errno(errp
, -ret
, "Failed to update the image size");
2627 s
->l1_vm_state_index
= new_l1_size
;
2631 /* XXX: put compressed sectors first, then all the cluster aligned
2632 tables to avoid losing bytes in alignment */
2633 static coroutine_fn
int
2634 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
2635 uint64_t bytes
, QEMUIOVector
*qiov
)
2637 BDRVQcow2State
*s
= bs
->opaque
;
2638 QEMUIOVector hd_qiov
;
2642 uint8_t *buf
, *out_buf
;
2643 uint64_t cluster_offset
;
2646 /* align end of file to a sector boundary to ease reading with
2647 sector based I/Os */
2648 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
2649 return bdrv_truncate(bs
->file
, cluster_offset
, NULL
);
2652 buf
= qemu_blockalign(bs
, s
->cluster_size
);
2653 if (bytes
!= s
->cluster_size
) {
2654 if (bytes
> s
->cluster_size
||
2655 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
2660 /* Zero-pad last write if image size is not cluster aligned */
2661 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
2663 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
2665 out_buf
= g_malloc(s
->cluster_size
);
2667 /* best compression, small window, no zlib header */
2668 memset(&strm
, 0, sizeof(strm
));
2669 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
2671 9, Z_DEFAULT_STRATEGY
);
2677 strm
.avail_in
= s
->cluster_size
;
2678 strm
.next_in
= (uint8_t *)buf
;
2679 strm
.avail_out
= s
->cluster_size
;
2680 strm
.next_out
= out_buf
;
2682 ret
= deflate(&strm
, Z_FINISH
);
2683 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
2688 out_len
= strm
.next_out
- out_buf
;
2692 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
2693 /* could not compress: write normal cluster */
2694 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
2701 qemu_co_mutex_lock(&s
->lock
);
2703 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
2704 if (!cluster_offset
) {
2705 qemu_co_mutex_unlock(&s
->lock
);
2709 cluster_offset
&= s
->cluster_offset_mask
;
2711 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
2712 qemu_co_mutex_unlock(&s
->lock
);
2717 iov
= (struct iovec
) {
2718 .iov_base
= out_buf
,
2721 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
2723 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
2724 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
2736 static int make_completely_empty(BlockDriverState
*bs
)
2738 BDRVQcow2State
*s
= bs
->opaque
;
2739 Error
*local_err
= NULL
;
2740 int ret
, l1_clusters
;
2742 uint64_t *new_reftable
= NULL
;
2743 uint64_t rt_entry
, l1_size2
;
2746 uint64_t reftable_offset
;
2747 uint32_t reftable_clusters
;
2748 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
2750 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
2755 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
2760 /* Refcounts will be broken utterly */
2761 ret
= qcow2_mark_dirty(bs
);
2766 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
2768 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
2769 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
2771 /* After this call, neither the in-memory nor the on-disk refcount
2772 * information accurately describe the actual references */
2774 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
2775 l1_clusters
* s
->cluster_size
, 0);
2777 goto fail_broken_refcounts
;
2779 memset(s
->l1_table
, 0, l1_size2
);
2781 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
2783 /* Overwrite enough clusters at the beginning of the sectors to place
2784 * the refcount table, a refcount block and the L1 table in; this may
2785 * overwrite parts of the existing refcount and L1 table, which is not
2786 * an issue because the dirty flag is set, complete data loss is in fact
2787 * desired and partial data loss is consequently fine as well */
2788 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
2789 (2 + l1_clusters
) * s
->cluster_size
, 0);
2790 /* This call (even if it failed overall) may have overwritten on-disk
2791 * refcount structures; in that case, the in-memory refcount information
2792 * will probably differ from the on-disk information which makes the BDS
2795 goto fail_broken_refcounts
;
2798 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
2799 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
2801 /* "Create" an empty reftable (one cluster) directly after the image
2802 * header and an empty L1 table three clusters after the image header;
2803 * the cluster between those two will be used as the first refblock */
2804 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
2805 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
2806 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
2807 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
2808 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
2810 goto fail_broken_refcounts
;
2813 s
->l1_table_offset
= 3 * s
->cluster_size
;
2815 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
2816 if (!new_reftable
) {
2818 goto fail_broken_refcounts
;
2821 s
->refcount_table_offset
= s
->cluster_size
;
2822 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
2823 s
->max_refcount_table_index
= 0;
2825 g_free(s
->refcount_table
);
2826 s
->refcount_table
= new_reftable
;
2827 new_reftable
= NULL
;
2829 /* Now the in-memory refcount information again corresponds to the on-disk
2830 * information (reftable is empty and no refblocks (the refblock cache is
2831 * empty)); however, this means some clusters (e.g. the image header) are
2832 * referenced, but not refcounted, but the normal qcow2 code assumes that
2833 * the in-memory information is always correct */
2835 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
2837 /* Enter the first refblock into the reftable */
2838 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
2839 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
2840 &rt_entry
, sizeof(rt_entry
));
2842 goto fail_broken_refcounts
;
2844 s
->refcount_table
[0] = 2 * s
->cluster_size
;
2846 s
->free_cluster_index
= 0;
2847 assert(3 + l1_clusters
<= s
->refcount_block_size
);
2848 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
2851 goto fail_broken_refcounts
;
2852 } else if (offset
> 0) {
2853 error_report("First cluster in emptied image is in use");
2857 /* Now finally the in-memory information corresponds to the on-disk
2858 * structures and is correct */
2859 ret
= qcow2_mark_clean(bs
);
2864 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
2867 error_report_err(local_err
);
2873 fail_broken_refcounts
:
2874 /* The BDS is unusable at this point. If we wanted to make it usable, we
2875 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2876 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2877 * again. However, because the functions which could have caused this error
2878 * path to be taken are used by those functions as well, it's very likely
2879 * that that sequence will fail as well. Therefore, just eject the BDS. */
2883 g_free(new_reftable
);
2887 static int qcow2_make_empty(BlockDriverState
*bs
)
2889 BDRVQcow2State
*s
= bs
->opaque
;
2890 uint64_t offset
, end_offset
;
2891 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
2892 int l1_clusters
, ret
= 0;
2894 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
2896 if (s
->qcow_version
>= 3 && !s
->snapshots
&&
2897 3 + l1_clusters
<= s
->refcount_block_size
) {
2898 /* The following function only works for qcow2 v3 images (it requires
2899 * the dirty flag) and only as long as there are no snapshots (because
2900 * it completely empties the image). Furthermore, the L1 table and three
2901 * additional clusters (image header, refcount table, one refcount
2902 * block) have to fit inside one refcount block. */
2903 return make_completely_empty(bs
);
2906 /* This fallback code simply discards every active cluster; this is slow,
2907 * but works in all cases */
2908 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2909 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
2910 /* As this function is generally used after committing an external
2911 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2912 * default action for this kind of discard is to pass the discard,
2913 * which will ideally result in an actually smaller image file, as
2914 * is probably desired. */
2915 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
2916 QCOW2_DISCARD_SNAPSHOT
, true);
2925 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
2927 BDRVQcow2State
*s
= bs
->opaque
;
2930 qemu_co_mutex_lock(&s
->lock
);
2931 ret
= qcow2_cache_write(bs
, s
->l2_table_cache
);
2933 qemu_co_mutex_unlock(&s
->lock
);
2937 if (qcow2_need_accurate_refcounts(s
)) {
2938 ret
= qcow2_cache_write(bs
, s
->refcount_block_cache
);
2940 qemu_co_mutex_unlock(&s
->lock
);
2944 qemu_co_mutex_unlock(&s
->lock
);
2949 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2951 BDRVQcow2State
*s
= bs
->opaque
;
2952 bdi
->unallocated_blocks_are_zero
= true;
2953 bdi
->can_write_zeroes_with_unmap
= (s
->qcow_version
>= 3);
2954 bdi
->cluster_size
= s
->cluster_size
;
2955 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
2959 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
2961 BDRVQcow2State
*s
= bs
->opaque
;
2962 ImageInfoSpecific
*spec_info
= g_new(ImageInfoSpecific
, 1);
2964 *spec_info
= (ImageInfoSpecific
){
2965 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
2966 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
2968 if (s
->qcow_version
== 2) {
2969 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
2970 .compat
= g_strdup("0.10"),
2971 .refcount_bits
= s
->refcount_bits
,
2973 } else if (s
->qcow_version
== 3) {
2974 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
2975 .compat
= g_strdup("1.1"),
2976 .lazy_refcounts
= s
->compatible_features
&
2977 QCOW2_COMPAT_LAZY_REFCOUNTS
,
2978 .has_lazy_refcounts
= true,
2979 .corrupt
= s
->incompatible_features
&
2980 QCOW2_INCOMPAT_CORRUPT
,
2981 .has_corrupt
= true,
2982 .refcount_bits
= s
->refcount_bits
,
2985 /* if this assertion fails, this probably means a new version was
2986 * added without having it covered here */
2994 static void dump_refcounts(BlockDriverState
*bs
)
2996 BDRVQcow2State
*s
= bs
->opaque
;
2997 int64_t nb_clusters
, k
, k1
, size
;
3000 size
= bdrv_getlength(bs
->file
->bs
);
3001 nb_clusters
= size_to_clusters(s
, size
);
3002 for(k
= 0; k
< nb_clusters
;) {
3004 refcount
= get_refcount(bs
, k
);
3006 while (k
< nb_clusters
&& get_refcount(bs
, k
) == refcount
)
3008 printf("%" PRId64
": refcount=%d nb=%" PRId64
"\n", k
, refcount
,
3014 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3017 BDRVQcow2State
*s
= bs
->opaque
;
3019 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
3020 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
3021 qiov
->size
, qiov
, 0);
3024 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3027 BDRVQcow2State
*s
= bs
->opaque
;
3029 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
3030 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
3031 qiov
->size
, qiov
, 0);
3035 * Downgrades an image's version. To achieve this, any incompatible features
3036 * have to be removed.
3038 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
3039 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
)
3041 BDRVQcow2State
*s
= bs
->opaque
;
3042 int current_version
= s
->qcow_version
;
3045 if (target_version
== current_version
) {
3047 } else if (target_version
> current_version
) {
3049 } else if (target_version
!= 2) {
3053 if (s
->refcount_order
!= 4) {
3054 error_report("compat=0.10 requires refcount_bits=16");
3058 /* clear incompatible features */
3059 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
3060 ret
= qcow2_mark_clean(bs
);
3066 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3067 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3068 * best thing to do anyway */
3070 if (s
->incompatible_features
) {
3074 /* since we can ignore compatible features, we can set them to 0 as well */
3075 s
->compatible_features
= 0;
3076 /* if lazy refcounts have been used, they have already been fixed through
3077 * clearing the dirty flag */
3079 /* clearing autoclear features is trivial */
3080 s
->autoclear_features
= 0;
3082 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
3087 s
->qcow_version
= target_version
;
3088 ret
= qcow2_update_header(bs
);
3090 s
->qcow_version
= current_version
;
3096 typedef enum Qcow2AmendOperation
{
3097 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3098 * statically initialized to so that the helper CB can discern the first
3099 * invocation from an operation change */
3100 QCOW2_NO_OPERATION
= 0,
3102 QCOW2_CHANGING_REFCOUNT_ORDER
,
3104 } Qcow2AmendOperation
;
3106 typedef struct Qcow2AmendHelperCBInfo
{
3107 /* The code coordinating the amend operations should only modify
3108 * these four fields; the rest will be managed by the CB */
3109 BlockDriverAmendStatusCB
*original_status_cb
;
3110 void *original_cb_opaque
;
3112 Qcow2AmendOperation current_operation
;
3114 /* Total number of operations to perform (only set once) */
3115 int total_operations
;
3117 /* The following fields are managed by the CB */
3119 /* Number of operations completed */
3120 int operations_completed
;
3122 /* Cumulative offset of all completed operations */
3123 int64_t offset_completed
;
3125 Qcow2AmendOperation last_operation
;
3126 int64_t last_work_size
;
3127 } Qcow2AmendHelperCBInfo
;
3129 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
3130 int64_t operation_offset
,
3131 int64_t operation_work_size
, void *opaque
)
3133 Qcow2AmendHelperCBInfo
*info
= opaque
;
3134 int64_t current_work_size
;
3135 int64_t projected_work_size
;
3137 if (info
->current_operation
!= info
->last_operation
) {
3138 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
3139 info
->offset_completed
+= info
->last_work_size
;
3140 info
->operations_completed
++;
3143 info
->last_operation
= info
->current_operation
;
3146 assert(info
->total_operations
> 0);
3147 assert(info
->operations_completed
< info
->total_operations
);
3149 info
->last_work_size
= operation_work_size
;
3151 current_work_size
= info
->offset_completed
+ operation_work_size
;
3153 /* current_work_size is the total work size for (operations_completed + 1)
3154 * operations (which includes this one), so multiply it by the number of
3155 * operations not covered and divide it by the number of operations
3156 * covered to get a projection for the operations not covered */
3157 projected_work_size
= current_work_size
* (info
->total_operations
-
3158 info
->operations_completed
- 1)
3159 / (info
->operations_completed
+ 1);
3161 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
3162 current_work_size
+ projected_work_size
,
3163 info
->original_cb_opaque
);
3166 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
3167 BlockDriverAmendStatusCB
*status_cb
,
3170 BDRVQcow2State
*s
= bs
->opaque
;
3171 int old_version
= s
->qcow_version
, new_version
= old_version
;
3172 uint64_t new_size
= 0;
3173 const char *backing_file
= NULL
, *backing_format
= NULL
;
3174 bool lazy_refcounts
= s
->use_lazy_refcounts
;
3175 const char *compat
= NULL
;
3176 uint64_t cluster_size
= s
->cluster_size
;
3178 int refcount_bits
= s
->refcount_bits
;
3179 Error
*local_err
= NULL
;
3181 QemuOptDesc
*desc
= opts
->list
->desc
;
3182 Qcow2AmendHelperCBInfo helper_cb_info
;
3184 while (desc
&& desc
->name
) {
3185 if (!qemu_opt_find(opts
, desc
->name
)) {
3186 /* only change explicitly defined options */
3191 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
3192 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
3194 /* preserve default */
3195 } else if (!strcmp(compat
, "0.10")) {
3197 } else if (!strcmp(compat
, "1.1")) {
3200 error_report("Unknown compatibility level %s", compat
);
3203 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
3204 error_report("Cannot change preallocation mode");
3206 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
3207 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
3208 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
3209 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
3210 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
3211 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
3212 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
3213 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
3216 if (encrypt
!= !!s
->cipher
) {
3217 error_report("Changing the encryption flag is not supported");
3220 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
3221 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
3223 if (cluster_size
!= s
->cluster_size
) {
3224 error_report("Changing the cluster size is not supported");
3227 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
3228 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
3230 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
3231 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
3234 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
3235 !is_power_of_2(refcount_bits
))
3237 error_report("Refcount width must be a power of two and may "
3238 "not exceed 64 bits");
3242 /* if this point is reached, this probably means a new option was
3243 * added without having it covered here */
3250 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
3251 .original_status_cb
= status_cb
,
3252 .original_cb_opaque
= cb_opaque
,
3253 .total_operations
= (new_version
< old_version
)
3254 + (s
->refcount_bits
!= refcount_bits
)
3257 /* Upgrade first (some features may require compat=1.1) */
3258 if (new_version
> old_version
) {
3259 s
->qcow_version
= new_version
;
3260 ret
= qcow2_update_header(bs
);
3262 s
->qcow_version
= old_version
;
3267 if (s
->refcount_bits
!= refcount_bits
) {
3268 int refcount_order
= ctz32(refcount_bits
);
3270 if (new_version
< 3 && refcount_bits
!= 16) {
3271 error_report("Different refcount widths than 16 bits require "
3272 "compatibility level 1.1 or above (use compat=1.1 or "
3277 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
3278 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
3279 &qcow2_amend_helper_cb
,
3280 &helper_cb_info
, &local_err
);
3282 error_report_err(local_err
);
3287 if (backing_file
|| backing_format
) {
3288 ret
= qcow2_change_backing_file(bs
,
3289 backing_file
?: s
->image_backing_file
,
3290 backing_format
?: s
->image_backing_format
);
3296 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
3297 if (lazy_refcounts
) {
3298 if (new_version
< 3) {
3299 error_report("Lazy refcounts only supported with compatibility "
3300 "level 1.1 and above (use compat=1.1 or greater)");
3303 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
3304 ret
= qcow2_update_header(bs
);
3306 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
3309 s
->use_lazy_refcounts
= true;
3311 /* make image clean first */
3312 ret
= qcow2_mark_clean(bs
);
3316 /* now disallow lazy refcounts */
3317 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
3318 ret
= qcow2_update_header(bs
);
3320 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
3323 s
->use_lazy_refcounts
= false;
3328 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
3329 ret
= blk_insert_bs(blk
, bs
, &local_err
);
3331 error_report_err(local_err
);
3336 ret
= blk_truncate(blk
, new_size
, &local_err
);
3339 error_report_err(local_err
);
3344 /* Downgrade last (so unsupported features can be removed before) */
3345 if (new_version
< old_version
) {
3346 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
3347 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
3358 * If offset or size are negative, respectively, they will not be included in
3359 * the BLOCK_IMAGE_CORRUPTED event emitted.
3360 * fatal will be ignored for read-only BDS; corruptions found there will always
3361 * be considered non-fatal.
3363 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
3364 int64_t size
, const char *message_format
, ...)
3366 BDRVQcow2State
*s
= bs
->opaque
;
3367 const char *node_name
;
3371 fatal
= fatal
&& !bs
->read_only
;
3373 if (s
->signaled_corruption
&&
3374 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
3379 va_start(ap
, message_format
);
3380 message
= g_strdup_vprintf(message_format
, ap
);
3384 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
3385 "corruption events will be suppressed\n", message
);
3387 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
3388 "corruption events will be suppressed\n", message
);
3391 node_name
= bdrv_get_node_name(bs
);
3392 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
3393 *node_name
!= '\0', node_name
,
3394 message
, offset
>= 0, offset
,
3396 fatal
, &error_abort
);
3400 qcow2_mark_corrupt(bs
);
3401 bs
->drv
= NULL
; /* make BDS unusable */
3404 s
->signaled_corruption
= true;
3407 static QemuOptsList qcow2_create_opts
= {
3408 .name
= "qcow2-create-opts",
3409 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
3412 .name
= BLOCK_OPT_SIZE
,
3413 .type
= QEMU_OPT_SIZE
,
3414 .help
= "Virtual disk size"
3417 .name
= BLOCK_OPT_COMPAT_LEVEL
,
3418 .type
= QEMU_OPT_STRING
,
3419 .help
= "Compatibility level (0.10 or 1.1)"
3422 .name
= BLOCK_OPT_BACKING_FILE
,
3423 .type
= QEMU_OPT_STRING
,
3424 .help
= "File name of a base image"
3427 .name
= BLOCK_OPT_BACKING_FMT
,
3428 .type
= QEMU_OPT_STRING
,
3429 .help
= "Image format of the base image"
3432 .name
= BLOCK_OPT_ENCRYPT
,
3433 .type
= QEMU_OPT_BOOL
,
3434 .help
= "Encrypt the image",
3435 .def_value_str
= "off"
3438 .name
= BLOCK_OPT_CLUSTER_SIZE
,
3439 .type
= QEMU_OPT_SIZE
,
3440 .help
= "qcow2 cluster size",
3441 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
3444 .name
= BLOCK_OPT_PREALLOC
,
3445 .type
= QEMU_OPT_STRING
,
3446 .help
= "Preallocation mode (allowed values: off, metadata, "
3450 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
3451 .type
= QEMU_OPT_BOOL
,
3452 .help
= "Postpone refcount updates",
3453 .def_value_str
= "off"
3456 .name
= BLOCK_OPT_REFCOUNT_BITS
,
3457 .type
= QEMU_OPT_NUMBER
,
3458 .help
= "Width of a reference count entry in bits",
3459 .def_value_str
= "16"
3461 { /* end of list */ }
3465 BlockDriver bdrv_qcow2
= {
3466 .format_name
= "qcow2",
3467 .instance_size
= sizeof(BDRVQcow2State
),
3468 .bdrv_probe
= qcow2_probe
,
3469 .bdrv_open
= qcow2_open
,
3470 .bdrv_close
= qcow2_close
,
3471 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
3472 .bdrv_reopen_commit
= qcow2_reopen_commit
,
3473 .bdrv_reopen_abort
= qcow2_reopen_abort
,
3474 .bdrv_join_options
= qcow2_join_options
,
3475 .bdrv_child_perm
= bdrv_format_default_perms
,
3476 .bdrv_create
= qcow2_create
,
3477 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3478 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
3479 .bdrv_set_key
= qcow2_set_key
,
3481 .bdrv_co_preadv
= qcow2_co_preadv
,
3482 .bdrv_co_pwritev
= qcow2_co_pwritev
,
3483 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
3485 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
3486 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
3487 .bdrv_truncate
= qcow2_truncate
,
3488 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
3489 .bdrv_make_empty
= qcow2_make_empty
,
3491 .bdrv_snapshot_create
= qcow2_snapshot_create
,
3492 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
3493 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
3494 .bdrv_snapshot_list
= qcow2_snapshot_list
,
3495 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
3496 .bdrv_get_info
= qcow2_get_info
,
3497 .bdrv_get_specific_info
= qcow2_get_specific_info
,
3499 .bdrv_save_vmstate
= qcow2_save_vmstate
,
3500 .bdrv_load_vmstate
= qcow2_load_vmstate
,
3502 .supports_backing
= true,
3503 .bdrv_change_backing_file
= qcow2_change_backing_file
,
3505 .bdrv_refresh_limits
= qcow2_refresh_limits
,
3506 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
3507 .bdrv_inactivate
= qcow2_inactivate
,
3509 .create_opts
= &qcow2_create_opts
,
3510 .bdrv_check
= qcow2_check
,
3511 .bdrv_amend_options
= qcow2_amend_options
,
3513 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
3514 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
3517 static void bdrv_qcow2_init(void)
3519 bdrv_register(&bdrv_qcow2
);
3522 block_init(bdrv_qcow2_init
);