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"
34 #include "qemu/option_int.h"
37 Differences with QCOW:
39 - Support for multiple incremental snapshots.
40 - Memory management by reference counts.
41 - Clusters which have a reference count of one have the bit
42 QCOW_OFLAG_COPIED to optimize write performance.
43 - Size of compressed clusters is stored in sectors to reduce bit usage
44 in the cluster offsets.
45 - Support for storing additional data (such as the VM state) in the
47 - If a backing store is used, the cluster size is not constrained
48 (could be backported to QCOW).
49 - L2 tables have always a size of one cluster.
56 } QEMU_PACKED QCowExtension
;
58 #define QCOW2_EXT_MAGIC_END 0
59 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
60 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
62 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
64 const QCowHeader
*cow_header
= (const void *)buf
;
66 if (buf_size
>= sizeof(QCowHeader
) &&
67 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
68 be32_to_cpu(cow_header
->version
) >= 2)
76 * read qcow2 extension and fill bs
77 * start reading from start_offset
78 * finish reading upon magic of value 0 or when end_offset reached
79 * unknown magic is skipped (future extension this version knows nothing about)
80 * return 0 upon success, non-0 otherwise
82 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
83 uint64_t end_offset
, void **p_feature_table
,
86 BDRVQcowState
*s
= bs
->opaque
;
92 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
94 offset
= start_offset
;
95 while (offset
< end_offset
) {
99 if (offset
> s
->cluster_size
)
100 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
102 printf("attempting to read extended header in offset %lu\n", offset
);
105 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
107 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
108 "pread fail from offset %" PRIu64
, offset
);
111 be32_to_cpus(&ext
.magic
);
112 be32_to_cpus(&ext
.len
);
113 offset
+= sizeof(ext
);
115 printf("ext.magic = 0x%x\n", ext
.magic
);
117 if (ext
.len
> end_offset
- offset
) {
118 error_setg(errp
, "Header extension too large");
123 case QCOW2_EXT_MAGIC_END
:
126 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
127 if (ext
.len
>= sizeof(bs
->backing_format
)) {
128 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
129 " too large (>=%zu)", ext
.len
,
130 sizeof(bs
->backing_format
));
133 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
135 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
136 "Could not read format name");
139 bs
->backing_format
[ext
.len
] = '\0';
141 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
145 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
146 if (p_feature_table
!= NULL
) {
147 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
148 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
150 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
151 "Could not read table");
155 *p_feature_table
= feature_table
;
160 /* unknown magic - save it in case we need to rewrite the header */
162 Qcow2UnknownHeaderExtension
*uext
;
164 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
165 uext
->magic
= ext
.magic
;
167 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
169 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
171 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
172 "Could not read data");
179 offset
+= ((ext
.len
+ 7) & ~7);
185 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
187 BDRVQcowState
*s
= bs
->opaque
;
188 Qcow2UnknownHeaderExtension
*uext
, *next
;
190 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
191 QLIST_REMOVE(uext
, next
);
196 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState
*bs
,
197 Error
**errp
, const char *fmt
, ...)
203 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
206 error_set(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
, bs
->device_name
, "qcow2",
210 static void report_unsupported_feature(BlockDriverState
*bs
,
211 Error
**errp
, Qcow2Feature
*table
, uint64_t mask
)
213 char *features
= g_strdup("");
216 while (table
&& table
->name
[0] != '\0') {
217 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
218 if (mask
& (1ULL << table
->bit
)) {
220 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
223 mask
&= ~(1ULL << table
->bit
);
231 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
232 old
, *old
? ", " : "", mask
);
236 report_unsupported(bs
, errp
, "%s", features
);
241 * Sets the dirty bit and flushes afterwards if necessary.
243 * The incompatible_features bit is only set if the image file header was
244 * updated successfully. Therefore it is not required to check the return
245 * value of this function.
247 int qcow2_mark_dirty(BlockDriverState
*bs
)
249 BDRVQcowState
*s
= bs
->opaque
;
253 assert(s
->qcow_version
>= 3);
255 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
256 return 0; /* already dirty */
259 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
260 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
265 ret
= bdrv_flush(bs
->file
);
270 /* Only treat image as dirty if the header was updated successfully */
271 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
276 * Clears the dirty bit and flushes before if necessary. Only call this
277 * function when there are no pending requests, it does not guard against
278 * concurrent requests dirtying the image.
280 static int qcow2_mark_clean(BlockDriverState
*bs
)
282 BDRVQcowState
*s
= bs
->opaque
;
284 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
287 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
289 ret
= bdrv_flush(bs
);
294 return qcow2_update_header(bs
);
300 * Marks the image as corrupt.
302 int qcow2_mark_corrupt(BlockDriverState
*bs
)
304 BDRVQcowState
*s
= bs
->opaque
;
306 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
307 return qcow2_update_header(bs
);
311 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
312 * before if necessary.
314 int qcow2_mark_consistent(BlockDriverState
*bs
)
316 BDRVQcowState
*s
= bs
->opaque
;
318 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
319 int ret
= bdrv_flush(bs
);
324 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
325 return qcow2_update_header(bs
);
330 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
333 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
338 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
339 ret
= qcow2_mark_clean(bs
);
343 return qcow2_mark_consistent(bs
);
348 static int validate_table_offset(BlockDriverState
*bs
, uint64_t offset
,
349 uint64_t entries
, size_t entry_len
)
351 BDRVQcowState
*s
= bs
->opaque
;
354 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
355 * because values will be passed to qemu functions taking int64_t. */
356 if (entries
> INT64_MAX
/ entry_len
) {
360 size
= entries
* entry_len
;
362 if (INT64_MAX
- size
< offset
) {
366 /* Tables must be cluster aligned */
367 if (offset
& (s
->cluster_size
- 1)) {
374 static QemuOptsList qcow2_runtime_opts
= {
376 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
379 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
380 .type
= QEMU_OPT_BOOL
,
381 .help
= "Postpone refcount updates",
384 .name
= QCOW2_OPT_DISCARD_REQUEST
,
385 .type
= QEMU_OPT_BOOL
,
386 .help
= "Pass guest discard requests to the layer below",
389 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
390 .type
= QEMU_OPT_BOOL
,
391 .help
= "Generate discard requests when snapshot related space "
395 .name
= QCOW2_OPT_DISCARD_OTHER
,
396 .type
= QEMU_OPT_BOOL
,
397 .help
= "Generate discard requests when other clusters are freed",
400 .name
= QCOW2_OPT_OVERLAP
,
401 .type
= QEMU_OPT_STRING
,
402 .help
= "Selects which overlap checks to perform from a range of "
403 "templates (none, constant, cached, all)",
406 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
407 .type
= QEMU_OPT_BOOL
,
408 .help
= "Check for unintended writes into the main qcow2 header",
411 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
412 .type
= QEMU_OPT_BOOL
,
413 .help
= "Check for unintended writes into the active L1 table",
416 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
417 .type
= QEMU_OPT_BOOL
,
418 .help
= "Check for unintended writes into an active L2 table",
421 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
422 .type
= QEMU_OPT_BOOL
,
423 .help
= "Check for unintended writes into the refcount table",
426 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
427 .type
= QEMU_OPT_BOOL
,
428 .help
= "Check for unintended writes into a refcount block",
431 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
432 .type
= QEMU_OPT_BOOL
,
433 .help
= "Check for unintended writes into the snapshot table",
436 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
437 .type
= QEMU_OPT_BOOL
,
438 .help
= "Check for unintended writes into an inactive L1 table",
441 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
442 .type
= QEMU_OPT_BOOL
,
443 .help
= "Check for unintended writes into an inactive L2 table",
445 { /* end of list */ }
449 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
450 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
451 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
452 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
453 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
454 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
455 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
456 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
457 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
460 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
463 BDRVQcowState
*s
= bs
->opaque
;
468 Error
*local_err
= NULL
;
470 uint64_t l1_vm_state_index
;
471 const char *opt_overlap_check
;
472 int overlap_check_template
= 0;
474 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
476 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
479 be32_to_cpus(&header
.magic
);
480 be32_to_cpus(&header
.version
);
481 be64_to_cpus(&header
.backing_file_offset
);
482 be32_to_cpus(&header
.backing_file_size
);
483 be64_to_cpus(&header
.size
);
484 be32_to_cpus(&header
.cluster_bits
);
485 be32_to_cpus(&header
.crypt_method
);
486 be64_to_cpus(&header
.l1_table_offset
);
487 be32_to_cpus(&header
.l1_size
);
488 be64_to_cpus(&header
.refcount_table_offset
);
489 be32_to_cpus(&header
.refcount_table_clusters
);
490 be64_to_cpus(&header
.snapshots_offset
);
491 be32_to_cpus(&header
.nb_snapshots
);
493 if (header
.magic
!= QCOW_MAGIC
) {
494 error_setg(errp
, "Image is not in qcow2 format");
498 if (header
.version
< 2 || header
.version
> 3) {
499 report_unsupported(bs
, errp
, "QCOW version %" PRIu32
, header
.version
);
504 s
->qcow_version
= header
.version
;
506 /* Initialise cluster size */
507 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
508 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
509 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
510 header
.cluster_bits
);
515 s
->cluster_bits
= header
.cluster_bits
;
516 s
->cluster_size
= 1 << s
->cluster_bits
;
517 s
->cluster_sectors
= 1 << (s
->cluster_bits
- 9);
519 /* Initialise version 3 header fields */
520 if (header
.version
== 2) {
521 header
.incompatible_features
= 0;
522 header
.compatible_features
= 0;
523 header
.autoclear_features
= 0;
524 header
.refcount_order
= 4;
525 header
.header_length
= 72;
527 be64_to_cpus(&header
.incompatible_features
);
528 be64_to_cpus(&header
.compatible_features
);
529 be64_to_cpus(&header
.autoclear_features
);
530 be32_to_cpus(&header
.refcount_order
);
531 be32_to_cpus(&header
.header_length
);
533 if (header
.header_length
< 104) {
534 error_setg(errp
, "qcow2 header too short");
540 if (header
.header_length
> s
->cluster_size
) {
541 error_setg(errp
, "qcow2 header exceeds cluster size");
546 if (header
.header_length
> sizeof(header
)) {
547 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
548 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
549 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
550 s
->unknown_header_fields_size
);
552 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
558 if (header
.backing_file_offset
> s
->cluster_size
) {
559 error_setg(errp
, "Invalid backing file offset");
564 if (header
.backing_file_offset
) {
565 ext_end
= header
.backing_file_offset
;
567 ext_end
= 1 << header
.cluster_bits
;
570 /* Handle feature bits */
571 s
->incompatible_features
= header
.incompatible_features
;
572 s
->compatible_features
= header
.compatible_features
;
573 s
->autoclear_features
= header
.autoclear_features
;
575 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
576 void *feature_table
= NULL
;
577 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
578 &feature_table
, NULL
);
579 report_unsupported_feature(bs
, errp
, feature_table
,
580 s
->incompatible_features
&
581 ~QCOW2_INCOMPAT_MASK
);
583 g_free(feature_table
);
587 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
588 /* Corrupt images may not be written to unless they are being repaired
590 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
591 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
598 /* Check support for various header values */
599 if (header
.refcount_order
!= 4) {
600 report_unsupported(bs
, errp
, "%d bit reference counts",
601 1 << header
.refcount_order
);
605 s
->refcount_order
= header
.refcount_order
;
607 if (header
.crypt_method
> QCOW_CRYPT_AES
) {
608 error_setg(errp
, "Unsupported encryption method: %" PRIu32
,
609 header
.crypt_method
);
613 s
->crypt_method_header
= header
.crypt_method
;
614 if (s
->crypt_method_header
) {
618 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
619 s
->l2_size
= 1 << s
->l2_bits
;
620 bs
->total_sectors
= header
.size
/ 512;
621 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
622 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
623 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
625 s
->refcount_table_offset
= header
.refcount_table_offset
;
626 s
->refcount_table_size
=
627 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
629 if (header
.refcount_table_clusters
> qcow2_max_refcount_clusters(s
)) {
630 error_setg(errp
, "Reference count table too large");
635 ret
= validate_table_offset(bs
, s
->refcount_table_offset
,
636 s
->refcount_table_size
, sizeof(uint64_t));
638 error_setg(errp
, "Invalid reference count table offset");
642 /* Snapshot table offset/length */
643 if (header
.nb_snapshots
> QCOW_MAX_SNAPSHOTS
) {
644 error_setg(errp
, "Too many snapshots");
649 ret
= validate_table_offset(bs
, header
.snapshots_offset
,
651 sizeof(QCowSnapshotHeader
));
653 error_setg(errp
, "Invalid snapshot table offset");
657 /* read the level 1 table */
658 if (header
.l1_size
> QCOW_MAX_L1_SIZE
) {
659 error_setg(errp
, "Active L1 table too large");
663 s
->l1_size
= header
.l1_size
;
665 l1_vm_state_index
= size_to_l1(s
, header
.size
);
666 if (l1_vm_state_index
> INT_MAX
) {
667 error_setg(errp
, "Image is too big");
671 s
->l1_vm_state_index
= l1_vm_state_index
;
673 /* the L1 table must contain at least enough entries to put
675 if (s
->l1_size
< s
->l1_vm_state_index
) {
676 error_setg(errp
, "L1 table is too small");
681 ret
= validate_table_offset(bs
, header
.l1_table_offset
,
682 header
.l1_size
, sizeof(uint64_t));
684 error_setg(errp
, "Invalid L1 table offset");
687 s
->l1_table_offset
= header
.l1_table_offset
;
690 if (s
->l1_size
> 0) {
691 s
->l1_table
= g_malloc0(
692 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
693 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
694 s
->l1_size
* sizeof(uint64_t));
696 error_setg_errno(errp
, -ret
, "Could not read L1 table");
699 for(i
= 0;i
< s
->l1_size
; i
++) {
700 be64_to_cpus(&s
->l1_table
[i
]);
704 /* alloc L2 table/refcount block cache */
705 s
->l2_table_cache
= qcow2_cache_create(bs
, L2_CACHE_SIZE
);
706 s
->refcount_block_cache
= qcow2_cache_create(bs
, REFCOUNT_CACHE_SIZE
);
708 s
->cluster_cache
= g_malloc(s
->cluster_size
);
709 /* one more sector for decompressed data alignment */
710 s
->cluster_data
= qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
712 s
->cluster_cache_offset
= -1;
715 ret
= qcow2_refcount_init(bs
);
717 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
721 QLIST_INIT(&s
->cluster_allocs
);
722 QTAILQ_INIT(&s
->discards
);
724 /* read qcow2 extensions */
725 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
727 error_propagate(errp
, local_err
);
732 /* read the backing file name */
733 if (header
.backing_file_offset
!= 0) {
734 len
= header
.backing_file_size
;
735 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
)) {
736 error_setg(errp
, "Backing file name too long");
740 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
741 bs
->backing_file
, len
);
743 error_setg_errno(errp
, -ret
, "Could not read backing file name");
746 bs
->backing_file
[len
] = '\0';
749 /* Internal snapshots */
750 s
->snapshots_offset
= header
.snapshots_offset
;
751 s
->nb_snapshots
= header
.nb_snapshots
;
753 ret
= qcow2_read_snapshots(bs
);
755 error_setg_errno(errp
, -ret
, "Could not read snapshots");
759 /* Clear unknown autoclear feature bits */
760 if (!bs
->read_only
&& !(flags
& BDRV_O_INCOMING
) && s
->autoclear_features
) {
761 s
->autoclear_features
= 0;
762 ret
= qcow2_update_header(bs
);
764 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
769 /* Initialise locks */
770 qemu_co_mutex_init(&s
->lock
);
772 /* Repair image if dirty */
773 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INCOMING
)) && !bs
->read_only
&&
774 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
775 BdrvCheckResult result
= {0};
777 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
);
779 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
784 /* Enable lazy_refcounts according to image and command line options */
785 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
786 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
788 error_propagate(errp
, local_err
);
793 s
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
794 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
796 s
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
797 s
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
798 s
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
799 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
800 flags
& BDRV_O_UNMAP
);
801 s
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
802 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
803 s
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
804 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
806 opt_overlap_check
= qemu_opt_get(opts
, "overlap-check") ?: "cached";
807 if (!strcmp(opt_overlap_check
, "none")) {
808 overlap_check_template
= 0;
809 } else if (!strcmp(opt_overlap_check
, "constant")) {
810 overlap_check_template
= QCOW2_OL_CONSTANT
;
811 } else if (!strcmp(opt_overlap_check
, "cached")) {
812 overlap_check_template
= QCOW2_OL_CACHED
;
813 } else if (!strcmp(opt_overlap_check
, "all")) {
814 overlap_check_template
= QCOW2_OL_ALL
;
816 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
817 "'overlap-check'. Allowed are either of the following: "
818 "none, constant, cached, all", opt_overlap_check
);
824 s
->overlap_check
= 0;
825 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
826 /* overlap-check defines a template bitmask, but every flag may be
827 * overwritten through the associated boolean option */
829 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
830 overlap_check_template
& (1 << i
)) << i
;
835 if (s
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
836 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
837 "qemu 1.1 compatibility level");
844 BdrvCheckResult result
= {0};
845 qcow2_check_refcounts(bs
, &result
, 0);
851 g_free(s
->unknown_header_fields
);
852 cleanup_unknown_header_ext(bs
);
853 qcow2_free_snapshots(bs
);
854 qcow2_refcount_close(bs
);
856 /* else pre-write overlap checks in cache_destroy may crash */
858 if (s
->l2_table_cache
) {
859 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
861 if (s
->refcount_block_cache
) {
862 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
864 g_free(s
->cluster_cache
);
865 qemu_vfree(s
->cluster_data
);
869 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
871 BDRVQcowState
*s
= bs
->opaque
;
873 bs
->bl
.write_zeroes_alignment
= s
->cluster_sectors
;
876 static int qcow2_set_key(BlockDriverState
*bs
, const char *key
)
878 BDRVQcowState
*s
= bs
->opaque
;
882 memset(keybuf
, 0, 16);
886 /* XXX: we could compress the chars to 7 bits to increase
888 for(i
= 0;i
< len
;i
++) {
891 s
->crypt_method
= s
->crypt_method_header
;
893 if (AES_set_encrypt_key(keybuf
, 128, &s
->aes_encrypt_key
) != 0)
895 if (AES_set_decrypt_key(keybuf
, 128, &s
->aes_decrypt_key
) != 0)
905 AES_encrypt(in
, tmp
, &s
->aes_encrypt_key
);
906 AES_decrypt(tmp
, out
, &s
->aes_decrypt_key
);
907 for(i
= 0; i
< 16; i
++)
908 printf(" %02x", tmp
[i
]);
910 for(i
= 0; i
< 16; i
++)
911 printf(" %02x", out
[i
]);
918 /* We have no actual commit/abort logic for qcow2, but we need to write out any
919 * unwritten data if we reopen read-only. */
920 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
921 BlockReopenQueue
*queue
, Error
**errp
)
925 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
926 ret
= bdrv_flush(state
->bs
);
931 ret
= qcow2_mark_clean(state
->bs
);
940 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
941 int64_t sector_num
, int nb_sectors
, int *pnum
)
943 BDRVQcowState
*s
= bs
->opaque
;
944 uint64_t cluster_offset
;
945 int index_in_cluster
, ret
;
949 qemu_co_mutex_lock(&s
->lock
);
950 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9, pnum
, &cluster_offset
);
951 qemu_co_mutex_unlock(&s
->lock
);
956 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
958 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
959 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
960 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
962 if (ret
== QCOW2_CLUSTER_ZERO
) {
963 status
|= BDRV_BLOCK_ZERO
;
964 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
965 status
|= BDRV_BLOCK_DATA
;
970 /* handle reading after the end of the backing file */
971 int qcow2_backing_read1(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
972 int64_t sector_num
, int nb_sectors
)
975 if ((sector_num
+ nb_sectors
) <= bs
->total_sectors
)
977 if (sector_num
>= bs
->total_sectors
)
980 n1
= bs
->total_sectors
- sector_num
;
982 qemu_iovec_memset(qiov
, 512 * n1
, 0, 512 * (nb_sectors
- n1
));
987 static coroutine_fn
int qcow2_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
988 int remaining_sectors
, QEMUIOVector
*qiov
)
990 BDRVQcowState
*s
= bs
->opaque
;
991 int index_in_cluster
, n1
;
993 int cur_nr_sectors
; /* number of sectors in current iteration */
994 uint64_t cluster_offset
= 0;
995 uint64_t bytes_done
= 0;
996 QEMUIOVector hd_qiov
;
997 uint8_t *cluster_data
= NULL
;
999 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1001 qemu_co_mutex_lock(&s
->lock
);
1003 while (remaining_sectors
!= 0) {
1005 /* prepare next request */
1006 cur_nr_sectors
= remaining_sectors
;
1007 if (s
->crypt_method
) {
1008 cur_nr_sectors
= MIN(cur_nr_sectors
,
1009 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
1012 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9,
1013 &cur_nr_sectors
, &cluster_offset
);
1018 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1020 qemu_iovec_reset(&hd_qiov
);
1021 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
1022 cur_nr_sectors
* 512);
1025 case QCOW2_CLUSTER_UNALLOCATED
:
1027 if (bs
->backing_hd
) {
1028 /* read from the base image */
1029 n1
= qcow2_backing_read1(bs
->backing_hd
, &hd_qiov
,
1030 sector_num
, cur_nr_sectors
);
1032 QEMUIOVector local_qiov
;
1034 qemu_iovec_init(&local_qiov
, hd_qiov
.niov
);
1035 qemu_iovec_concat(&local_qiov
, &hd_qiov
, 0,
1036 n1
* BDRV_SECTOR_SIZE
);
1038 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1039 qemu_co_mutex_unlock(&s
->lock
);
1040 ret
= bdrv_co_readv(bs
->backing_hd
, sector_num
,
1042 qemu_co_mutex_lock(&s
->lock
);
1044 qemu_iovec_destroy(&local_qiov
);
1051 /* Note: in this case, no need to wait */
1052 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
1056 case QCOW2_CLUSTER_ZERO
:
1057 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
1060 case QCOW2_CLUSTER_COMPRESSED
:
1061 /* add AIO support for compressed blocks ? */
1062 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1067 qemu_iovec_from_buf(&hd_qiov
, 0,
1068 s
->cluster_cache
+ index_in_cluster
* 512,
1069 512 * cur_nr_sectors
);
1072 case QCOW2_CLUSTER_NORMAL
:
1073 if ((cluster_offset
& 511) != 0) {
1078 if (s
->crypt_method
) {
1080 * For encrypted images, read everything into a temporary
1081 * contiguous buffer on which the AES functions can work.
1083 if (!cluster_data
) {
1085 qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1088 assert(cur_nr_sectors
<=
1089 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
1090 qemu_iovec_reset(&hd_qiov
);
1091 qemu_iovec_add(&hd_qiov
, cluster_data
,
1092 512 * cur_nr_sectors
);
1095 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1096 qemu_co_mutex_unlock(&s
->lock
);
1097 ret
= bdrv_co_readv(bs
->file
,
1098 (cluster_offset
>> 9) + index_in_cluster
,
1099 cur_nr_sectors
, &hd_qiov
);
1100 qemu_co_mutex_lock(&s
->lock
);
1104 if (s
->crypt_method
) {
1105 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
1106 cluster_data
, cur_nr_sectors
, 0, &s
->aes_decrypt_key
);
1107 qemu_iovec_from_buf(qiov
, bytes_done
,
1108 cluster_data
, 512 * cur_nr_sectors
);
1113 g_assert_not_reached();
1118 remaining_sectors
-= cur_nr_sectors
;
1119 sector_num
+= cur_nr_sectors
;
1120 bytes_done
+= cur_nr_sectors
* 512;
1125 qemu_co_mutex_unlock(&s
->lock
);
1127 qemu_iovec_destroy(&hd_qiov
);
1128 qemu_vfree(cluster_data
);
1133 static coroutine_fn
int qcow2_co_writev(BlockDriverState
*bs
,
1135 int remaining_sectors
,
1138 BDRVQcowState
*s
= bs
->opaque
;
1139 int index_in_cluster
;
1141 int cur_nr_sectors
; /* number of sectors in current iteration */
1142 uint64_t cluster_offset
;
1143 QEMUIOVector hd_qiov
;
1144 uint64_t bytes_done
= 0;
1145 uint8_t *cluster_data
= NULL
;
1146 QCowL2Meta
*l2meta
= NULL
;
1148 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num
,
1151 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1153 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1155 qemu_co_mutex_lock(&s
->lock
);
1157 while (remaining_sectors
!= 0) {
1161 trace_qcow2_writev_start_part(qemu_coroutine_self());
1162 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1163 cur_nr_sectors
= remaining_sectors
;
1164 if (s
->crypt_method
&&
1166 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
- index_in_cluster
) {
1168 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
- index_in_cluster
;
1171 ret
= qcow2_alloc_cluster_offset(bs
, sector_num
<< 9,
1172 &cur_nr_sectors
, &cluster_offset
, &l2meta
);
1177 assert((cluster_offset
& 511) == 0);
1179 qemu_iovec_reset(&hd_qiov
);
1180 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
1181 cur_nr_sectors
* 512);
1183 if (s
->crypt_method
) {
1184 if (!cluster_data
) {
1185 cluster_data
= qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
*
1189 assert(hd_qiov
.size
<=
1190 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1191 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
1193 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
1194 cluster_data
, cur_nr_sectors
, 1, &s
->aes_encrypt_key
);
1196 qemu_iovec_reset(&hd_qiov
);
1197 qemu_iovec_add(&hd_qiov
, cluster_data
,
1198 cur_nr_sectors
* 512);
1201 ret
= qcow2_pre_write_overlap_check(bs
, 0,
1202 cluster_offset
+ index_in_cluster
* BDRV_SECTOR_SIZE
,
1203 cur_nr_sectors
* BDRV_SECTOR_SIZE
);
1208 qemu_co_mutex_unlock(&s
->lock
);
1209 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
1210 trace_qcow2_writev_data(qemu_coroutine_self(),
1211 (cluster_offset
>> 9) + index_in_cluster
);
1212 ret
= bdrv_co_writev(bs
->file
,
1213 (cluster_offset
>> 9) + index_in_cluster
,
1214 cur_nr_sectors
, &hd_qiov
);
1215 qemu_co_mutex_lock(&s
->lock
);
1220 while (l2meta
!= NULL
) {
1223 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1228 /* Take the request off the list of running requests */
1229 if (l2meta
->nb_clusters
!= 0) {
1230 QLIST_REMOVE(l2meta
, next_in_flight
);
1233 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1235 next
= l2meta
->next
;
1240 remaining_sectors
-= cur_nr_sectors
;
1241 sector_num
+= cur_nr_sectors
;
1242 bytes_done
+= cur_nr_sectors
* 512;
1243 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors
);
1248 qemu_co_mutex_unlock(&s
->lock
);
1250 while (l2meta
!= NULL
) {
1253 if (l2meta
->nb_clusters
!= 0) {
1254 QLIST_REMOVE(l2meta
, next_in_flight
);
1256 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1258 next
= l2meta
->next
;
1263 qemu_iovec_destroy(&hd_qiov
);
1264 qemu_vfree(cluster_data
);
1265 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
1270 static void qcow2_close(BlockDriverState
*bs
)
1272 BDRVQcowState
*s
= bs
->opaque
;
1273 g_free(s
->l1_table
);
1274 /* else pre-write overlap checks in cache_destroy may crash */
1277 if (!(bs
->open_flags
& BDRV_O_INCOMING
)) {
1278 qcow2_cache_flush(bs
, s
->l2_table_cache
);
1279 qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1281 qcow2_mark_clean(bs
);
1284 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1285 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1287 g_free(s
->unknown_header_fields
);
1288 cleanup_unknown_header_ext(bs
);
1290 g_free(s
->cluster_cache
);
1291 qemu_vfree(s
->cluster_data
);
1292 qcow2_refcount_close(bs
);
1293 qcow2_free_snapshots(bs
);
1296 static void qcow2_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
1298 BDRVQcowState
*s
= bs
->opaque
;
1299 int flags
= s
->flags
;
1300 AES_KEY aes_encrypt_key
;
1301 AES_KEY aes_decrypt_key
;
1302 uint32_t crypt_method
= 0;
1304 Error
*local_err
= NULL
;
1308 * Backing files are read-only which makes all of their metadata immutable,
1309 * that means we don't have to worry about reopening them here.
1312 if (s
->crypt_method
) {
1313 crypt_method
= s
->crypt_method
;
1314 memcpy(&aes_encrypt_key
, &s
->aes_encrypt_key
, sizeof(aes_encrypt_key
));
1315 memcpy(&aes_decrypt_key
, &s
->aes_decrypt_key
, sizeof(aes_decrypt_key
));
1320 bdrv_invalidate_cache(bs
->file
, &local_err
);
1322 error_propagate(errp
, local_err
);
1326 memset(s
, 0, sizeof(BDRVQcowState
));
1327 options
= qdict_clone_shallow(bs
->options
);
1329 ret
= qcow2_open(bs
, options
, flags
, &local_err
);
1332 error_setg(errp
, "Could not reopen qcow2 layer: %s",
1333 error_get_pretty(local_err
));
1334 error_free(local_err
);
1336 } else if (ret
< 0) {
1337 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
1342 s
->crypt_method
= crypt_method
;
1343 memcpy(&s
->aes_encrypt_key
, &aes_encrypt_key
, sizeof(aes_encrypt_key
));
1344 memcpy(&s
->aes_decrypt_key
, &aes_decrypt_key
, sizeof(aes_decrypt_key
));
1348 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
1349 size_t len
, size_t buflen
)
1351 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
1352 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
1354 if (buflen
< ext_len
) {
1358 *ext_backing_fmt
= (QCowExtension
) {
1359 .magic
= cpu_to_be32(magic
),
1360 .len
= cpu_to_be32(len
),
1362 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
1368 * Updates the qcow2 header, including the variable length parts of it, i.e.
1369 * the backing file name and all extensions. qcow2 was not designed to allow
1370 * such changes, so if we run out of space (we can only use the first cluster)
1371 * this function may fail.
1373 * Returns 0 on success, -errno in error cases.
1375 int qcow2_update_header(BlockDriverState
*bs
)
1377 BDRVQcowState
*s
= bs
->opaque
;
1380 size_t buflen
= s
->cluster_size
;
1382 uint64_t total_size
;
1383 uint32_t refcount_table_clusters
;
1384 size_t header_length
;
1385 Qcow2UnknownHeaderExtension
*uext
;
1387 buf
= qemu_blockalign(bs
, buflen
);
1389 /* Header structure */
1390 header
= (QCowHeader
*) buf
;
1392 if (buflen
< sizeof(*header
)) {
1397 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
1398 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1399 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
1401 *header
= (QCowHeader
) {
1402 /* Version 2 fields */
1403 .magic
= cpu_to_be32(QCOW_MAGIC
),
1404 .version
= cpu_to_be32(s
->qcow_version
),
1405 .backing_file_offset
= 0,
1406 .backing_file_size
= 0,
1407 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
1408 .size
= cpu_to_be64(total_size
),
1409 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
1410 .l1_size
= cpu_to_be32(s
->l1_size
),
1411 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
1412 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
1413 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
1414 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
1415 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
1417 /* Version 3 fields */
1418 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
1419 .compatible_features
= cpu_to_be64(s
->compatible_features
),
1420 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
1421 .refcount_order
= cpu_to_be32(s
->refcount_order
),
1422 .header_length
= cpu_to_be32(header_length
),
1425 /* For older versions, write a shorter header */
1426 switch (s
->qcow_version
) {
1428 ret
= offsetof(QCowHeader
, incompatible_features
);
1431 ret
= sizeof(*header
);
1440 memset(buf
, 0, buflen
);
1442 /* Preserve any unknown field in the header */
1443 if (s
->unknown_header_fields_size
) {
1444 if (buflen
< s
->unknown_header_fields_size
) {
1449 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
1450 buf
+= s
->unknown_header_fields_size
;
1451 buflen
-= s
->unknown_header_fields_size
;
1454 /* Backing file format header extension */
1455 if (*bs
->backing_format
) {
1456 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
1457 bs
->backing_format
, strlen(bs
->backing_format
),
1468 Qcow2Feature features
[] = {
1470 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1471 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
1472 .name
= "dirty bit",
1475 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1476 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
1477 .name
= "corrupt bit",
1480 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
1481 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
1482 .name
= "lazy refcounts",
1486 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
1487 features
, sizeof(features
), buflen
);
1494 /* Keep unknown header extensions */
1495 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
1496 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
1505 /* End of header extensions */
1506 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
1514 /* Backing file name */
1515 if (*bs
->backing_file
) {
1516 size_t backing_file_len
= strlen(bs
->backing_file
);
1518 if (buflen
< backing_file_len
) {
1523 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1524 strncpy(buf
, bs
->backing_file
, buflen
);
1526 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
1527 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
1530 /* Write the new header */
1531 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
1542 static int qcow2_change_backing_file(BlockDriverState
*bs
,
1543 const char *backing_file
, const char *backing_fmt
)
1545 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
1546 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
1548 return qcow2_update_header(bs
);
1551 static int preallocate(BlockDriverState
*bs
)
1553 uint64_t nb_sectors
;
1555 uint64_t host_offset
= 0;
1560 nb_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
1563 while (nb_sectors
) {
1564 num
= MIN(nb_sectors
, INT_MAX
>> BDRV_SECTOR_BITS
);
1565 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &num
,
1566 &host_offset
, &meta
);
1572 QCowL2Meta
*next
= meta
->next
;
1574 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
1576 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
1577 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
1581 /* There are no dependent requests, but we need to remove our
1582 * request from the list of in-flight requests */
1583 QLIST_REMOVE(meta
, next_in_flight
);
1589 /* TODO Preallocate data if requested */
1592 offset
+= num
<< BDRV_SECTOR_BITS
;
1596 * It is expected that the image file is large enough to actually contain
1597 * all of the allocated clusters (otherwise we get failing reads after
1598 * EOF). Extend the image to the last allocated sector.
1600 if (host_offset
!= 0) {
1601 uint8_t buf
[BDRV_SECTOR_SIZE
];
1602 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1603 ret
= bdrv_write(bs
->file
, (host_offset
>> BDRV_SECTOR_BITS
) + num
- 1,
1613 static int qcow2_create2(const char *filename
, int64_t total_size
,
1614 const char *backing_file
, const char *backing_format
,
1615 int flags
, size_t cluster_size
, int prealloc
,
1616 QemuOpts
*opts
, int version
,
1619 /* Calculate cluster_bits */
1621 cluster_bits
= ffs(cluster_size
) - 1;
1622 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
1623 (1 << cluster_bits
) != cluster_size
)
1625 error_setg(errp
, "Cluster size must be a power of two between %d and "
1626 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
1631 * Open the image file and write a minimal qcow2 header.
1633 * We keep things simple and start with a zero-sized image. We also
1634 * do without refcount blocks or a L1 table for now. We'll fix the
1635 * inconsistency later.
1637 * We do need a refcount table because growing the refcount table means
1638 * allocating two new refcount blocks - the seconds of which would be at
1639 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1640 * size for any qcow2 image.
1642 BlockDriverState
* bs
;
1644 uint64_t* refcount_table
;
1645 Error
*local_err
= NULL
;
1648 ret
= bdrv_create_file(filename
, opts
, &local_err
);
1650 error_propagate(errp
, local_err
);
1655 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
, BDRV_O_RDWR
| BDRV_O_PROTOCOL
,
1658 error_propagate(errp
, local_err
);
1662 /* Write the header */
1663 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
1664 header
= g_malloc0(cluster_size
);
1665 *header
= (QCowHeader
) {
1666 .magic
= cpu_to_be32(QCOW_MAGIC
),
1667 .version
= cpu_to_be32(version
),
1668 .cluster_bits
= cpu_to_be32(cluster_bits
),
1669 .size
= cpu_to_be64(0),
1670 .l1_table_offset
= cpu_to_be64(0),
1671 .l1_size
= cpu_to_be32(0),
1672 .refcount_table_offset
= cpu_to_be64(cluster_size
),
1673 .refcount_table_clusters
= cpu_to_be32(1),
1674 .refcount_order
= cpu_to_be32(3 + REFCOUNT_SHIFT
),
1675 .header_length
= cpu_to_be32(sizeof(*header
)),
1678 if (flags
& BLOCK_FLAG_ENCRYPT
) {
1679 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_AES
);
1681 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
1684 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
1685 header
->compatible_features
|=
1686 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
1689 ret
= bdrv_pwrite(bs
, 0, header
, cluster_size
);
1692 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
1696 /* Write a refcount table with one refcount block */
1697 refcount_table
= g_malloc0(2 * cluster_size
);
1698 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
1699 ret
= bdrv_pwrite(bs
, cluster_size
, refcount_table
, 2 * cluster_size
);
1700 g_free(refcount_table
);
1703 error_setg_errno(errp
, -ret
, "Could not write refcount table");
1711 * And now open the image and make it consistent first (i.e. increase the
1712 * refcount of the cluster that is occupied by the header and the refcount
1715 BlockDriver
* drv
= bdrv_find_format("qcow2");
1716 assert(drv
!= NULL
);
1717 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
,
1718 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_NO_FLUSH
, drv
, &local_err
);
1720 error_propagate(errp
, local_err
);
1724 ret
= qcow2_alloc_clusters(bs
, 3 * cluster_size
);
1726 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
1727 "header and refcount table");
1730 } else if (ret
!= 0) {
1731 error_report("Huh, first cluster in empty image is already in use?");
1735 /* Okay, now that we have a valid image, let's give it the right size */
1736 ret
= bdrv_truncate(bs
, total_size
* BDRV_SECTOR_SIZE
);
1738 error_setg_errno(errp
, -ret
, "Could not resize image");
1742 /* Want a backing file? There you go.*/
1744 ret
= bdrv_change_backing_file(bs
, backing_file
, backing_format
);
1746 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
1747 "with format '%s'", backing_file
, backing_format
);
1752 /* And if we're supposed to preallocate metadata, do that now */
1754 BDRVQcowState
*s
= bs
->opaque
;
1755 qemu_co_mutex_lock(&s
->lock
);
1756 ret
= preallocate(bs
);
1757 qemu_co_mutex_unlock(&s
->lock
);
1759 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
1767 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1768 ret
= bdrv_open(&bs
, filename
, NULL
, NULL
,
1769 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_NO_BACKING
,
1772 error_propagate(errp
, local_err
);
1784 static int qcow2_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1786 char *backing_file
= NULL
;
1787 char *backing_fmt
= NULL
;
1789 uint64_t sectors
= 0;
1791 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
1794 Error
*local_err
= NULL
;
1797 /* Read out options */
1798 sectors
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0) / 512;
1799 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1800 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
1801 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ENCRYPT
, false)) {
1802 flags
|= BLOCK_FLAG_ENCRYPT
;
1804 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
1805 DEFAULT_CLUSTER_SIZE
);
1806 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1807 if (!buf
|| !strcmp(buf
, "off")) {
1809 } else if (!strcmp(buf
, "metadata")) {
1812 error_setg(errp
, "Invalid preallocation mode: '%s'", buf
);
1817 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
1819 /* keep the default */
1820 } else if (!strcmp(buf
, "0.10")) {
1822 } else if (!strcmp(buf
, "1.1")) {
1825 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
1830 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_LAZY_REFCOUNTS
, false)) {
1831 flags
|= BLOCK_FLAG_LAZY_REFCOUNTS
;
1834 if (backing_file
&& prealloc
) {
1835 error_setg(errp
, "Backing file and preallocation cannot be used at "
1841 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
1842 error_setg(errp
, "Lazy refcounts only supported with compatibility "
1843 "level 1.1 and above (use compat=1.1 or greater)");
1848 ret
= qcow2_create2(filename
, sectors
, backing_file
, backing_fmt
, flags
,
1849 cluster_size
, prealloc
, opts
, version
, &local_err
);
1851 error_propagate(errp
, local_err
);
1855 g_free(backing_file
);
1856 g_free(backing_fmt
);
1861 static coroutine_fn
int qcow2_co_write_zeroes(BlockDriverState
*bs
,
1862 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1865 BDRVQcowState
*s
= bs
->opaque
;
1867 /* Emulate misaligned zero writes */
1868 if (sector_num
% s
->cluster_sectors
|| nb_sectors
% s
->cluster_sectors
) {
1872 /* Whatever is left can use real zero clusters */
1873 qemu_co_mutex_lock(&s
->lock
);
1874 ret
= qcow2_zero_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1876 qemu_co_mutex_unlock(&s
->lock
);
1881 static coroutine_fn
int qcow2_co_discard(BlockDriverState
*bs
,
1882 int64_t sector_num
, int nb_sectors
)
1885 BDRVQcowState
*s
= bs
->opaque
;
1887 qemu_co_mutex_lock(&s
->lock
);
1888 ret
= qcow2_discard_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1889 nb_sectors
, QCOW2_DISCARD_REQUEST
);
1890 qemu_co_mutex_unlock(&s
->lock
);
1894 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
)
1896 BDRVQcowState
*s
= bs
->opaque
;
1897 int64_t new_l1_size
;
1901 error_report("The new size must be a multiple of 512");
1905 /* cannot proceed if image has snapshots */
1906 if (s
->nb_snapshots
) {
1907 error_report("Can't resize an image which has snapshots");
1911 /* shrinking is currently not supported */
1912 if (offset
< bs
->total_sectors
* 512) {
1913 error_report("qcow2 doesn't support shrinking images yet");
1917 new_l1_size
= size_to_l1(s
, offset
);
1918 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
1923 /* write updated header.size */
1924 offset
= cpu_to_be64(offset
);
1925 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
1926 &offset
, sizeof(uint64_t));
1931 s
->l1_vm_state_index
= new_l1_size
;
1935 /* XXX: put compressed sectors first, then all the cluster aligned
1936 tables to avoid losing bytes in alignment */
1937 static int qcow2_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1938 const uint8_t *buf
, int nb_sectors
)
1940 BDRVQcowState
*s
= bs
->opaque
;
1944 uint64_t cluster_offset
;
1946 if (nb_sectors
== 0) {
1947 /* align end of file to a sector boundary to ease reading with
1948 sector based I/Os */
1949 cluster_offset
= bdrv_getlength(bs
->file
);
1950 cluster_offset
= (cluster_offset
+ 511) & ~511;
1951 bdrv_truncate(bs
->file
, cluster_offset
);
1955 if (nb_sectors
!= s
->cluster_sectors
) {
1958 /* Zero-pad last write if image size is not cluster aligned */
1959 if (sector_num
+ nb_sectors
== bs
->total_sectors
&&
1960 nb_sectors
< s
->cluster_sectors
) {
1961 uint8_t *pad_buf
= qemu_blockalign(bs
, s
->cluster_size
);
1962 memset(pad_buf
, 0, s
->cluster_size
);
1963 memcpy(pad_buf
, buf
, nb_sectors
* BDRV_SECTOR_SIZE
);
1964 ret
= qcow2_write_compressed(bs
, sector_num
,
1965 pad_buf
, s
->cluster_sectors
);
1966 qemu_vfree(pad_buf
);
1971 out_buf
= g_malloc(s
->cluster_size
+ (s
->cluster_size
/ 1000) + 128);
1973 /* best compression, small window, no zlib header */
1974 memset(&strm
, 0, sizeof(strm
));
1975 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
1977 9, Z_DEFAULT_STRATEGY
);
1983 strm
.avail_in
= s
->cluster_size
;
1984 strm
.next_in
= (uint8_t *)buf
;
1985 strm
.avail_out
= s
->cluster_size
;
1986 strm
.next_out
= out_buf
;
1988 ret
= deflate(&strm
, Z_FINISH
);
1989 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
1994 out_len
= strm
.next_out
- out_buf
;
1998 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
1999 /* could not compress: write normal cluster */
2000 ret
= bdrv_write(bs
, sector_num
, buf
, s
->cluster_sectors
);
2005 cluster_offset
= qcow2_alloc_compressed_cluster_offset(bs
,
2006 sector_num
<< 9, out_len
);
2007 if (!cluster_offset
) {
2011 cluster_offset
&= s
->cluster_offset_mask
;
2013 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
2018 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
2019 ret
= bdrv_pwrite(bs
->file
, cluster_offset
, out_buf
, out_len
);
2031 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
2033 BDRVQcowState
*s
= bs
->opaque
;
2036 qemu_co_mutex_lock(&s
->lock
);
2037 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2039 qemu_co_mutex_unlock(&s
->lock
);
2043 if (qcow2_need_accurate_refcounts(s
)) {
2044 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2046 qemu_co_mutex_unlock(&s
->lock
);
2050 qemu_co_mutex_unlock(&s
->lock
);
2055 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2057 BDRVQcowState
*s
= bs
->opaque
;
2058 bdi
->unallocated_blocks_are_zero
= true;
2059 bdi
->can_write_zeroes_with_unmap
= (s
->qcow_version
>= 3);
2060 bdi
->cluster_size
= s
->cluster_size
;
2061 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
2065 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
2067 BDRVQcowState
*s
= bs
->opaque
;
2068 ImageInfoSpecific
*spec_info
= g_new(ImageInfoSpecific
, 1);
2070 *spec_info
= (ImageInfoSpecific
){
2071 .kind
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
2073 .qcow2
= g_new(ImageInfoSpecificQCow2
, 1),
2076 if (s
->qcow_version
== 2) {
2077 *spec_info
->qcow2
= (ImageInfoSpecificQCow2
){
2078 .compat
= g_strdup("0.10"),
2080 } else if (s
->qcow_version
== 3) {
2081 *spec_info
->qcow2
= (ImageInfoSpecificQCow2
){
2082 .compat
= g_strdup("1.1"),
2083 .lazy_refcounts
= s
->compatible_features
&
2084 QCOW2_COMPAT_LAZY_REFCOUNTS
,
2085 .has_lazy_refcounts
= true,
2093 static void dump_refcounts(BlockDriverState
*bs
)
2095 BDRVQcowState
*s
= bs
->opaque
;
2096 int64_t nb_clusters
, k
, k1
, size
;
2099 size
= bdrv_getlength(bs
->file
);
2100 nb_clusters
= size_to_clusters(s
, size
);
2101 for(k
= 0; k
< nb_clusters
;) {
2103 refcount
= get_refcount(bs
, k
);
2105 while (k
< nb_clusters
&& get_refcount(bs
, k
) == refcount
)
2107 printf("%" PRId64
": refcount=%d nb=%" PRId64
"\n", k
, refcount
,
2113 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
2116 BDRVQcowState
*s
= bs
->opaque
;
2117 int64_t total_sectors
= bs
->total_sectors
;
2118 int growable
= bs
->growable
;
2119 bool zero_beyond_eof
= bs
->zero_beyond_eof
;
2122 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
2124 bs
->zero_beyond_eof
= false;
2125 ret
= bdrv_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
, qiov
);
2126 bs
->growable
= growable
;
2127 bs
->zero_beyond_eof
= zero_beyond_eof
;
2129 /* bdrv_co_do_writev will have increased the total_sectors value to include
2130 * the VM state - the VM state is however not an actual part of the block
2131 * device, therefore, we need to restore the old value. */
2132 bs
->total_sectors
= total_sectors
;
2137 static int qcow2_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2138 int64_t pos
, int size
)
2140 BDRVQcowState
*s
= bs
->opaque
;
2141 int growable
= bs
->growable
;
2142 bool zero_beyond_eof
= bs
->zero_beyond_eof
;
2145 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
2147 bs
->zero_beyond_eof
= false;
2148 ret
= bdrv_pread(bs
, qcow2_vm_state_offset(s
) + pos
, buf
, size
);
2149 bs
->growable
= growable
;
2150 bs
->zero_beyond_eof
= zero_beyond_eof
;
2156 * Downgrades an image's version. To achieve this, any incompatible features
2157 * have to be removed.
2159 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
)
2161 BDRVQcowState
*s
= bs
->opaque
;
2162 int current_version
= s
->qcow_version
;
2165 if (target_version
== current_version
) {
2167 } else if (target_version
> current_version
) {
2169 } else if (target_version
!= 2) {
2173 if (s
->refcount_order
!= 4) {
2174 /* we would have to convert the image to a refcount_order == 4 image
2175 * here; however, since qemu (at the time of writing this) does not
2176 * support anything different than 4 anyway, there is no point in doing
2177 * so right now; however, we should error out (if qemu supports this in
2178 * the future and this code has not been adapted) */
2179 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2180 "currently not supported.");
2184 /* clear incompatible features */
2185 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
2186 ret
= qcow2_mark_clean(bs
);
2192 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2193 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2194 * best thing to do anyway */
2196 if (s
->incompatible_features
) {
2200 /* since we can ignore compatible features, we can set them to 0 as well */
2201 s
->compatible_features
= 0;
2202 /* if lazy refcounts have been used, they have already been fixed through
2203 * clearing the dirty flag */
2205 /* clearing autoclear features is trivial */
2206 s
->autoclear_features
= 0;
2208 ret
= qcow2_expand_zero_clusters(bs
);
2213 s
->qcow_version
= target_version
;
2214 ret
= qcow2_update_header(bs
);
2216 s
->qcow_version
= current_version
;
2222 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
)
2224 BDRVQcowState
*s
= bs
->opaque
;
2225 int old_version
= s
->qcow_version
, new_version
= old_version
;
2226 uint64_t new_size
= 0;
2227 const char *backing_file
= NULL
, *backing_format
= NULL
;
2228 bool lazy_refcounts
= s
->use_lazy_refcounts
;
2229 const char *compat
= NULL
;
2230 uint64_t cluster_size
= s
->cluster_size
;
2233 QemuOptDesc
*desc
= opts
->list
->desc
;
2235 while (desc
&& desc
->name
) {
2236 if (!qemu_opt_find(opts
, desc
->name
)) {
2237 /* only change explicitly defined options */
2242 if (!strcmp(desc
->name
, "compat")) {
2243 compat
= qemu_opt_get(opts
, "compat");
2245 /* preserve default */
2246 } else if (!strcmp(compat
, "0.10")) {
2248 } else if (!strcmp(compat
, "1.1")) {
2251 fprintf(stderr
, "Unknown compatibility level %s.\n", compat
);
2254 } else if (!strcmp(desc
->name
, "preallocation")) {
2255 fprintf(stderr
, "Cannot change preallocation mode.\n");
2257 } else if (!strcmp(desc
->name
, "size")) {
2258 new_size
= qemu_opt_get_size(opts
, "size", 0);
2259 } else if (!strcmp(desc
->name
, "backing_file")) {
2260 backing_file
= qemu_opt_get(opts
, "backing_file");
2261 } else if (!strcmp(desc
->name
, "backing_fmt")) {
2262 backing_format
= qemu_opt_get(opts
, "backing_fmt");
2263 } else if (!strcmp(desc
->name
, "encryption")) {
2264 encrypt
= qemu_opt_get_bool(opts
, "encryption", s
->crypt_method
);
2265 if (encrypt
!= !!s
->crypt_method
) {
2266 fprintf(stderr
, "Changing the encryption flag is not "
2270 } else if (!strcmp(desc
->name
, "cluster_size")) {
2271 cluster_size
= qemu_opt_get_size(opts
, "cluster_size",
2273 if (cluster_size
!= s
->cluster_size
) {
2274 fprintf(stderr
, "Changing the cluster size is not "
2278 } else if (!strcmp(desc
->name
, "lazy_refcounts")) {
2279 lazy_refcounts
= qemu_opt_get_bool(opts
, "lazy_refcounts",
2282 /* if this assertion fails, this probably means a new option was
2283 * added without having it covered here */
2290 if (new_version
!= old_version
) {
2291 if (new_version
> old_version
) {
2293 s
->qcow_version
= new_version
;
2294 ret
= qcow2_update_header(bs
);
2296 s
->qcow_version
= old_version
;
2300 ret
= qcow2_downgrade(bs
, new_version
);
2307 if (backing_file
|| backing_format
) {
2308 ret
= qcow2_change_backing_file(bs
, backing_file
?: bs
->backing_file
,
2309 backing_format
?: bs
->backing_format
);
2315 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
2316 if (lazy_refcounts
) {
2317 if (s
->qcow_version
< 3) {
2318 fprintf(stderr
, "Lazy refcounts only supported with compatibility "
2319 "level 1.1 and above (use compat=1.1 or greater)\n");
2322 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2323 ret
= qcow2_update_header(bs
);
2325 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2328 s
->use_lazy_refcounts
= true;
2330 /* make image clean first */
2331 ret
= qcow2_mark_clean(bs
);
2335 /* now disallow lazy refcounts */
2336 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2337 ret
= qcow2_update_header(bs
);
2339 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2342 s
->use_lazy_refcounts
= false;
2347 ret
= bdrv_truncate(bs
, new_size
);
2356 static QemuOptsList qcow2_create_opts
= {
2357 .name
= "qcow2-create-opts",
2358 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
2361 .name
= BLOCK_OPT_SIZE
,
2362 .type
= QEMU_OPT_SIZE
,
2363 .help
= "Virtual disk size"
2366 .name
= BLOCK_OPT_COMPAT_LEVEL
,
2367 .type
= QEMU_OPT_STRING
,
2368 .help
= "Compatibility level (0.10 or 1.1)"
2371 .name
= BLOCK_OPT_BACKING_FILE
,
2372 .type
= QEMU_OPT_STRING
,
2373 .help
= "File name of a base image"
2376 .name
= BLOCK_OPT_BACKING_FMT
,
2377 .type
= QEMU_OPT_STRING
,
2378 .help
= "Image format of the base image"
2381 .name
= BLOCK_OPT_ENCRYPT
,
2382 .type
= QEMU_OPT_BOOL
,
2383 .help
= "Encrypt the image",
2384 .def_value_str
= "off"
2387 .name
= BLOCK_OPT_CLUSTER_SIZE
,
2388 .type
= QEMU_OPT_SIZE
,
2389 .help
= "qcow2 cluster size",
2390 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
2393 .name
= BLOCK_OPT_PREALLOC
,
2394 .type
= QEMU_OPT_STRING
,
2395 .help
= "Preallocation mode (allowed values: off, metadata)"
2398 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
2399 .type
= QEMU_OPT_BOOL
,
2400 .help
= "Postpone refcount updates",
2401 .def_value_str
= "off"
2403 { /* end of list */ }
2407 static BlockDriver bdrv_qcow2
= {
2408 .format_name
= "qcow2",
2409 .instance_size
= sizeof(BDRVQcowState
),
2410 .bdrv_probe
= qcow2_probe
,
2411 .bdrv_open
= qcow2_open
,
2412 .bdrv_close
= qcow2_close
,
2413 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
2414 .bdrv_create
= qcow2_create
,
2415 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
2416 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
2417 .bdrv_set_key
= qcow2_set_key
,
2419 .bdrv_co_readv
= qcow2_co_readv
,
2420 .bdrv_co_writev
= qcow2_co_writev
,
2421 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
2423 .bdrv_co_write_zeroes
= qcow2_co_write_zeroes
,
2424 .bdrv_co_discard
= qcow2_co_discard
,
2425 .bdrv_truncate
= qcow2_truncate
,
2426 .bdrv_write_compressed
= qcow2_write_compressed
,
2428 .bdrv_snapshot_create
= qcow2_snapshot_create
,
2429 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
2430 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
2431 .bdrv_snapshot_list
= qcow2_snapshot_list
,
2432 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
2433 .bdrv_get_info
= qcow2_get_info
,
2434 .bdrv_get_specific_info
= qcow2_get_specific_info
,
2436 .bdrv_save_vmstate
= qcow2_save_vmstate
,
2437 .bdrv_load_vmstate
= qcow2_load_vmstate
,
2439 .supports_backing
= true,
2440 .bdrv_change_backing_file
= qcow2_change_backing_file
,
2442 .bdrv_refresh_limits
= qcow2_refresh_limits
,
2443 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
2445 .create_opts
= &qcow2_create_opts
,
2446 .bdrv_check
= qcow2_check
,
2447 .bdrv_amend_options
= qcow2_amend_options
,
2450 static void bdrv_qcow2_init(void)
2452 bdrv_register(&bdrv_qcow2
);
2455 block_init(bdrv_qcow2_init
);