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-common.h"
25 #include "block/block_int.h"
26 #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"
35 #include "qemu/option_int.h"
38 Differences with QCOW:
40 - Support for multiple incremental snapshots.
41 - Memory management by reference counts.
42 - Clusters which have a reference count of one have the bit
43 QCOW_OFLAG_COPIED to optimize write performance.
44 - Size of compressed clusters is stored in sectors to reduce bit usage
45 in the cluster offsets.
46 - Support for storing additional data (such as the VM state) in the
48 - If a backing store is used, the cluster size is not constrained
49 (could be backported to QCOW).
50 - L2 tables have always a size of one cluster.
57 } QEMU_PACKED QCowExtension
;
59 #define QCOW2_EXT_MAGIC_END 0
60 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
61 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
63 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
65 const QCowHeader
*cow_header
= (const void *)buf
;
67 if (buf_size
>= sizeof(QCowHeader
) &&
68 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
69 be32_to_cpu(cow_header
->version
) >= 2)
77 * read qcow2 extension and fill bs
78 * start reading from start_offset
79 * finish reading upon magic of value 0 or when end_offset reached
80 * unknown magic is skipped (future extension this version knows nothing about)
81 * return 0 upon success, non-0 otherwise
83 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
84 uint64_t end_offset
, void **p_feature_table
,
87 BDRVQcowState
*s
= bs
->opaque
;
93 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
95 offset
= start_offset
;
96 while (offset
< end_offset
) {
100 if (offset
> s
->cluster_size
)
101 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
103 printf("attempting to read extended header in offset %lu\n", offset
);
106 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
108 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
109 "pread fail from offset %" PRIu64
, offset
);
112 be32_to_cpus(&ext
.magic
);
113 be32_to_cpus(&ext
.len
);
114 offset
+= sizeof(ext
);
116 printf("ext.magic = 0x%x\n", ext
.magic
);
118 if (ext
.len
> end_offset
- offset
) {
119 error_setg(errp
, "Header extension too large");
124 case QCOW2_EXT_MAGIC_END
:
127 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
128 if (ext
.len
>= sizeof(bs
->backing_format
)) {
129 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
130 " too large (>=%zu)", ext
.len
,
131 sizeof(bs
->backing_format
));
134 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
136 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
137 "Could not read format name");
140 bs
->backing_format
[ext
.len
] = '\0';
142 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
146 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
147 if (p_feature_table
!= NULL
) {
148 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
149 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
151 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
152 "Could not read table");
156 *p_feature_table
= feature_table
;
161 /* unknown magic - save it in case we need to rewrite the header */
163 Qcow2UnknownHeaderExtension
*uext
;
165 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
166 uext
->magic
= ext
.magic
;
168 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
170 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
172 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
173 "Could not read data");
180 offset
+= ((ext
.len
+ 7) & ~7);
186 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
188 BDRVQcowState
*s
= bs
->opaque
;
189 Qcow2UnknownHeaderExtension
*uext
, *next
;
191 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
192 QLIST_REMOVE(uext
, next
);
197 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState
*bs
,
198 Error
**errp
, const char *fmt
, ...)
204 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
207 error_set(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
, bs
->device_name
, "qcow2",
211 static void report_unsupported_feature(BlockDriverState
*bs
,
212 Error
**errp
, Qcow2Feature
*table
, uint64_t mask
)
214 char *features
= g_strdup("");
217 while (table
&& table
->name
[0] != '\0') {
218 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
219 if (mask
& (1ULL << table
->bit
)) {
221 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
224 mask
&= ~(1ULL << table
->bit
);
232 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
233 old
, *old
? ", " : "", mask
);
237 report_unsupported(bs
, errp
, "%s", features
);
242 * Sets the dirty bit and flushes afterwards if necessary.
244 * The incompatible_features bit is only set if the image file header was
245 * updated successfully. Therefore it is not required to check the return
246 * value of this function.
248 int qcow2_mark_dirty(BlockDriverState
*bs
)
250 BDRVQcowState
*s
= bs
->opaque
;
254 assert(s
->qcow_version
>= 3);
256 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
257 return 0; /* already dirty */
260 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
261 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
266 ret
= bdrv_flush(bs
->file
);
271 /* Only treat image as dirty if the header was updated successfully */
272 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
277 * Clears the dirty bit and flushes before if necessary. Only call this
278 * function when there are no pending requests, it does not guard against
279 * concurrent requests dirtying the image.
281 static int qcow2_mark_clean(BlockDriverState
*bs
)
283 BDRVQcowState
*s
= bs
->opaque
;
285 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
288 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
290 ret
= bdrv_flush(bs
);
295 return qcow2_update_header(bs
);
301 * Marks the image as corrupt.
303 int qcow2_mark_corrupt(BlockDriverState
*bs
)
305 BDRVQcowState
*s
= bs
->opaque
;
307 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
308 return qcow2_update_header(bs
);
312 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
313 * before if necessary.
315 int qcow2_mark_consistent(BlockDriverState
*bs
)
317 BDRVQcowState
*s
= bs
->opaque
;
319 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
320 int ret
= bdrv_flush(bs
);
325 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
326 return qcow2_update_header(bs
);
331 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
334 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
339 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
340 ret
= qcow2_mark_clean(bs
);
344 return qcow2_mark_consistent(bs
);
349 static int validate_table_offset(BlockDriverState
*bs
, uint64_t offset
,
350 uint64_t entries
, size_t entry_len
)
352 BDRVQcowState
*s
= bs
->opaque
;
355 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
356 * because values will be passed to qemu functions taking int64_t. */
357 if (entries
> INT64_MAX
/ entry_len
) {
361 size
= entries
* entry_len
;
363 if (INT64_MAX
- size
< offset
) {
367 /* Tables must be cluster aligned */
368 if (offset
& (s
->cluster_size
- 1)) {
375 static QemuOptsList qcow2_runtime_opts
= {
377 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
380 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
381 .type
= QEMU_OPT_BOOL
,
382 .help
= "Postpone refcount updates",
385 .name
= QCOW2_OPT_DISCARD_REQUEST
,
386 .type
= QEMU_OPT_BOOL
,
387 .help
= "Pass guest discard requests to the layer below",
390 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
391 .type
= QEMU_OPT_BOOL
,
392 .help
= "Generate discard requests when snapshot related space "
396 .name
= QCOW2_OPT_DISCARD_OTHER
,
397 .type
= QEMU_OPT_BOOL
,
398 .help
= "Generate discard requests when other clusters are freed",
401 .name
= QCOW2_OPT_OVERLAP
,
402 .type
= QEMU_OPT_STRING
,
403 .help
= "Selects which overlap checks to perform from a range of "
404 "templates (none, constant, cached, all)",
407 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
408 .type
= QEMU_OPT_BOOL
,
409 .help
= "Check for unintended writes into the main qcow2 header",
412 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
413 .type
= QEMU_OPT_BOOL
,
414 .help
= "Check for unintended writes into the active L1 table",
417 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
418 .type
= QEMU_OPT_BOOL
,
419 .help
= "Check for unintended writes into an active L2 table",
422 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
423 .type
= QEMU_OPT_BOOL
,
424 .help
= "Check for unintended writes into the refcount table",
427 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
428 .type
= QEMU_OPT_BOOL
,
429 .help
= "Check for unintended writes into a refcount block",
432 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
433 .type
= QEMU_OPT_BOOL
,
434 .help
= "Check for unintended writes into the snapshot table",
437 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
438 .type
= QEMU_OPT_BOOL
,
439 .help
= "Check for unintended writes into an inactive L1 table",
442 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
443 .type
= QEMU_OPT_BOOL
,
444 .help
= "Check for unintended writes into an inactive L2 table",
447 .name
= QCOW2_OPT_CACHE_SIZE
,
448 .type
= QEMU_OPT_SIZE
,
449 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
453 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
454 .type
= QEMU_OPT_SIZE
,
455 .help
= "Maximum L2 table cache size",
458 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
459 .type
= QEMU_OPT_SIZE
,
460 .help
= "Maximum refcount block cache size",
462 { /* end of list */ }
466 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
467 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
468 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
469 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
470 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
471 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
472 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
473 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
474 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
477 static void read_cache_sizes(QemuOpts
*opts
, uint64_t *l2_cache_size
,
478 uint64_t *refcount_cache_size
, Error
**errp
)
480 uint64_t combined_cache_size
;
481 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
483 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
484 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
485 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
487 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
488 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
489 *refcount_cache_size
= qemu_opt_get_size(opts
,
490 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
492 if (combined_cache_size_set
) {
493 if (l2_cache_size_set
&& refcount_cache_size_set
) {
494 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
495 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
498 } else if (*l2_cache_size
> combined_cache_size
) {
499 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
500 QCOW2_OPT_CACHE_SIZE
);
502 } else if (*refcount_cache_size
> combined_cache_size
) {
503 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
504 QCOW2_OPT_CACHE_SIZE
);
508 if (l2_cache_size_set
) {
509 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
510 } else if (refcount_cache_size_set
) {
511 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
513 *refcount_cache_size
= combined_cache_size
514 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO
+ 1);
515 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
518 if (!l2_cache_size_set
&& !refcount_cache_size_set
) {
519 *l2_cache_size
= DEFAULT_L2_CACHE_BYTE_SIZE
;
520 *refcount_cache_size
= *l2_cache_size
521 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
522 } else if (!l2_cache_size_set
) {
523 *l2_cache_size
= *refcount_cache_size
524 * DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
525 } else if (!refcount_cache_size_set
) {
526 *refcount_cache_size
= *l2_cache_size
527 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
532 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
535 BDRVQcowState
*s
= bs
->opaque
;
540 Error
*local_err
= NULL
;
542 uint64_t l1_vm_state_index
;
543 const char *opt_overlap_check
;
544 int overlap_check_template
= 0;
545 uint64_t l2_cache_size
, refcount_cache_size
;
547 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
549 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
552 be32_to_cpus(&header
.magic
);
553 be32_to_cpus(&header
.version
);
554 be64_to_cpus(&header
.backing_file_offset
);
555 be32_to_cpus(&header
.backing_file_size
);
556 be64_to_cpus(&header
.size
);
557 be32_to_cpus(&header
.cluster_bits
);
558 be32_to_cpus(&header
.crypt_method
);
559 be64_to_cpus(&header
.l1_table_offset
);
560 be32_to_cpus(&header
.l1_size
);
561 be64_to_cpus(&header
.refcount_table_offset
);
562 be32_to_cpus(&header
.refcount_table_clusters
);
563 be64_to_cpus(&header
.snapshots_offset
);
564 be32_to_cpus(&header
.nb_snapshots
);
566 if (header
.magic
!= QCOW_MAGIC
) {
567 error_setg(errp
, "Image is not in qcow2 format");
571 if (header
.version
< 2 || header
.version
> 3) {
572 report_unsupported(bs
, errp
, "QCOW version %" PRIu32
, header
.version
);
577 s
->qcow_version
= header
.version
;
579 /* Initialise cluster size */
580 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
581 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
582 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
583 header
.cluster_bits
);
588 s
->cluster_bits
= header
.cluster_bits
;
589 s
->cluster_size
= 1 << s
->cluster_bits
;
590 s
->cluster_sectors
= 1 << (s
->cluster_bits
- 9);
592 /* Initialise version 3 header fields */
593 if (header
.version
== 2) {
594 header
.incompatible_features
= 0;
595 header
.compatible_features
= 0;
596 header
.autoclear_features
= 0;
597 header
.refcount_order
= 4;
598 header
.header_length
= 72;
600 be64_to_cpus(&header
.incompatible_features
);
601 be64_to_cpus(&header
.compatible_features
);
602 be64_to_cpus(&header
.autoclear_features
);
603 be32_to_cpus(&header
.refcount_order
);
604 be32_to_cpus(&header
.header_length
);
606 if (header
.header_length
< 104) {
607 error_setg(errp
, "qcow2 header too short");
613 if (header
.header_length
> s
->cluster_size
) {
614 error_setg(errp
, "qcow2 header exceeds cluster size");
619 if (header
.header_length
> sizeof(header
)) {
620 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
621 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
622 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
623 s
->unknown_header_fields_size
);
625 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
631 if (header
.backing_file_offset
> s
->cluster_size
) {
632 error_setg(errp
, "Invalid backing file offset");
637 if (header
.backing_file_offset
) {
638 ext_end
= header
.backing_file_offset
;
640 ext_end
= 1 << header
.cluster_bits
;
643 /* Handle feature bits */
644 s
->incompatible_features
= header
.incompatible_features
;
645 s
->compatible_features
= header
.compatible_features
;
646 s
->autoclear_features
= header
.autoclear_features
;
648 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
649 void *feature_table
= NULL
;
650 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
651 &feature_table
, NULL
);
652 report_unsupported_feature(bs
, errp
, feature_table
,
653 s
->incompatible_features
&
654 ~QCOW2_INCOMPAT_MASK
);
656 g_free(feature_table
);
660 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
661 /* Corrupt images may not be written to unless they are being repaired
663 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
664 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
671 /* Check support for various header values */
672 if (header
.refcount_order
!= 4) {
673 report_unsupported(bs
, errp
, "%d bit reference counts",
674 1 << header
.refcount_order
);
678 s
->refcount_order
= header
.refcount_order
;
680 if (header
.crypt_method
> QCOW_CRYPT_AES
) {
681 error_setg(errp
, "Unsupported encryption method: %" PRIu32
,
682 header
.crypt_method
);
686 s
->crypt_method_header
= header
.crypt_method
;
687 if (s
->crypt_method_header
) {
691 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
692 s
->l2_size
= 1 << s
->l2_bits
;
693 bs
->total_sectors
= header
.size
/ 512;
694 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
695 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
696 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
698 s
->refcount_table_offset
= header
.refcount_table_offset
;
699 s
->refcount_table_size
=
700 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
702 if (header
.refcount_table_clusters
> qcow2_max_refcount_clusters(s
)) {
703 error_setg(errp
, "Reference count table too large");
708 ret
= validate_table_offset(bs
, s
->refcount_table_offset
,
709 s
->refcount_table_size
, sizeof(uint64_t));
711 error_setg(errp
, "Invalid reference count table offset");
715 /* Snapshot table offset/length */
716 if (header
.nb_snapshots
> QCOW_MAX_SNAPSHOTS
) {
717 error_setg(errp
, "Too many snapshots");
722 ret
= validate_table_offset(bs
, header
.snapshots_offset
,
724 sizeof(QCowSnapshotHeader
));
726 error_setg(errp
, "Invalid snapshot table offset");
730 /* read the level 1 table */
731 if (header
.l1_size
> QCOW_MAX_L1_SIZE
) {
732 error_setg(errp
, "Active L1 table too large");
736 s
->l1_size
= header
.l1_size
;
738 l1_vm_state_index
= size_to_l1(s
, header
.size
);
739 if (l1_vm_state_index
> INT_MAX
) {
740 error_setg(errp
, "Image is too big");
744 s
->l1_vm_state_index
= l1_vm_state_index
;
746 /* the L1 table must contain at least enough entries to put
748 if (s
->l1_size
< s
->l1_vm_state_index
) {
749 error_setg(errp
, "L1 table is too small");
754 ret
= validate_table_offset(bs
, header
.l1_table_offset
,
755 header
.l1_size
, sizeof(uint64_t));
757 error_setg(errp
, "Invalid L1 table offset");
760 s
->l1_table_offset
= header
.l1_table_offset
;
763 if (s
->l1_size
> 0) {
764 s
->l1_table
= qemu_try_blockalign(bs
->file
,
765 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
766 if (s
->l1_table
== NULL
) {
767 error_setg(errp
, "Could not allocate L1 table");
771 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
772 s
->l1_size
* sizeof(uint64_t));
774 error_setg_errno(errp
, -ret
, "Could not read L1 table");
777 for(i
= 0;i
< s
->l1_size
; i
++) {
778 be64_to_cpus(&s
->l1_table
[i
]);
782 /* get L2 table/refcount block cache size from command line options */
783 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
784 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
786 error_propagate(errp
, local_err
);
791 read_cache_sizes(opts
, &l2_cache_size
, &refcount_cache_size
, &local_err
);
793 error_propagate(errp
, local_err
);
798 l2_cache_size
/= s
->cluster_size
;
799 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
800 l2_cache_size
= MIN_L2_CACHE_SIZE
;
802 if (l2_cache_size
> INT_MAX
) {
803 error_setg(errp
, "L2 cache size too big");
808 refcount_cache_size
/= s
->cluster_size
;
809 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
810 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
812 if (refcount_cache_size
> INT_MAX
) {
813 error_setg(errp
, "Refcount cache size too big");
818 /* alloc L2 table/refcount block cache */
819 s
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
);
820 s
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
);
821 if (s
->l2_table_cache
== NULL
|| s
->refcount_block_cache
== NULL
) {
822 error_setg(errp
, "Could not allocate metadata caches");
827 s
->cluster_cache
= g_malloc(s
->cluster_size
);
828 /* one more sector for decompressed data alignment */
829 s
->cluster_data
= qemu_try_blockalign(bs
->file
, QCOW_MAX_CRYPT_CLUSTERS
830 * s
->cluster_size
+ 512);
831 if (s
->cluster_data
== NULL
) {
832 error_setg(errp
, "Could not allocate temporary cluster buffer");
837 s
->cluster_cache_offset
= -1;
840 ret
= qcow2_refcount_init(bs
);
842 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
846 QLIST_INIT(&s
->cluster_allocs
);
847 QTAILQ_INIT(&s
->discards
);
849 /* read qcow2 extensions */
850 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
852 error_propagate(errp
, local_err
);
857 /* read the backing file name */
858 if (header
.backing_file_offset
!= 0) {
859 len
= header
.backing_file_size
;
860 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
)) {
861 error_setg(errp
, "Backing file name too long");
865 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
866 bs
->backing_file
, len
);
868 error_setg_errno(errp
, -ret
, "Could not read backing file name");
871 bs
->backing_file
[len
] = '\0';
874 /* Internal snapshots */
875 s
->snapshots_offset
= header
.snapshots_offset
;
876 s
->nb_snapshots
= header
.nb_snapshots
;
878 ret
= qcow2_read_snapshots(bs
);
880 error_setg_errno(errp
, -ret
, "Could not read snapshots");
884 /* Clear unknown autoclear feature bits */
885 if (!bs
->read_only
&& !(flags
& BDRV_O_INCOMING
) && s
->autoclear_features
) {
886 s
->autoclear_features
= 0;
887 ret
= qcow2_update_header(bs
);
889 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
894 /* Initialise locks */
895 qemu_co_mutex_init(&s
->lock
);
897 /* Repair image if dirty */
898 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INCOMING
)) && !bs
->read_only
&&
899 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
900 BdrvCheckResult result
= {0};
902 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
);
904 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
909 /* Enable lazy_refcounts according to image and command line options */
910 s
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
911 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
913 s
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
914 s
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
915 s
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
916 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
917 flags
& BDRV_O_UNMAP
);
918 s
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
919 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
920 s
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
921 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
923 opt_overlap_check
= qemu_opt_get(opts
, "overlap-check") ?: "cached";
924 if (!strcmp(opt_overlap_check
, "none")) {
925 overlap_check_template
= 0;
926 } else if (!strcmp(opt_overlap_check
, "constant")) {
927 overlap_check_template
= QCOW2_OL_CONSTANT
;
928 } else if (!strcmp(opt_overlap_check
, "cached")) {
929 overlap_check_template
= QCOW2_OL_CACHED
;
930 } else if (!strcmp(opt_overlap_check
, "all")) {
931 overlap_check_template
= QCOW2_OL_ALL
;
933 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
934 "'overlap-check'. Allowed are either of the following: "
935 "none, constant, cached, all", opt_overlap_check
);
941 s
->overlap_check
= 0;
942 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
943 /* overlap-check defines a template bitmask, but every flag may be
944 * overwritten through the associated boolean option */
946 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
947 overlap_check_template
& (1 << i
)) << i
;
952 if (s
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
953 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
954 "qemu 1.1 compatibility level");
961 BdrvCheckResult result
= {0};
962 qcow2_check_refcounts(bs
, &result
, 0);
968 g_free(s
->unknown_header_fields
);
969 cleanup_unknown_header_ext(bs
);
970 qcow2_free_snapshots(bs
);
971 qcow2_refcount_close(bs
);
972 qemu_vfree(s
->l1_table
);
973 /* else pre-write overlap checks in cache_destroy may crash */
975 if (s
->l2_table_cache
) {
976 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
978 if (s
->refcount_block_cache
) {
979 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
981 g_free(s
->cluster_cache
);
982 qemu_vfree(s
->cluster_data
);
986 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
988 BDRVQcowState
*s
= bs
->opaque
;
990 bs
->bl
.write_zeroes_alignment
= s
->cluster_sectors
;
993 static int qcow2_set_key(BlockDriverState
*bs
, const char *key
)
995 BDRVQcowState
*s
= bs
->opaque
;
999 memset(keybuf
, 0, 16);
1003 /* XXX: we could compress the chars to 7 bits to increase
1005 for(i
= 0;i
< len
;i
++) {
1008 s
->crypt_method
= s
->crypt_method_header
;
1010 if (AES_set_encrypt_key(keybuf
, 128, &s
->aes_encrypt_key
) != 0)
1012 if (AES_set_decrypt_key(keybuf
, 128, &s
->aes_decrypt_key
) != 0)
1022 AES_encrypt(in
, tmp
, &s
->aes_encrypt_key
);
1023 AES_decrypt(tmp
, out
, &s
->aes_decrypt_key
);
1024 for(i
= 0; i
< 16; i
++)
1025 printf(" %02x", tmp
[i
]);
1027 for(i
= 0; i
< 16; i
++)
1028 printf(" %02x", out
[i
]);
1035 /* We have no actual commit/abort logic for qcow2, but we need to write out any
1036 * unwritten data if we reopen read-only. */
1037 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1038 BlockReopenQueue
*queue
, Error
**errp
)
1042 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1043 ret
= bdrv_flush(state
->bs
);
1048 ret
= qcow2_mark_clean(state
->bs
);
1057 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
1058 int64_t sector_num
, int nb_sectors
, int *pnum
)
1060 BDRVQcowState
*s
= bs
->opaque
;
1061 uint64_t cluster_offset
;
1062 int index_in_cluster
, ret
;
1066 qemu_co_mutex_lock(&s
->lock
);
1067 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9, pnum
, &cluster_offset
);
1068 qemu_co_mutex_unlock(&s
->lock
);
1073 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1075 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1076 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
1077 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
1079 if (ret
== QCOW2_CLUSTER_ZERO
) {
1080 status
|= BDRV_BLOCK_ZERO
;
1081 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1082 status
|= BDRV_BLOCK_DATA
;
1087 /* handle reading after the end of the backing file */
1088 int qcow2_backing_read1(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
1089 int64_t sector_num
, int nb_sectors
)
1092 if ((sector_num
+ nb_sectors
) <= bs
->total_sectors
)
1094 if (sector_num
>= bs
->total_sectors
)
1097 n1
= bs
->total_sectors
- sector_num
;
1099 qemu_iovec_memset(qiov
, 512 * n1
, 0, 512 * (nb_sectors
- n1
));
1104 static coroutine_fn
int qcow2_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
1105 int remaining_sectors
, QEMUIOVector
*qiov
)
1107 BDRVQcowState
*s
= bs
->opaque
;
1108 int index_in_cluster
, n1
;
1110 int cur_nr_sectors
; /* number of sectors in current iteration */
1111 uint64_t cluster_offset
= 0;
1112 uint64_t bytes_done
= 0;
1113 QEMUIOVector hd_qiov
;
1114 uint8_t *cluster_data
= NULL
;
1116 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1118 qemu_co_mutex_lock(&s
->lock
);
1120 while (remaining_sectors
!= 0) {
1122 /* prepare next request */
1123 cur_nr_sectors
= remaining_sectors
;
1124 if (s
->crypt_method
) {
1125 cur_nr_sectors
= MIN(cur_nr_sectors
,
1126 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
1129 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9,
1130 &cur_nr_sectors
, &cluster_offset
);
1135 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1137 qemu_iovec_reset(&hd_qiov
);
1138 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
1139 cur_nr_sectors
* 512);
1142 case QCOW2_CLUSTER_UNALLOCATED
:
1144 if (bs
->backing_hd
) {
1145 /* read from the base image */
1146 n1
= qcow2_backing_read1(bs
->backing_hd
, &hd_qiov
,
1147 sector_num
, cur_nr_sectors
);
1149 QEMUIOVector local_qiov
;
1151 qemu_iovec_init(&local_qiov
, hd_qiov
.niov
);
1152 qemu_iovec_concat(&local_qiov
, &hd_qiov
, 0,
1153 n1
* BDRV_SECTOR_SIZE
);
1155 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1156 qemu_co_mutex_unlock(&s
->lock
);
1157 ret
= bdrv_co_readv(bs
->backing_hd
, sector_num
,
1159 qemu_co_mutex_lock(&s
->lock
);
1161 qemu_iovec_destroy(&local_qiov
);
1168 /* Note: in this case, no need to wait */
1169 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
1173 case QCOW2_CLUSTER_ZERO
:
1174 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
1177 case QCOW2_CLUSTER_COMPRESSED
:
1178 /* add AIO support for compressed blocks ? */
1179 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1184 qemu_iovec_from_buf(&hd_qiov
, 0,
1185 s
->cluster_cache
+ index_in_cluster
* 512,
1186 512 * cur_nr_sectors
);
1189 case QCOW2_CLUSTER_NORMAL
:
1190 if ((cluster_offset
& 511) != 0) {
1195 if (s
->crypt_method
) {
1197 * For encrypted images, read everything into a temporary
1198 * contiguous buffer on which the AES functions can work.
1200 if (!cluster_data
) {
1202 qemu_try_blockalign(bs
->file
, QCOW_MAX_CRYPT_CLUSTERS
1204 if (cluster_data
== NULL
) {
1210 assert(cur_nr_sectors
<=
1211 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
1212 qemu_iovec_reset(&hd_qiov
);
1213 qemu_iovec_add(&hd_qiov
, cluster_data
,
1214 512 * cur_nr_sectors
);
1217 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1218 qemu_co_mutex_unlock(&s
->lock
);
1219 ret
= bdrv_co_readv(bs
->file
,
1220 (cluster_offset
>> 9) + index_in_cluster
,
1221 cur_nr_sectors
, &hd_qiov
);
1222 qemu_co_mutex_lock(&s
->lock
);
1226 if (s
->crypt_method
) {
1227 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
1228 cluster_data
, cur_nr_sectors
, 0, &s
->aes_decrypt_key
);
1229 qemu_iovec_from_buf(qiov
, bytes_done
,
1230 cluster_data
, 512 * cur_nr_sectors
);
1235 g_assert_not_reached();
1240 remaining_sectors
-= cur_nr_sectors
;
1241 sector_num
+= cur_nr_sectors
;
1242 bytes_done
+= cur_nr_sectors
* 512;
1247 qemu_co_mutex_unlock(&s
->lock
);
1249 qemu_iovec_destroy(&hd_qiov
);
1250 qemu_vfree(cluster_data
);
1255 static coroutine_fn
int qcow2_co_writev(BlockDriverState
*bs
,
1257 int remaining_sectors
,
1260 BDRVQcowState
*s
= bs
->opaque
;
1261 int index_in_cluster
;
1263 int cur_nr_sectors
; /* number of sectors in current iteration */
1264 uint64_t cluster_offset
;
1265 QEMUIOVector hd_qiov
;
1266 uint64_t bytes_done
= 0;
1267 uint8_t *cluster_data
= NULL
;
1268 QCowL2Meta
*l2meta
= NULL
;
1270 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num
,
1273 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1275 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1277 qemu_co_mutex_lock(&s
->lock
);
1279 while (remaining_sectors
!= 0) {
1283 trace_qcow2_writev_start_part(qemu_coroutine_self());
1284 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1285 cur_nr_sectors
= remaining_sectors
;
1286 if (s
->crypt_method
&&
1288 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
- index_in_cluster
) {
1290 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
- index_in_cluster
;
1293 ret
= qcow2_alloc_cluster_offset(bs
, sector_num
<< 9,
1294 &cur_nr_sectors
, &cluster_offset
, &l2meta
);
1299 assert((cluster_offset
& 511) == 0);
1301 qemu_iovec_reset(&hd_qiov
);
1302 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
1303 cur_nr_sectors
* 512);
1305 if (s
->crypt_method
) {
1306 if (!cluster_data
) {
1307 cluster_data
= qemu_try_blockalign(bs
->file
,
1308 QCOW_MAX_CRYPT_CLUSTERS
1310 if (cluster_data
== NULL
) {
1316 assert(hd_qiov
.size
<=
1317 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1318 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
1320 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
1321 cluster_data
, cur_nr_sectors
, 1, &s
->aes_encrypt_key
);
1323 qemu_iovec_reset(&hd_qiov
);
1324 qemu_iovec_add(&hd_qiov
, cluster_data
,
1325 cur_nr_sectors
* 512);
1328 ret
= qcow2_pre_write_overlap_check(bs
, 0,
1329 cluster_offset
+ index_in_cluster
* BDRV_SECTOR_SIZE
,
1330 cur_nr_sectors
* BDRV_SECTOR_SIZE
);
1335 qemu_co_mutex_unlock(&s
->lock
);
1336 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
1337 trace_qcow2_writev_data(qemu_coroutine_self(),
1338 (cluster_offset
>> 9) + index_in_cluster
);
1339 ret
= bdrv_co_writev(bs
->file
,
1340 (cluster_offset
>> 9) + index_in_cluster
,
1341 cur_nr_sectors
, &hd_qiov
);
1342 qemu_co_mutex_lock(&s
->lock
);
1347 while (l2meta
!= NULL
) {
1350 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1355 /* Take the request off the list of running requests */
1356 if (l2meta
->nb_clusters
!= 0) {
1357 QLIST_REMOVE(l2meta
, next_in_flight
);
1360 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1362 next
= l2meta
->next
;
1367 remaining_sectors
-= cur_nr_sectors
;
1368 sector_num
+= cur_nr_sectors
;
1369 bytes_done
+= cur_nr_sectors
* 512;
1370 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors
);
1375 qemu_co_mutex_unlock(&s
->lock
);
1377 while (l2meta
!= NULL
) {
1380 if (l2meta
->nb_clusters
!= 0) {
1381 QLIST_REMOVE(l2meta
, next_in_flight
);
1383 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1385 next
= l2meta
->next
;
1390 qemu_iovec_destroy(&hd_qiov
);
1391 qemu_vfree(cluster_data
);
1392 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
1397 static void qcow2_close(BlockDriverState
*bs
)
1399 BDRVQcowState
*s
= bs
->opaque
;
1400 qemu_vfree(s
->l1_table
);
1401 /* else pre-write overlap checks in cache_destroy may crash */
1404 if (!(bs
->open_flags
& BDRV_O_INCOMING
)) {
1405 qcow2_cache_flush(bs
, s
->l2_table_cache
);
1406 qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1408 qcow2_mark_clean(bs
);
1411 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1412 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1414 g_free(s
->unknown_header_fields
);
1415 cleanup_unknown_header_ext(bs
);
1417 g_free(s
->cluster_cache
);
1418 qemu_vfree(s
->cluster_data
);
1419 qcow2_refcount_close(bs
);
1420 qcow2_free_snapshots(bs
);
1423 static void qcow2_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
1425 BDRVQcowState
*s
= bs
->opaque
;
1426 int flags
= s
->flags
;
1427 AES_KEY aes_encrypt_key
;
1428 AES_KEY aes_decrypt_key
;
1429 uint32_t crypt_method
= 0;
1431 Error
*local_err
= NULL
;
1435 * Backing files are read-only which makes all of their metadata immutable,
1436 * that means we don't have to worry about reopening them here.
1439 if (s
->crypt_method
) {
1440 crypt_method
= s
->crypt_method
;
1441 memcpy(&aes_encrypt_key
, &s
->aes_encrypt_key
, sizeof(aes_encrypt_key
));
1442 memcpy(&aes_decrypt_key
, &s
->aes_decrypt_key
, sizeof(aes_decrypt_key
));
1447 bdrv_invalidate_cache(bs
->file
, &local_err
);
1449 error_propagate(errp
, local_err
);
1453 memset(s
, 0, sizeof(BDRVQcowState
));
1454 options
= qdict_clone_shallow(bs
->options
);
1456 ret
= qcow2_open(bs
, options
, flags
, &local_err
);
1459 error_setg(errp
, "Could not reopen qcow2 layer: %s",
1460 error_get_pretty(local_err
));
1461 error_free(local_err
);
1463 } else if (ret
< 0) {
1464 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
1469 s
->crypt_method
= crypt_method
;
1470 memcpy(&s
->aes_encrypt_key
, &aes_encrypt_key
, sizeof(aes_encrypt_key
));
1471 memcpy(&s
->aes_decrypt_key
, &aes_decrypt_key
, sizeof(aes_decrypt_key
));
1475 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
1476 size_t len
, size_t buflen
)
1478 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
1479 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
1481 if (buflen
< ext_len
) {
1485 *ext_backing_fmt
= (QCowExtension
) {
1486 .magic
= cpu_to_be32(magic
),
1487 .len
= cpu_to_be32(len
),
1489 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
1495 * Updates the qcow2 header, including the variable length parts of it, i.e.
1496 * the backing file name and all extensions. qcow2 was not designed to allow
1497 * such changes, so if we run out of space (we can only use the first cluster)
1498 * this function may fail.
1500 * Returns 0 on success, -errno in error cases.
1502 int qcow2_update_header(BlockDriverState
*bs
)
1504 BDRVQcowState
*s
= bs
->opaque
;
1507 size_t buflen
= s
->cluster_size
;
1509 uint64_t total_size
;
1510 uint32_t refcount_table_clusters
;
1511 size_t header_length
;
1512 Qcow2UnknownHeaderExtension
*uext
;
1514 buf
= qemu_blockalign(bs
, buflen
);
1516 /* Header structure */
1517 header
= (QCowHeader
*) buf
;
1519 if (buflen
< sizeof(*header
)) {
1524 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
1525 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1526 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
1528 *header
= (QCowHeader
) {
1529 /* Version 2 fields */
1530 .magic
= cpu_to_be32(QCOW_MAGIC
),
1531 .version
= cpu_to_be32(s
->qcow_version
),
1532 .backing_file_offset
= 0,
1533 .backing_file_size
= 0,
1534 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
1535 .size
= cpu_to_be64(total_size
),
1536 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
1537 .l1_size
= cpu_to_be32(s
->l1_size
),
1538 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
1539 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
1540 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
1541 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
1542 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
1544 /* Version 3 fields */
1545 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
1546 .compatible_features
= cpu_to_be64(s
->compatible_features
),
1547 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
1548 .refcount_order
= cpu_to_be32(s
->refcount_order
),
1549 .header_length
= cpu_to_be32(header_length
),
1552 /* For older versions, write a shorter header */
1553 switch (s
->qcow_version
) {
1555 ret
= offsetof(QCowHeader
, incompatible_features
);
1558 ret
= sizeof(*header
);
1567 memset(buf
, 0, buflen
);
1569 /* Preserve any unknown field in the header */
1570 if (s
->unknown_header_fields_size
) {
1571 if (buflen
< s
->unknown_header_fields_size
) {
1576 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
1577 buf
+= s
->unknown_header_fields_size
;
1578 buflen
-= s
->unknown_header_fields_size
;
1581 /* Backing file format header extension */
1582 if (*bs
->backing_format
) {
1583 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
1584 bs
->backing_format
, strlen(bs
->backing_format
),
1595 Qcow2Feature features
[] = {
1597 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1598 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
1599 .name
= "dirty bit",
1602 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1603 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
1604 .name
= "corrupt bit",
1607 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
1608 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
1609 .name
= "lazy refcounts",
1613 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
1614 features
, sizeof(features
), buflen
);
1621 /* Keep unknown header extensions */
1622 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
1623 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
1632 /* End of header extensions */
1633 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
1641 /* Backing file name */
1642 if (*bs
->backing_file
) {
1643 size_t backing_file_len
= strlen(bs
->backing_file
);
1645 if (buflen
< backing_file_len
) {
1650 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1651 strncpy(buf
, bs
->backing_file
, buflen
);
1653 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
1654 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
1657 /* Write the new header */
1658 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
1669 static int qcow2_change_backing_file(BlockDriverState
*bs
,
1670 const char *backing_file
, const char *backing_fmt
)
1672 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
1673 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
1675 return qcow2_update_header(bs
);
1678 static int preallocate(BlockDriverState
*bs
)
1680 uint64_t nb_sectors
;
1682 uint64_t host_offset
= 0;
1687 nb_sectors
= bdrv_nb_sectors(bs
);
1690 while (nb_sectors
) {
1691 num
= MIN(nb_sectors
, INT_MAX
>> BDRV_SECTOR_BITS
);
1692 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &num
,
1693 &host_offset
, &meta
);
1699 QCowL2Meta
*next
= meta
->next
;
1701 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
1703 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
1704 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
1708 /* There are no dependent requests, but we need to remove our
1709 * request from the list of in-flight requests */
1710 QLIST_REMOVE(meta
, next_in_flight
);
1716 /* TODO Preallocate data if requested */
1719 offset
+= num
<< BDRV_SECTOR_BITS
;
1723 * It is expected that the image file is large enough to actually contain
1724 * all of the allocated clusters (otherwise we get failing reads after
1725 * EOF). Extend the image to the last allocated sector.
1727 if (host_offset
!= 0) {
1728 uint8_t buf
[BDRV_SECTOR_SIZE
];
1729 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1730 ret
= bdrv_write(bs
->file
, (host_offset
>> BDRV_SECTOR_BITS
) + num
- 1,
1740 static int qcow2_create2(const char *filename
, int64_t total_size
,
1741 const char *backing_file
, const char *backing_format
,
1742 int flags
, size_t cluster_size
, PreallocMode prealloc
,
1743 QemuOpts
*opts
, int version
,
1746 /* Calculate cluster_bits */
1748 cluster_bits
= ffs(cluster_size
) - 1;
1749 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
1750 (1 << cluster_bits
) != cluster_size
)
1752 error_setg(errp
, "Cluster size must be a power of two between %d and "
1753 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
1758 * Open the image file and write a minimal qcow2 header.
1760 * We keep things simple and start with a zero-sized image. We also
1761 * do without refcount blocks or a L1 table for now. We'll fix the
1762 * inconsistency later.
1764 * We do need a refcount table because growing the refcount table means
1765 * allocating two new refcount blocks - the seconds of which would be at
1766 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1767 * size for any qcow2 image.
1769 BlockDriverState
* bs
;
1771 uint64_t* refcount_table
;
1772 Error
*local_err
= NULL
;
1775 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
1776 int64_t meta_size
= 0;
1777 uint64_t nreftablee
, nrefblocke
, nl1e
, nl2e
;
1778 int64_t aligned_total_size
= align_offset(total_size
, cluster_size
);
1780 /* header: 1 cluster */
1781 meta_size
+= cluster_size
;
1783 /* total size of L2 tables */
1784 nl2e
= aligned_total_size
/ cluster_size
;
1785 nl2e
= align_offset(nl2e
, cluster_size
/ sizeof(uint64_t));
1786 meta_size
+= nl2e
* sizeof(uint64_t);
1788 /* total size of L1 tables */
1789 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
1790 nl1e
= align_offset(nl1e
, cluster_size
/ sizeof(uint64_t));
1791 meta_size
+= nl1e
* sizeof(uint64_t);
1793 /* total size of refcount blocks
1795 * note: every host cluster is reference-counted, including metadata
1796 * (even refcount blocks are recursively included).
1798 * a = total_size (this is the guest disk size)
1799 * m = meta size not including refcount blocks and refcount tables
1801 * y1 = number of refcount blocks entries
1802 * y2 = meta size including everything
1805 * y2 = y1 * sizeof(u16) + y1 * sizeof(u16) * sizeof(u64) / c + m
1807 * y1 = (a + m) / (c - sizeof(u16) - sizeof(u16) * sizeof(u64) / c)
1809 nrefblocke
= (aligned_total_size
+ meta_size
+ cluster_size
) /
1810 (cluster_size
- sizeof(uint16_t) -
1811 1.0 * sizeof(uint16_t) * sizeof(uint64_t) / cluster_size
);
1812 nrefblocke
= align_offset(nrefblocke
, cluster_size
/ sizeof(uint16_t));
1813 meta_size
+= nrefblocke
* sizeof(uint16_t);
1815 /* total size of refcount tables */
1816 nreftablee
= nrefblocke
* sizeof(uint16_t) / cluster_size
;
1817 nreftablee
= align_offset(nreftablee
, cluster_size
/ sizeof(uint64_t));
1818 meta_size
+= nreftablee
* sizeof(uint64_t);
1820 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
1821 aligned_total_size
+ meta_size
);
1822 qemu_opt_set(opts
, BLOCK_OPT_PREALLOC
, PreallocMode_lookup
[prealloc
]);
1825 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1827 error_propagate(errp
, local_err
);
1832 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1835 error_propagate(errp
, local_err
);
1839 /* Write the header */
1840 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
1841 header
= g_malloc0(cluster_size
);
1842 *header
= (QCowHeader
) {
1843 .magic
= cpu_to_be32(QCOW_MAGIC
),
1844 .version
= cpu_to_be32(version
),
1845 .cluster_bits
= cpu_to_be32(cluster_bits
),
1846 .size
= cpu_to_be64(0),
1847 .l1_table_offset
= cpu_to_be64(0),
1848 .l1_size
= cpu_to_be32(0),
1849 .refcount_table_offset
= cpu_to_be64(cluster_size
),
1850 .refcount_table_clusters
= cpu_to_be32(1),
1851 .refcount_order
= cpu_to_be32(3 + REFCOUNT_SHIFT
),
1852 .header_length
= cpu_to_be32(sizeof(*header
)),
1855 if (flags
& BLOCK_FLAG_ENCRYPT
) {
1856 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_AES
);
1858 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
1861 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
1862 header
->compatible_features
|=
1863 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
1866 ret
= bdrv_pwrite(bs
, 0, header
, cluster_size
);
1869 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
1873 /* Write a refcount table with one refcount block */
1874 refcount_table
= g_malloc0(2 * cluster_size
);
1875 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
1876 ret
= bdrv_pwrite(bs
, cluster_size
, refcount_table
, 2 * cluster_size
);
1877 g_free(refcount_table
);
1880 error_setg_errno(errp
, -ret
, "Could not write refcount table");
1888 * And now open the image and make it consistent first (i.e. increase the
1889 * refcount of the cluster that is occupied by the header and the refcount
1892 BlockDriver
* drv
= bdrv_find_format("qcow2");
1893 assert(drv
!= NULL
);
1894 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
,
1895 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_NO_FLUSH
, drv
, &local_err
);
1897 error_propagate(errp
, local_err
);
1901 ret
= qcow2_alloc_clusters(bs
, 3 * cluster_size
);
1903 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
1904 "header and refcount table");
1907 } else if (ret
!= 0) {
1908 error_report("Huh, first cluster in empty image is already in use?");
1912 /* Okay, now that we have a valid image, let's give it the right size */
1913 ret
= bdrv_truncate(bs
, total_size
);
1915 error_setg_errno(errp
, -ret
, "Could not resize image");
1919 /* Want a backing file? There you go.*/
1921 ret
= bdrv_change_backing_file(bs
, backing_file
, backing_format
);
1923 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
1924 "with format '%s'", backing_file
, backing_format
);
1929 /* And if we're supposed to preallocate metadata, do that now */
1930 if (prealloc
!= PREALLOC_MODE_OFF
) {
1931 BDRVQcowState
*s
= bs
->opaque
;
1932 qemu_co_mutex_lock(&s
->lock
);
1933 ret
= preallocate(bs
);
1934 qemu_co_mutex_unlock(&s
->lock
);
1936 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
1944 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1945 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
,
1946 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_NO_BACKING
,
1949 error_propagate(errp
, local_err
);
1961 static int qcow2_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1963 char *backing_file
= NULL
;
1964 char *backing_fmt
= NULL
;
1968 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
1969 PreallocMode prealloc
;
1971 Error
*local_err
= NULL
;
1974 /* Read out options */
1975 size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1977 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1978 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
1979 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ENCRYPT
, false)) {
1980 flags
|= BLOCK_FLAG_ENCRYPT
;
1982 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
1983 DEFAULT_CLUSTER_SIZE
);
1984 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1985 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
1986 PREALLOC_MODE_MAX
, PREALLOC_MODE_OFF
,
1989 error_propagate(errp
, local_err
);
1994 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
1996 /* keep the default */
1997 } else if (!strcmp(buf
, "0.10")) {
1999 } else if (!strcmp(buf
, "1.1")) {
2002 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2007 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_LAZY_REFCOUNTS
, false)) {
2008 flags
|= BLOCK_FLAG_LAZY_REFCOUNTS
;
2011 if (backing_file
&& prealloc
!= PREALLOC_MODE_OFF
) {
2012 error_setg(errp
, "Backing file and preallocation cannot be used at "
2018 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
2019 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2020 "level 1.1 and above (use compat=1.1 or greater)");
2025 ret
= qcow2_create2(filename
, size
, backing_file
, backing_fmt
, flags
,
2026 cluster_size
, prealloc
, opts
, version
, &local_err
);
2028 error_propagate(errp
, local_err
);
2032 g_free(backing_file
);
2033 g_free(backing_fmt
);
2038 static coroutine_fn
int qcow2_co_write_zeroes(BlockDriverState
*bs
,
2039 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
2042 BDRVQcowState
*s
= bs
->opaque
;
2044 /* Emulate misaligned zero writes */
2045 if (sector_num
% s
->cluster_sectors
|| nb_sectors
% s
->cluster_sectors
) {
2049 /* Whatever is left can use real zero clusters */
2050 qemu_co_mutex_lock(&s
->lock
);
2051 ret
= qcow2_zero_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
2053 qemu_co_mutex_unlock(&s
->lock
);
2058 static coroutine_fn
int qcow2_co_discard(BlockDriverState
*bs
,
2059 int64_t sector_num
, int nb_sectors
)
2062 BDRVQcowState
*s
= bs
->opaque
;
2064 qemu_co_mutex_lock(&s
->lock
);
2065 ret
= qcow2_discard_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
2066 nb_sectors
, QCOW2_DISCARD_REQUEST
);
2067 qemu_co_mutex_unlock(&s
->lock
);
2071 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
)
2073 BDRVQcowState
*s
= bs
->opaque
;
2074 int64_t new_l1_size
;
2078 error_report("The new size must be a multiple of 512");
2082 /* cannot proceed if image has snapshots */
2083 if (s
->nb_snapshots
) {
2084 error_report("Can't resize an image which has snapshots");
2088 /* shrinking is currently not supported */
2089 if (offset
< bs
->total_sectors
* 512) {
2090 error_report("qcow2 doesn't support shrinking images yet");
2094 new_l1_size
= size_to_l1(s
, offset
);
2095 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
2100 /* write updated header.size */
2101 offset
= cpu_to_be64(offset
);
2102 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
2103 &offset
, sizeof(uint64_t));
2108 s
->l1_vm_state_index
= new_l1_size
;
2112 /* XXX: put compressed sectors first, then all the cluster aligned
2113 tables to avoid losing bytes in alignment */
2114 static int qcow2_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
2115 const uint8_t *buf
, int nb_sectors
)
2117 BDRVQcowState
*s
= bs
->opaque
;
2121 uint64_t cluster_offset
;
2123 if (nb_sectors
== 0) {
2124 /* align end of file to a sector boundary to ease reading with
2125 sector based I/Os */
2126 cluster_offset
= bdrv_getlength(bs
->file
);
2127 bdrv_truncate(bs
->file
, cluster_offset
);
2131 if (nb_sectors
!= s
->cluster_sectors
) {
2134 /* Zero-pad last write if image size is not cluster aligned */
2135 if (sector_num
+ nb_sectors
== bs
->total_sectors
&&
2136 nb_sectors
< s
->cluster_sectors
) {
2137 uint8_t *pad_buf
= qemu_blockalign(bs
, s
->cluster_size
);
2138 memset(pad_buf
, 0, s
->cluster_size
);
2139 memcpy(pad_buf
, buf
, nb_sectors
* BDRV_SECTOR_SIZE
);
2140 ret
= qcow2_write_compressed(bs
, sector_num
,
2141 pad_buf
, s
->cluster_sectors
);
2142 qemu_vfree(pad_buf
);
2147 out_buf
= g_malloc(s
->cluster_size
+ (s
->cluster_size
/ 1000) + 128);
2149 /* best compression, small window, no zlib header */
2150 memset(&strm
, 0, sizeof(strm
));
2151 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
2153 9, Z_DEFAULT_STRATEGY
);
2159 strm
.avail_in
= s
->cluster_size
;
2160 strm
.next_in
= (uint8_t *)buf
;
2161 strm
.avail_out
= s
->cluster_size
;
2162 strm
.next_out
= out_buf
;
2164 ret
= deflate(&strm
, Z_FINISH
);
2165 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
2170 out_len
= strm
.next_out
- out_buf
;
2174 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
2175 /* could not compress: write normal cluster */
2176 ret
= bdrv_write(bs
, sector_num
, buf
, s
->cluster_sectors
);
2181 cluster_offset
= qcow2_alloc_compressed_cluster_offset(bs
,
2182 sector_num
<< 9, out_len
);
2183 if (!cluster_offset
) {
2187 cluster_offset
&= s
->cluster_offset_mask
;
2189 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
2194 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
2195 ret
= bdrv_pwrite(bs
->file
, cluster_offset
, out_buf
, out_len
);
2207 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
2209 BDRVQcowState
*s
= bs
->opaque
;
2212 qemu_co_mutex_lock(&s
->lock
);
2213 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2215 qemu_co_mutex_unlock(&s
->lock
);
2219 if (qcow2_need_accurate_refcounts(s
)) {
2220 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2222 qemu_co_mutex_unlock(&s
->lock
);
2226 qemu_co_mutex_unlock(&s
->lock
);
2231 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2233 BDRVQcowState
*s
= bs
->opaque
;
2234 bdi
->unallocated_blocks_are_zero
= true;
2235 bdi
->can_write_zeroes_with_unmap
= (s
->qcow_version
>= 3);
2236 bdi
->cluster_size
= s
->cluster_size
;
2237 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
2241 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
2243 BDRVQcowState
*s
= bs
->opaque
;
2244 ImageInfoSpecific
*spec_info
= g_new(ImageInfoSpecific
, 1);
2246 *spec_info
= (ImageInfoSpecific
){
2247 .kind
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
2249 .qcow2
= g_new(ImageInfoSpecificQCow2
, 1),
2252 if (s
->qcow_version
== 2) {
2253 *spec_info
->qcow2
= (ImageInfoSpecificQCow2
){
2254 .compat
= g_strdup("0.10"),
2256 } else if (s
->qcow_version
== 3) {
2257 *spec_info
->qcow2
= (ImageInfoSpecificQCow2
){
2258 .compat
= g_strdup("1.1"),
2259 .lazy_refcounts
= s
->compatible_features
&
2260 QCOW2_COMPAT_LAZY_REFCOUNTS
,
2261 .has_lazy_refcounts
= true,
2269 static void dump_refcounts(BlockDriverState
*bs
)
2271 BDRVQcowState
*s
= bs
->opaque
;
2272 int64_t nb_clusters
, k
, k1
, size
;
2275 size
= bdrv_getlength(bs
->file
);
2276 nb_clusters
= size_to_clusters(s
, size
);
2277 for(k
= 0; k
< nb_clusters
;) {
2279 refcount
= get_refcount(bs
, k
);
2281 while (k
< nb_clusters
&& get_refcount(bs
, k
) == refcount
)
2283 printf("%" PRId64
": refcount=%d nb=%" PRId64
"\n", k
, refcount
,
2289 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
2292 BDRVQcowState
*s
= bs
->opaque
;
2293 int64_t total_sectors
= bs
->total_sectors
;
2294 int growable
= bs
->growable
;
2295 bool zero_beyond_eof
= bs
->zero_beyond_eof
;
2298 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
2300 bs
->zero_beyond_eof
= false;
2301 ret
= bdrv_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
, qiov
);
2302 bs
->growable
= growable
;
2303 bs
->zero_beyond_eof
= zero_beyond_eof
;
2305 /* bdrv_co_do_writev will have increased the total_sectors value to include
2306 * the VM state - the VM state is however not an actual part of the block
2307 * device, therefore, we need to restore the old value. */
2308 bs
->total_sectors
= total_sectors
;
2313 static int qcow2_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2314 int64_t pos
, int size
)
2316 BDRVQcowState
*s
= bs
->opaque
;
2317 int growable
= bs
->growable
;
2318 bool zero_beyond_eof
= bs
->zero_beyond_eof
;
2321 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
2323 bs
->zero_beyond_eof
= false;
2324 ret
= bdrv_pread(bs
, qcow2_vm_state_offset(s
) + pos
, buf
, size
);
2325 bs
->growable
= growable
;
2326 bs
->zero_beyond_eof
= zero_beyond_eof
;
2332 * Downgrades an image's version. To achieve this, any incompatible features
2333 * have to be removed.
2335 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
)
2337 BDRVQcowState
*s
= bs
->opaque
;
2338 int current_version
= s
->qcow_version
;
2341 if (target_version
== current_version
) {
2343 } else if (target_version
> current_version
) {
2345 } else if (target_version
!= 2) {
2349 if (s
->refcount_order
!= 4) {
2350 /* we would have to convert the image to a refcount_order == 4 image
2351 * here; however, since qemu (at the time of writing this) does not
2352 * support anything different than 4 anyway, there is no point in doing
2353 * so right now; however, we should error out (if qemu supports this in
2354 * the future and this code has not been adapted) */
2355 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2356 "currently not supported.");
2360 /* clear incompatible features */
2361 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
2362 ret
= qcow2_mark_clean(bs
);
2368 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2369 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2370 * best thing to do anyway */
2372 if (s
->incompatible_features
) {
2376 /* since we can ignore compatible features, we can set them to 0 as well */
2377 s
->compatible_features
= 0;
2378 /* if lazy refcounts have been used, they have already been fixed through
2379 * clearing the dirty flag */
2381 /* clearing autoclear features is trivial */
2382 s
->autoclear_features
= 0;
2384 ret
= qcow2_expand_zero_clusters(bs
);
2389 s
->qcow_version
= target_version
;
2390 ret
= qcow2_update_header(bs
);
2392 s
->qcow_version
= current_version
;
2398 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
)
2400 BDRVQcowState
*s
= bs
->opaque
;
2401 int old_version
= s
->qcow_version
, new_version
= old_version
;
2402 uint64_t new_size
= 0;
2403 const char *backing_file
= NULL
, *backing_format
= NULL
;
2404 bool lazy_refcounts
= s
->use_lazy_refcounts
;
2405 const char *compat
= NULL
;
2406 uint64_t cluster_size
= s
->cluster_size
;
2409 QemuOptDesc
*desc
= opts
->list
->desc
;
2411 while (desc
&& desc
->name
) {
2412 if (!qemu_opt_find(opts
, desc
->name
)) {
2413 /* only change explicitly defined options */
2418 if (!strcmp(desc
->name
, "compat")) {
2419 compat
= qemu_opt_get(opts
, "compat");
2421 /* preserve default */
2422 } else if (!strcmp(compat
, "0.10")) {
2424 } else if (!strcmp(compat
, "1.1")) {
2427 fprintf(stderr
, "Unknown compatibility level %s.\n", compat
);
2430 } else if (!strcmp(desc
->name
, "preallocation")) {
2431 fprintf(stderr
, "Cannot change preallocation mode.\n");
2433 } else if (!strcmp(desc
->name
, "size")) {
2434 new_size
= qemu_opt_get_size(opts
, "size", 0);
2435 } else if (!strcmp(desc
->name
, "backing_file")) {
2436 backing_file
= qemu_opt_get(opts
, "backing_file");
2437 } else if (!strcmp(desc
->name
, "backing_fmt")) {
2438 backing_format
= qemu_opt_get(opts
, "backing_fmt");
2439 } else if (!strcmp(desc
->name
, "encryption")) {
2440 encrypt
= qemu_opt_get_bool(opts
, "encryption", s
->crypt_method
);
2441 if (encrypt
!= !!s
->crypt_method
) {
2442 fprintf(stderr
, "Changing the encryption flag is not "
2446 } else if (!strcmp(desc
->name
, "cluster_size")) {
2447 cluster_size
= qemu_opt_get_size(opts
, "cluster_size",
2449 if (cluster_size
!= s
->cluster_size
) {
2450 fprintf(stderr
, "Changing the cluster size is not "
2454 } else if (!strcmp(desc
->name
, "lazy_refcounts")) {
2455 lazy_refcounts
= qemu_opt_get_bool(opts
, "lazy_refcounts",
2458 /* if this assertion fails, this probably means a new option was
2459 * added without having it covered here */
2466 if (new_version
!= old_version
) {
2467 if (new_version
> old_version
) {
2469 s
->qcow_version
= new_version
;
2470 ret
= qcow2_update_header(bs
);
2472 s
->qcow_version
= old_version
;
2476 ret
= qcow2_downgrade(bs
, new_version
);
2483 if (backing_file
|| backing_format
) {
2484 ret
= qcow2_change_backing_file(bs
, backing_file
?: bs
->backing_file
,
2485 backing_format
?: bs
->backing_format
);
2491 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
2492 if (lazy_refcounts
) {
2493 if (s
->qcow_version
< 3) {
2494 fprintf(stderr
, "Lazy refcounts only supported with compatibility "
2495 "level 1.1 and above (use compat=1.1 or greater)\n");
2498 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2499 ret
= qcow2_update_header(bs
);
2501 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2504 s
->use_lazy_refcounts
= true;
2506 /* make image clean first */
2507 ret
= qcow2_mark_clean(bs
);
2511 /* now disallow lazy refcounts */
2512 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2513 ret
= qcow2_update_header(bs
);
2515 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2518 s
->use_lazy_refcounts
= false;
2523 ret
= bdrv_truncate(bs
, new_size
);
2532 static QemuOptsList qcow2_create_opts
= {
2533 .name
= "qcow2-create-opts",
2534 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
2537 .name
= BLOCK_OPT_SIZE
,
2538 .type
= QEMU_OPT_SIZE
,
2539 .help
= "Virtual disk size"
2542 .name
= BLOCK_OPT_COMPAT_LEVEL
,
2543 .type
= QEMU_OPT_STRING
,
2544 .help
= "Compatibility level (0.10 or 1.1)"
2547 .name
= BLOCK_OPT_BACKING_FILE
,
2548 .type
= QEMU_OPT_STRING
,
2549 .help
= "File name of a base image"
2552 .name
= BLOCK_OPT_BACKING_FMT
,
2553 .type
= QEMU_OPT_STRING
,
2554 .help
= "Image format of the base image"
2557 .name
= BLOCK_OPT_ENCRYPT
,
2558 .type
= QEMU_OPT_BOOL
,
2559 .help
= "Encrypt the image",
2560 .def_value_str
= "off"
2563 .name
= BLOCK_OPT_CLUSTER_SIZE
,
2564 .type
= QEMU_OPT_SIZE
,
2565 .help
= "qcow2 cluster size",
2566 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
2569 .name
= BLOCK_OPT_PREALLOC
,
2570 .type
= QEMU_OPT_STRING
,
2571 .help
= "Preallocation mode (allowed values: off, metadata, "
2575 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
2576 .type
= QEMU_OPT_BOOL
,
2577 .help
= "Postpone refcount updates",
2578 .def_value_str
= "off"
2580 { /* end of list */ }
2584 static BlockDriver bdrv_qcow2
= {
2585 .format_name
= "qcow2",
2586 .instance_size
= sizeof(BDRVQcowState
),
2587 .bdrv_probe
= qcow2_probe
,
2588 .bdrv_open
= qcow2_open
,
2589 .bdrv_close
= qcow2_close
,
2590 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
2591 .bdrv_create
= qcow2_create
,
2592 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
2593 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
2594 .bdrv_set_key
= qcow2_set_key
,
2596 .bdrv_co_readv
= qcow2_co_readv
,
2597 .bdrv_co_writev
= qcow2_co_writev
,
2598 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
2600 .bdrv_co_write_zeroes
= qcow2_co_write_zeroes
,
2601 .bdrv_co_discard
= qcow2_co_discard
,
2602 .bdrv_truncate
= qcow2_truncate
,
2603 .bdrv_write_compressed
= qcow2_write_compressed
,
2605 .bdrv_snapshot_create
= qcow2_snapshot_create
,
2606 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
2607 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
2608 .bdrv_snapshot_list
= qcow2_snapshot_list
,
2609 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
2610 .bdrv_get_info
= qcow2_get_info
,
2611 .bdrv_get_specific_info
= qcow2_get_specific_info
,
2613 .bdrv_save_vmstate
= qcow2_save_vmstate
,
2614 .bdrv_load_vmstate
= qcow2_load_vmstate
,
2616 .supports_backing
= true,
2617 .bdrv_change_backing_file
= qcow2_change_backing_file
,
2619 .bdrv_refresh_limits
= qcow2_refresh_limits
,
2620 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
2622 .create_opts
= &qcow2_create_opts
,
2623 .bdrv_check
= qcow2_check
,
2624 .bdrv_amend_options
= qcow2_amend_options
,
2627 static void bdrv_qcow2_init(void)
2629 bdrv_register(&bdrv_qcow2
);
2632 block_init(bdrv_qcow2_init
);