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"
36 Differences with QCOW:
38 - Support for multiple incremental snapshots.
39 - Memory management by reference counts.
40 - Clusters which have a reference count of one have the bit
41 QCOW_OFLAG_COPIED to optimize write performance.
42 - Size of compressed clusters is stored in sectors to reduce bit usage
43 in the cluster offsets.
44 - Support for storing additional data (such as the VM state) in the
46 - If a backing store is used, the cluster size is not constrained
47 (could be backported to QCOW).
48 - L2 tables have always a size of one cluster.
55 } QEMU_PACKED QCowExtension
;
57 #define QCOW2_EXT_MAGIC_END 0
58 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
59 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
61 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
63 const QCowHeader
*cow_header
= (const void *)buf
;
65 if (buf_size
>= sizeof(QCowHeader
) &&
66 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
67 be32_to_cpu(cow_header
->version
) >= 2)
75 * read qcow2 extension and fill bs
76 * start reading from start_offset
77 * finish reading upon magic of value 0 or when end_offset reached
78 * unknown magic is skipped (future extension this version knows nothing about)
79 * return 0 upon success, non-0 otherwise
81 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
82 uint64_t end_offset
, void **p_feature_table
,
85 BDRVQcowState
*s
= bs
->opaque
;
91 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
93 offset
= start_offset
;
94 while (offset
< end_offset
) {
98 if (offset
> s
->cluster_size
)
99 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
101 printf("attempting to read extended header in offset %lu\n", offset
);
104 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
106 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
107 "pread fail from offset %" PRIu64
, offset
);
110 be32_to_cpus(&ext
.magic
);
111 be32_to_cpus(&ext
.len
);
112 offset
+= sizeof(ext
);
114 printf("ext.magic = 0x%x\n", ext
.magic
);
116 if (ext
.len
> end_offset
- offset
) {
117 error_setg(errp
, "Header extension too large");
122 case QCOW2_EXT_MAGIC_END
:
125 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
126 if (ext
.len
>= sizeof(bs
->backing_format
)) {
127 error_setg(errp
, "ERROR: ext_backing_format: len=%u too large"
128 " (>=%zu)", ext
.len
, sizeof(bs
->backing_format
));
131 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
133 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
134 "Could not read format name");
137 bs
->backing_format
[ext
.len
] = '\0';
139 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
143 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
144 if (p_feature_table
!= NULL
) {
145 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
146 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
148 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
149 "Could not read table");
153 *p_feature_table
= feature_table
;
158 /* unknown magic - save it in case we need to rewrite the header */
160 Qcow2UnknownHeaderExtension
*uext
;
162 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
163 uext
->magic
= ext
.magic
;
165 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
167 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
169 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
170 "Could not read data");
177 offset
+= ((ext
.len
+ 7) & ~7);
183 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
185 BDRVQcowState
*s
= bs
->opaque
;
186 Qcow2UnknownHeaderExtension
*uext
, *next
;
188 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
189 QLIST_REMOVE(uext
, next
);
194 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState
*bs
,
195 Error
**errp
, const char *fmt
, ...)
201 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
204 error_set(errp
, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
, bs
->device_name
, "qcow2",
208 static void report_unsupported_feature(BlockDriverState
*bs
,
209 Error
**errp
, Qcow2Feature
*table
, uint64_t mask
)
211 while (table
&& table
->name
[0] != '\0') {
212 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
213 if (mask
& (1 << table
->bit
)) {
214 report_unsupported(bs
, errp
, "%.46s", table
->name
);
215 mask
&= ~(1 << table
->bit
);
222 report_unsupported(bs
, errp
, "Unknown incompatible feature: %" PRIx64
,
228 * Sets the dirty bit and flushes afterwards if necessary.
230 * The incompatible_features bit is only set if the image file header was
231 * updated successfully. Therefore it is not required to check the return
232 * value of this function.
234 int qcow2_mark_dirty(BlockDriverState
*bs
)
236 BDRVQcowState
*s
= bs
->opaque
;
240 assert(s
->qcow_version
>= 3);
242 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
243 return 0; /* already dirty */
246 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
247 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
252 ret
= bdrv_flush(bs
->file
);
257 /* Only treat image as dirty if the header was updated successfully */
258 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
263 * Clears the dirty bit and flushes before if necessary. Only call this
264 * function when there are no pending requests, it does not guard against
265 * concurrent requests dirtying the image.
267 static int qcow2_mark_clean(BlockDriverState
*bs
)
269 BDRVQcowState
*s
= bs
->opaque
;
271 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
272 int ret
= bdrv_flush(bs
);
277 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
278 return qcow2_update_header(bs
);
284 * Marks the image as corrupt.
286 int qcow2_mark_corrupt(BlockDriverState
*bs
)
288 BDRVQcowState
*s
= bs
->opaque
;
290 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
291 return qcow2_update_header(bs
);
295 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
296 * before if necessary.
298 int qcow2_mark_consistent(BlockDriverState
*bs
)
300 BDRVQcowState
*s
= bs
->opaque
;
302 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
303 int ret
= bdrv_flush(bs
);
308 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
309 return qcow2_update_header(bs
);
314 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
317 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
322 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
323 ret
= qcow2_mark_clean(bs
);
327 return qcow2_mark_consistent(bs
);
332 static QemuOptsList qcow2_runtime_opts
= {
334 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
337 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
338 .type
= QEMU_OPT_BOOL
,
339 .help
= "Postpone refcount updates",
342 .name
= QCOW2_OPT_DISCARD_REQUEST
,
343 .type
= QEMU_OPT_BOOL
,
344 .help
= "Pass guest discard requests to the layer below",
347 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
348 .type
= QEMU_OPT_BOOL
,
349 .help
= "Generate discard requests when snapshot related space "
353 .name
= QCOW2_OPT_DISCARD_OTHER
,
354 .type
= QEMU_OPT_BOOL
,
355 .help
= "Generate discard requests when other clusters are freed",
357 { /* end of list */ }
361 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
364 BDRVQcowState
*s
= bs
->opaque
;
368 Error
*local_err
= NULL
;
370 uint64_t l1_vm_state_index
;
372 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
374 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
377 be32_to_cpus(&header
.magic
);
378 be32_to_cpus(&header
.version
);
379 be64_to_cpus(&header
.backing_file_offset
);
380 be32_to_cpus(&header
.backing_file_size
);
381 be64_to_cpus(&header
.size
);
382 be32_to_cpus(&header
.cluster_bits
);
383 be32_to_cpus(&header
.crypt_method
);
384 be64_to_cpus(&header
.l1_table_offset
);
385 be32_to_cpus(&header
.l1_size
);
386 be64_to_cpus(&header
.refcount_table_offset
);
387 be32_to_cpus(&header
.refcount_table_clusters
);
388 be64_to_cpus(&header
.snapshots_offset
);
389 be32_to_cpus(&header
.nb_snapshots
);
391 if (header
.magic
!= QCOW_MAGIC
) {
392 error_setg(errp
, "Image is not in qcow2 format");
396 if (header
.version
< 2 || header
.version
> 3) {
397 report_unsupported(bs
, errp
, "QCOW version %d", header
.version
);
402 s
->qcow_version
= header
.version
;
404 /* Initialise version 3 header fields */
405 if (header
.version
== 2) {
406 header
.incompatible_features
= 0;
407 header
.compatible_features
= 0;
408 header
.autoclear_features
= 0;
409 header
.refcount_order
= 4;
410 header
.header_length
= 72;
412 be64_to_cpus(&header
.incompatible_features
);
413 be64_to_cpus(&header
.compatible_features
);
414 be64_to_cpus(&header
.autoclear_features
);
415 be32_to_cpus(&header
.refcount_order
);
416 be32_to_cpus(&header
.header_length
);
419 if (header
.header_length
> sizeof(header
)) {
420 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
421 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
422 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
423 s
->unknown_header_fields_size
);
425 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
431 if (header
.backing_file_offset
) {
432 ext_end
= header
.backing_file_offset
;
434 ext_end
= 1 << header
.cluster_bits
;
437 /* Handle feature bits */
438 s
->incompatible_features
= header
.incompatible_features
;
439 s
->compatible_features
= header
.compatible_features
;
440 s
->autoclear_features
= header
.autoclear_features
;
442 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
443 void *feature_table
= NULL
;
444 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
445 &feature_table
, NULL
);
446 report_unsupported_feature(bs
, errp
, feature_table
,
447 s
->incompatible_features
&
448 ~QCOW2_INCOMPAT_MASK
);
453 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
454 /* Corrupt images may not be written to unless they are being repaired
456 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
457 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
464 /* Check support for various header values */
465 if (header
.refcount_order
!= 4) {
466 report_unsupported(bs
, errp
, "%d bit reference counts",
467 1 << header
.refcount_order
);
471 s
->refcount_order
= header
.refcount_order
;
473 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
474 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
475 error_setg(errp
, "Unsupported cluster size: 2^%i", header
.cluster_bits
);
479 if (header
.crypt_method
> QCOW_CRYPT_AES
) {
480 error_setg(errp
, "Unsupported encryption method: %i",
481 header
.crypt_method
);
485 s
->crypt_method_header
= header
.crypt_method
;
486 if (s
->crypt_method_header
) {
489 s
->cluster_bits
= header
.cluster_bits
;
490 s
->cluster_size
= 1 << s
->cluster_bits
;
491 s
->cluster_sectors
= 1 << (s
->cluster_bits
- 9);
492 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
493 s
->l2_size
= 1 << s
->l2_bits
;
494 bs
->total_sectors
= header
.size
/ 512;
495 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
496 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
497 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
498 s
->refcount_table_offset
= header
.refcount_table_offset
;
499 s
->refcount_table_size
=
500 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
502 s
->snapshots_offset
= header
.snapshots_offset
;
503 s
->nb_snapshots
= header
.nb_snapshots
;
505 /* read the level 1 table */
506 s
->l1_size
= header
.l1_size
;
508 l1_vm_state_index
= size_to_l1(s
, header
.size
);
509 if (l1_vm_state_index
> INT_MAX
) {
510 error_setg(errp
, "Image is too big");
514 s
->l1_vm_state_index
= l1_vm_state_index
;
516 /* the L1 table must contain at least enough entries to put
518 if (s
->l1_size
< s
->l1_vm_state_index
) {
519 error_setg(errp
, "L1 table is too small");
523 s
->l1_table_offset
= header
.l1_table_offset
;
524 if (s
->l1_size
> 0) {
525 s
->l1_table
= g_malloc0(
526 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
527 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
528 s
->l1_size
* sizeof(uint64_t));
530 error_setg_errno(errp
, -ret
, "Could not read L1 table");
533 for(i
= 0;i
< s
->l1_size
; i
++) {
534 be64_to_cpus(&s
->l1_table
[i
]);
538 /* alloc L2 table/refcount block cache */
539 s
->l2_table_cache
= qcow2_cache_create(bs
, L2_CACHE_SIZE
);
540 s
->refcount_block_cache
= qcow2_cache_create(bs
, REFCOUNT_CACHE_SIZE
);
542 s
->cluster_cache
= g_malloc(s
->cluster_size
);
543 /* one more sector for decompressed data alignment */
544 s
->cluster_data
= qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
546 s
->cluster_cache_offset
= -1;
549 ret
= qcow2_refcount_init(bs
);
551 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
555 QLIST_INIT(&s
->cluster_allocs
);
556 QTAILQ_INIT(&s
->discards
);
558 /* read qcow2 extensions */
559 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
561 error_propagate(errp
, local_err
);
566 /* read the backing file name */
567 if (header
.backing_file_offset
!= 0) {
568 len
= header
.backing_file_size
;
572 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
573 bs
->backing_file
, len
);
575 error_setg_errno(errp
, -ret
, "Could not read backing file name");
578 bs
->backing_file
[len
] = '\0';
581 ret
= qcow2_read_snapshots(bs
);
583 error_setg_errno(errp
, -ret
, "Could not read snapshots");
587 /* Clear unknown autoclear feature bits */
588 if (!bs
->read_only
&& s
->autoclear_features
!= 0) {
589 s
->autoclear_features
= 0;
590 ret
= qcow2_update_header(bs
);
592 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
597 /* Initialise locks */
598 qemu_co_mutex_init(&s
->lock
);
600 /* Repair image if dirty */
601 if (!(flags
& BDRV_O_CHECK
) && !bs
->read_only
&&
602 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
603 BdrvCheckResult result
= {0};
605 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
);
607 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
612 /* Enable lazy_refcounts according to image and command line options */
613 opts
= qemu_opts_create_nofail(&qcow2_runtime_opts
);
614 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
615 if (error_is_set(&local_err
)) {
616 error_propagate(errp
, local_err
);
621 s
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
622 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
624 s
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
625 s
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
626 s
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
627 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
628 flags
& BDRV_O_UNMAP
);
629 s
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
630 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
631 s
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
632 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
634 s
->overlap_check
= QCOW2_OL_CACHED
;
638 if (s
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
639 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
640 "qemu 1.1 compatibility level");
647 BdrvCheckResult result
= {0};
648 qcow2_check_refcounts(bs
, &result
, 0);
654 g_free(s
->unknown_header_fields
);
655 cleanup_unknown_header_ext(bs
);
656 qcow2_free_snapshots(bs
);
657 qcow2_refcount_close(bs
);
659 /* else pre-write overlap checks in cache_destroy may crash */
661 if (s
->l2_table_cache
) {
662 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
664 g_free(s
->cluster_cache
);
665 qemu_vfree(s
->cluster_data
);
669 static int qcow2_set_key(BlockDriverState
*bs
, const char *key
)
671 BDRVQcowState
*s
= bs
->opaque
;
675 memset(keybuf
, 0, 16);
679 /* XXX: we could compress the chars to 7 bits to increase
681 for(i
= 0;i
< len
;i
++) {
684 s
->crypt_method
= s
->crypt_method_header
;
686 if (AES_set_encrypt_key(keybuf
, 128, &s
->aes_encrypt_key
) != 0)
688 if (AES_set_decrypt_key(keybuf
, 128, &s
->aes_decrypt_key
) != 0)
698 AES_encrypt(in
, tmp
, &s
->aes_encrypt_key
);
699 AES_decrypt(tmp
, out
, &s
->aes_decrypt_key
);
700 for(i
= 0; i
< 16; i
++)
701 printf(" %02x", tmp
[i
]);
703 for(i
= 0; i
< 16; i
++)
704 printf(" %02x", out
[i
]);
711 /* We have nothing to do for QCOW2 reopen, stubs just return
713 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
714 BlockReopenQueue
*queue
, Error
**errp
)
719 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
720 int64_t sector_num
, int nb_sectors
, int *pnum
)
722 BDRVQcowState
*s
= bs
->opaque
;
723 uint64_t cluster_offset
;
724 int index_in_cluster
, ret
;
728 qemu_co_mutex_lock(&s
->lock
);
729 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9, pnum
, &cluster_offset
);
730 qemu_co_mutex_unlock(&s
->lock
);
735 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
737 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
738 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
739 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
741 if (ret
== QCOW2_CLUSTER_ZERO
) {
742 status
|= BDRV_BLOCK_ZERO
;
743 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
744 status
|= BDRV_BLOCK_DATA
;
749 /* handle reading after the end of the backing file */
750 int qcow2_backing_read1(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
751 int64_t sector_num
, int nb_sectors
)
754 if ((sector_num
+ nb_sectors
) <= bs
->total_sectors
)
756 if (sector_num
>= bs
->total_sectors
)
759 n1
= bs
->total_sectors
- sector_num
;
761 qemu_iovec_memset(qiov
, 512 * n1
, 0, 512 * (nb_sectors
- n1
));
766 static coroutine_fn
int qcow2_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
767 int remaining_sectors
, QEMUIOVector
*qiov
)
769 BDRVQcowState
*s
= bs
->opaque
;
770 int index_in_cluster
, n1
;
772 int cur_nr_sectors
; /* number of sectors in current iteration */
773 uint64_t cluster_offset
= 0;
774 uint64_t bytes_done
= 0;
775 QEMUIOVector hd_qiov
;
776 uint8_t *cluster_data
= NULL
;
778 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
780 qemu_co_mutex_lock(&s
->lock
);
782 while (remaining_sectors
!= 0) {
784 /* prepare next request */
785 cur_nr_sectors
= remaining_sectors
;
786 if (s
->crypt_method
) {
787 cur_nr_sectors
= MIN(cur_nr_sectors
,
788 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
791 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9,
792 &cur_nr_sectors
, &cluster_offset
);
797 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
799 qemu_iovec_reset(&hd_qiov
);
800 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
801 cur_nr_sectors
* 512);
804 case QCOW2_CLUSTER_UNALLOCATED
:
806 if (bs
->backing_hd
) {
807 /* read from the base image */
808 n1
= qcow2_backing_read1(bs
->backing_hd
, &hd_qiov
,
809 sector_num
, cur_nr_sectors
);
811 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
812 qemu_co_mutex_unlock(&s
->lock
);
813 ret
= bdrv_co_readv(bs
->backing_hd
, sector_num
,
815 qemu_co_mutex_lock(&s
->lock
);
821 /* Note: in this case, no need to wait */
822 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
826 case QCOW2_CLUSTER_ZERO
:
827 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
830 case QCOW2_CLUSTER_COMPRESSED
:
831 /* add AIO support for compressed blocks ? */
832 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
837 qemu_iovec_from_buf(&hd_qiov
, 0,
838 s
->cluster_cache
+ index_in_cluster
* 512,
839 512 * cur_nr_sectors
);
842 case QCOW2_CLUSTER_NORMAL
:
843 if ((cluster_offset
& 511) != 0) {
848 if (s
->crypt_method
) {
850 * For encrypted images, read everything into a temporary
851 * contiguous buffer on which the AES functions can work.
855 qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
858 assert(cur_nr_sectors
<=
859 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
860 qemu_iovec_reset(&hd_qiov
);
861 qemu_iovec_add(&hd_qiov
, cluster_data
,
862 512 * cur_nr_sectors
);
865 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
866 qemu_co_mutex_unlock(&s
->lock
);
867 ret
= bdrv_co_readv(bs
->file
,
868 (cluster_offset
>> 9) + index_in_cluster
,
869 cur_nr_sectors
, &hd_qiov
);
870 qemu_co_mutex_lock(&s
->lock
);
874 if (s
->crypt_method
) {
875 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
876 cluster_data
, cur_nr_sectors
, 0, &s
->aes_decrypt_key
);
877 qemu_iovec_from_buf(qiov
, bytes_done
,
878 cluster_data
, 512 * cur_nr_sectors
);
883 g_assert_not_reached();
888 remaining_sectors
-= cur_nr_sectors
;
889 sector_num
+= cur_nr_sectors
;
890 bytes_done
+= cur_nr_sectors
* 512;
895 qemu_co_mutex_unlock(&s
->lock
);
897 qemu_iovec_destroy(&hd_qiov
);
898 qemu_vfree(cluster_data
);
903 static coroutine_fn
int qcow2_co_writev(BlockDriverState
*bs
,
905 int remaining_sectors
,
908 BDRVQcowState
*s
= bs
->opaque
;
909 int index_in_cluster
;
912 int cur_nr_sectors
; /* number of sectors in current iteration */
913 uint64_t cluster_offset
;
914 QEMUIOVector hd_qiov
;
915 uint64_t bytes_done
= 0;
916 uint8_t *cluster_data
= NULL
;
917 QCowL2Meta
*l2meta
= NULL
;
919 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num
,
922 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
924 s
->cluster_cache_offset
= -1; /* disable compressed cache */
926 qemu_co_mutex_lock(&s
->lock
);
928 while (remaining_sectors
!= 0) {
932 trace_qcow2_writev_start_part(qemu_coroutine_self());
933 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
934 n_end
= index_in_cluster
+ remaining_sectors
;
935 if (s
->crypt_method
&&
936 n_end
> QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
) {
937 n_end
= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
;
940 ret
= qcow2_alloc_cluster_offset(bs
, sector_num
<< 9,
941 index_in_cluster
, n_end
, &cur_nr_sectors
, &cluster_offset
, &l2meta
);
946 assert((cluster_offset
& 511) == 0);
948 qemu_iovec_reset(&hd_qiov
);
949 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
950 cur_nr_sectors
* 512);
952 if (s
->crypt_method
) {
954 cluster_data
= qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
*
958 assert(hd_qiov
.size
<=
959 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
960 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
962 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
963 cluster_data
, cur_nr_sectors
, 1, &s
->aes_encrypt_key
);
965 qemu_iovec_reset(&hd_qiov
);
966 qemu_iovec_add(&hd_qiov
, cluster_data
,
967 cur_nr_sectors
* 512);
970 ret
= qcow2_pre_write_overlap_check(bs
, 0,
971 cluster_offset
+ index_in_cluster
* BDRV_SECTOR_SIZE
,
972 cur_nr_sectors
* BDRV_SECTOR_SIZE
);
977 qemu_co_mutex_unlock(&s
->lock
);
978 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
979 trace_qcow2_writev_data(qemu_coroutine_self(),
980 (cluster_offset
>> 9) + index_in_cluster
);
981 ret
= bdrv_co_writev(bs
->file
,
982 (cluster_offset
>> 9) + index_in_cluster
,
983 cur_nr_sectors
, &hd_qiov
);
984 qemu_co_mutex_lock(&s
->lock
);
989 while (l2meta
!= NULL
) {
992 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
997 /* Take the request off the list of running requests */
998 if (l2meta
->nb_clusters
!= 0) {
999 QLIST_REMOVE(l2meta
, next_in_flight
);
1002 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1004 next
= l2meta
->next
;
1009 remaining_sectors
-= cur_nr_sectors
;
1010 sector_num
+= cur_nr_sectors
;
1011 bytes_done
+= cur_nr_sectors
* 512;
1012 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors
);
1017 qemu_co_mutex_unlock(&s
->lock
);
1019 while (l2meta
!= NULL
) {
1022 if (l2meta
->nb_clusters
!= 0) {
1023 QLIST_REMOVE(l2meta
, next_in_flight
);
1025 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1027 next
= l2meta
->next
;
1032 qemu_iovec_destroy(&hd_qiov
);
1033 qemu_vfree(cluster_data
);
1034 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
1039 static void qcow2_close(BlockDriverState
*bs
)
1041 BDRVQcowState
*s
= bs
->opaque
;
1042 g_free(s
->l1_table
);
1043 /* else pre-write overlap checks in cache_destroy may crash */
1046 qcow2_cache_flush(bs
, s
->l2_table_cache
);
1047 qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1049 qcow2_mark_clean(bs
);
1051 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1052 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1054 g_free(s
->unknown_header_fields
);
1055 cleanup_unknown_header_ext(bs
);
1057 g_free(s
->cluster_cache
);
1058 qemu_vfree(s
->cluster_data
);
1059 qcow2_refcount_close(bs
);
1060 qcow2_free_snapshots(bs
);
1063 static void qcow2_invalidate_cache(BlockDriverState
*bs
)
1065 BDRVQcowState
*s
= bs
->opaque
;
1066 int flags
= s
->flags
;
1067 AES_KEY aes_encrypt_key
;
1068 AES_KEY aes_decrypt_key
;
1069 uint32_t crypt_method
= 0;
1073 * Backing files are read-only which makes all of their metadata immutable,
1074 * that means we don't have to worry about reopening them here.
1077 if (s
->crypt_method
) {
1078 crypt_method
= s
->crypt_method
;
1079 memcpy(&aes_encrypt_key
, &s
->aes_encrypt_key
, sizeof(aes_encrypt_key
));
1080 memcpy(&aes_decrypt_key
, &s
->aes_decrypt_key
, sizeof(aes_decrypt_key
));
1085 options
= qdict_new();
1086 qdict_put(options
, QCOW2_OPT_LAZY_REFCOUNTS
,
1087 qbool_from_int(s
->use_lazy_refcounts
));
1089 memset(s
, 0, sizeof(BDRVQcowState
));
1090 qcow2_open(bs
, options
, flags
, NULL
);
1095 s
->crypt_method
= crypt_method
;
1096 memcpy(&s
->aes_encrypt_key
, &aes_encrypt_key
, sizeof(aes_encrypt_key
));
1097 memcpy(&s
->aes_decrypt_key
, &aes_decrypt_key
, sizeof(aes_decrypt_key
));
1101 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
1102 size_t len
, size_t buflen
)
1104 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
1105 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
1107 if (buflen
< ext_len
) {
1111 *ext_backing_fmt
= (QCowExtension
) {
1112 .magic
= cpu_to_be32(magic
),
1113 .len
= cpu_to_be32(len
),
1115 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
1121 * Updates the qcow2 header, including the variable length parts of it, i.e.
1122 * the backing file name and all extensions. qcow2 was not designed to allow
1123 * such changes, so if we run out of space (we can only use the first cluster)
1124 * this function may fail.
1126 * Returns 0 on success, -errno in error cases.
1128 int qcow2_update_header(BlockDriverState
*bs
)
1130 BDRVQcowState
*s
= bs
->opaque
;
1133 size_t buflen
= s
->cluster_size
;
1135 uint64_t total_size
;
1136 uint32_t refcount_table_clusters
;
1137 size_t header_length
;
1138 Qcow2UnknownHeaderExtension
*uext
;
1140 buf
= qemu_blockalign(bs
, buflen
);
1142 /* Header structure */
1143 header
= (QCowHeader
*) buf
;
1145 if (buflen
< sizeof(*header
)) {
1150 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
1151 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1152 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
1154 *header
= (QCowHeader
) {
1155 /* Version 2 fields */
1156 .magic
= cpu_to_be32(QCOW_MAGIC
),
1157 .version
= cpu_to_be32(s
->qcow_version
),
1158 .backing_file_offset
= 0,
1159 .backing_file_size
= 0,
1160 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
1161 .size
= cpu_to_be64(total_size
),
1162 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
1163 .l1_size
= cpu_to_be32(s
->l1_size
),
1164 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
1165 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
1166 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
1167 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
1168 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
1170 /* Version 3 fields */
1171 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
1172 .compatible_features
= cpu_to_be64(s
->compatible_features
),
1173 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
1174 .refcount_order
= cpu_to_be32(s
->refcount_order
),
1175 .header_length
= cpu_to_be32(header_length
),
1178 /* For older versions, write a shorter header */
1179 switch (s
->qcow_version
) {
1181 ret
= offsetof(QCowHeader
, incompatible_features
);
1184 ret
= sizeof(*header
);
1193 memset(buf
, 0, buflen
);
1195 /* Preserve any unknown field in the header */
1196 if (s
->unknown_header_fields_size
) {
1197 if (buflen
< s
->unknown_header_fields_size
) {
1202 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
1203 buf
+= s
->unknown_header_fields_size
;
1204 buflen
-= s
->unknown_header_fields_size
;
1207 /* Backing file format header extension */
1208 if (*bs
->backing_format
) {
1209 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
1210 bs
->backing_format
, strlen(bs
->backing_format
),
1221 Qcow2Feature features
[] = {
1223 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1224 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
1225 .name
= "dirty bit",
1228 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1229 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
1230 .name
= "corrupt bit",
1233 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
1234 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
1235 .name
= "lazy refcounts",
1239 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
1240 features
, sizeof(features
), buflen
);
1247 /* Keep unknown header extensions */
1248 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
1249 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
1258 /* End of header extensions */
1259 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
1267 /* Backing file name */
1268 if (*bs
->backing_file
) {
1269 size_t backing_file_len
= strlen(bs
->backing_file
);
1271 if (buflen
< backing_file_len
) {
1276 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1277 strncpy(buf
, bs
->backing_file
, buflen
);
1279 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
1280 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
1283 /* Write the new header */
1284 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
1295 static int qcow2_change_backing_file(BlockDriverState
*bs
,
1296 const char *backing_file
, const char *backing_fmt
)
1298 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
1299 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
1301 return qcow2_update_header(bs
);
1304 static int preallocate(BlockDriverState
*bs
)
1306 uint64_t nb_sectors
;
1308 uint64_t host_offset
= 0;
1313 nb_sectors
= bdrv_getlength(bs
) >> 9;
1316 while (nb_sectors
) {
1317 num
= MIN(nb_sectors
, INT_MAX
>> 9);
1318 ret
= qcow2_alloc_cluster_offset(bs
, offset
, 0, num
, &num
,
1319 &host_offset
, &meta
);
1324 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
1326 qcow2_free_any_clusters(bs
, meta
->alloc_offset
, meta
->nb_clusters
,
1327 QCOW2_DISCARD_NEVER
);
1331 /* There are no dependent requests, but we need to remove our request
1332 * from the list of in-flight requests */
1334 QLIST_REMOVE(meta
, next_in_flight
);
1337 /* TODO Preallocate data if requested */
1344 * It is expected that the image file is large enough to actually contain
1345 * all of the allocated clusters (otherwise we get failing reads after
1346 * EOF). Extend the image to the last allocated sector.
1348 if (host_offset
!= 0) {
1350 memset(buf
, 0, 512);
1351 ret
= bdrv_write(bs
->file
, (host_offset
>> 9) + num
- 1, buf
, 1);
1360 static int qcow2_create2(const char *filename
, int64_t total_size
,
1361 const char *backing_file
, const char *backing_format
,
1362 int flags
, size_t cluster_size
, int prealloc
,
1363 QEMUOptionParameter
*options
, int version
,
1366 /* Calculate cluster_bits */
1368 cluster_bits
= ffs(cluster_size
) - 1;
1369 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
1370 (1 << cluster_bits
) != cluster_size
)
1372 error_setg(errp
, "Cluster size must be a power of two between %d and "
1373 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
1378 * Open the image file and write a minimal qcow2 header.
1380 * We keep things simple and start with a zero-sized image. We also
1381 * do without refcount blocks or a L1 table for now. We'll fix the
1382 * inconsistency later.
1384 * We do need a refcount table because growing the refcount table means
1385 * allocating two new refcount blocks - the seconds of which would be at
1386 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1387 * size for any qcow2 image.
1389 BlockDriverState
* bs
;
1391 uint8_t* refcount_table
;
1392 Error
*local_err
= NULL
;
1395 ret
= bdrv_create_file(filename
, options
, &local_err
);
1397 error_propagate(errp
, local_err
);
1401 ret
= bdrv_file_open(&bs
, filename
, NULL
, BDRV_O_RDWR
, &local_err
);
1403 error_propagate(errp
, local_err
);
1407 /* Write the header */
1408 memset(&header
, 0, sizeof(header
));
1409 header
.magic
= cpu_to_be32(QCOW_MAGIC
);
1410 header
.version
= cpu_to_be32(version
);
1411 header
.cluster_bits
= cpu_to_be32(cluster_bits
);
1412 header
.size
= cpu_to_be64(0);
1413 header
.l1_table_offset
= cpu_to_be64(0);
1414 header
.l1_size
= cpu_to_be32(0);
1415 header
.refcount_table_offset
= cpu_to_be64(cluster_size
);
1416 header
.refcount_table_clusters
= cpu_to_be32(1);
1417 header
.refcount_order
= cpu_to_be32(3 + REFCOUNT_SHIFT
);
1418 header
.header_length
= cpu_to_be32(sizeof(header
));
1420 if (flags
& BLOCK_FLAG_ENCRYPT
) {
1421 header
.crypt_method
= cpu_to_be32(QCOW_CRYPT_AES
);
1423 header
.crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
1426 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
1427 header
.compatible_features
|=
1428 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
1431 ret
= bdrv_pwrite(bs
, 0, &header
, sizeof(header
));
1433 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
1437 /* Write an empty refcount table */
1438 refcount_table
= g_malloc0(cluster_size
);
1439 ret
= bdrv_pwrite(bs
, cluster_size
, refcount_table
, cluster_size
);
1440 g_free(refcount_table
);
1443 error_setg_errno(errp
, -ret
, "Could not write refcount table");
1450 * And now open the image and make it consistent first (i.e. increase the
1451 * refcount of the cluster that is occupied by the header and the refcount
1454 BlockDriver
* drv
= bdrv_find_format("qcow2");
1455 assert(drv
!= NULL
);
1456 ret
= bdrv_open(bs
, filename
, NULL
,
1457 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_NO_FLUSH
, drv
, &local_err
);
1459 error_propagate(errp
, local_err
);
1463 ret
= qcow2_alloc_clusters(bs
, 2 * cluster_size
);
1465 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
1466 "header and refcount table");
1469 } else if (ret
!= 0) {
1470 error_report("Huh, first cluster in empty image is already in use?");
1474 /* Okay, now that we have a valid image, let's give it the right size */
1475 ret
= bdrv_truncate(bs
, total_size
* BDRV_SECTOR_SIZE
);
1477 error_setg_errno(errp
, -ret
, "Could not resize image");
1481 /* Want a backing file? There you go.*/
1483 ret
= bdrv_change_backing_file(bs
, backing_file
, backing_format
);
1485 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
1486 "with format '%s'", backing_file
, backing_format
);
1491 /* And if we're supposed to preallocate metadata, do that now */
1493 BDRVQcowState
*s
= bs
->opaque
;
1494 qemu_co_mutex_lock(&s
->lock
);
1495 ret
= preallocate(bs
);
1496 qemu_co_mutex_unlock(&s
->lock
);
1498 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
1509 static int qcow2_create(const char *filename
, QEMUOptionParameter
*options
,
1512 const char *backing_file
= NULL
;
1513 const char *backing_fmt
= NULL
;
1514 uint64_t sectors
= 0;
1516 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
1519 Error
*local_err
= NULL
;
1522 /* Read out options */
1523 while (options
&& options
->name
) {
1524 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1525 sectors
= options
->value
.n
/ 512;
1526 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FILE
)) {
1527 backing_file
= options
->value
.s
;
1528 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FMT
)) {
1529 backing_fmt
= options
->value
.s
;
1530 } else if (!strcmp(options
->name
, BLOCK_OPT_ENCRYPT
)) {
1531 flags
|= options
->value
.n
? BLOCK_FLAG_ENCRYPT
: 0;
1532 } else if (!strcmp(options
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
1533 if (options
->value
.n
) {
1534 cluster_size
= options
->value
.n
;
1536 } else if (!strcmp(options
->name
, BLOCK_OPT_PREALLOC
)) {
1537 if (!options
->value
.s
|| !strcmp(options
->value
.s
, "off")) {
1539 } else if (!strcmp(options
->value
.s
, "metadata")) {
1542 error_setg(errp
, "Invalid preallocation mode: '%s'",
1546 } else if (!strcmp(options
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
1547 if (!options
->value
.s
) {
1548 /* keep the default */
1549 } else if (!strcmp(options
->value
.s
, "0.10")) {
1551 } else if (!strcmp(options
->value
.s
, "1.1")) {
1554 error_setg(errp
, "Invalid compatibility level: '%s'",
1558 } else if (!strcmp(options
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
1559 flags
|= options
->value
.n
? BLOCK_FLAG_LAZY_REFCOUNTS
: 0;
1564 if (backing_file
&& prealloc
) {
1565 error_setg(errp
, "Backing file and preallocation cannot be used at "
1570 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
1571 error_setg(errp
, "Lazy refcounts only supported with compatibility "
1572 "level 1.1 and above (use compat=1.1 or greater)");
1576 ret
= qcow2_create2(filename
, sectors
, backing_file
, backing_fmt
, flags
,
1577 cluster_size
, prealloc
, options
, version
, &local_err
);
1578 if (error_is_set(&local_err
)) {
1579 error_propagate(errp
, local_err
);
1584 static int qcow2_make_empty(BlockDriverState
*bs
)
1587 /* XXX: not correct */
1588 BDRVQcowState
*s
= bs
->opaque
;
1589 uint32_t l1_length
= s
->l1_size
* sizeof(uint64_t);
1592 memset(s
->l1_table
, 0, l1_length
);
1593 if (bdrv_pwrite(bs
->file
, s
->l1_table_offset
, s
->l1_table
, l1_length
) < 0)
1595 ret
= bdrv_truncate(bs
->file
, s
->l1_table_offset
+ l1_length
);
1604 static coroutine_fn
int qcow2_co_write_zeroes(BlockDriverState
*bs
,
1605 int64_t sector_num
, int nb_sectors
)
1608 BDRVQcowState
*s
= bs
->opaque
;
1610 /* Emulate misaligned zero writes */
1611 if (sector_num
% s
->cluster_sectors
|| nb_sectors
% s
->cluster_sectors
) {
1615 /* Whatever is left can use real zero clusters */
1616 qemu_co_mutex_lock(&s
->lock
);
1617 ret
= qcow2_zero_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1619 qemu_co_mutex_unlock(&s
->lock
);
1624 static coroutine_fn
int qcow2_co_discard(BlockDriverState
*bs
,
1625 int64_t sector_num
, int nb_sectors
)
1628 BDRVQcowState
*s
= bs
->opaque
;
1630 qemu_co_mutex_lock(&s
->lock
);
1631 ret
= qcow2_discard_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1632 nb_sectors
, QCOW2_DISCARD_REQUEST
);
1633 qemu_co_mutex_unlock(&s
->lock
);
1637 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
)
1639 BDRVQcowState
*s
= bs
->opaque
;
1640 int64_t new_l1_size
;
1644 error_report("The new size must be a multiple of 512");
1648 /* cannot proceed if image has snapshots */
1649 if (s
->nb_snapshots
) {
1650 error_report("Can't resize an image which has snapshots");
1654 /* shrinking is currently not supported */
1655 if (offset
< bs
->total_sectors
* 512) {
1656 error_report("qcow2 doesn't support shrinking images yet");
1660 new_l1_size
= size_to_l1(s
, offset
);
1661 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
1666 /* write updated header.size */
1667 offset
= cpu_to_be64(offset
);
1668 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
1669 &offset
, sizeof(uint64_t));
1674 s
->l1_vm_state_index
= new_l1_size
;
1678 /* XXX: put compressed sectors first, then all the cluster aligned
1679 tables to avoid losing bytes in alignment */
1680 static int qcow2_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1681 const uint8_t *buf
, int nb_sectors
)
1683 BDRVQcowState
*s
= bs
->opaque
;
1687 uint64_t cluster_offset
;
1689 if (nb_sectors
== 0) {
1690 /* align end of file to a sector boundary to ease reading with
1691 sector based I/Os */
1692 cluster_offset
= bdrv_getlength(bs
->file
);
1693 cluster_offset
= (cluster_offset
+ 511) & ~511;
1694 bdrv_truncate(bs
->file
, cluster_offset
);
1698 if (nb_sectors
!= s
->cluster_sectors
) {
1701 /* Zero-pad last write if image size is not cluster aligned */
1702 if (sector_num
+ nb_sectors
== bs
->total_sectors
&&
1703 nb_sectors
< s
->cluster_sectors
) {
1704 uint8_t *pad_buf
= qemu_blockalign(bs
, s
->cluster_size
);
1705 memset(pad_buf
, 0, s
->cluster_size
);
1706 memcpy(pad_buf
, buf
, nb_sectors
* BDRV_SECTOR_SIZE
);
1707 ret
= qcow2_write_compressed(bs
, sector_num
,
1708 pad_buf
, s
->cluster_sectors
);
1709 qemu_vfree(pad_buf
);
1714 out_buf
= g_malloc(s
->cluster_size
+ (s
->cluster_size
/ 1000) + 128);
1716 /* best compression, small window, no zlib header */
1717 memset(&strm
, 0, sizeof(strm
));
1718 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
1720 9, Z_DEFAULT_STRATEGY
);
1726 strm
.avail_in
= s
->cluster_size
;
1727 strm
.next_in
= (uint8_t *)buf
;
1728 strm
.avail_out
= s
->cluster_size
;
1729 strm
.next_out
= out_buf
;
1731 ret
= deflate(&strm
, Z_FINISH
);
1732 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
1737 out_len
= strm
.next_out
- out_buf
;
1741 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
1742 /* could not compress: write normal cluster */
1743 ret
= bdrv_write(bs
, sector_num
, buf
, s
->cluster_sectors
);
1748 cluster_offset
= qcow2_alloc_compressed_cluster_offset(bs
,
1749 sector_num
<< 9, out_len
);
1750 if (!cluster_offset
) {
1754 cluster_offset
&= s
->cluster_offset_mask
;
1756 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
1761 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
1762 ret
= bdrv_pwrite(bs
->file
, cluster_offset
, out_buf
, out_len
);
1774 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
1776 BDRVQcowState
*s
= bs
->opaque
;
1779 qemu_co_mutex_lock(&s
->lock
);
1780 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
1782 qemu_co_mutex_unlock(&s
->lock
);
1786 if (qcow2_need_accurate_refcounts(s
)) {
1787 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1789 qemu_co_mutex_unlock(&s
->lock
);
1793 qemu_co_mutex_unlock(&s
->lock
);
1798 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1800 BDRVQcowState
*s
= bs
->opaque
;
1801 bdi
->cluster_size
= s
->cluster_size
;
1802 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
1806 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
1808 BDRVQcowState
*s
= bs
->opaque
;
1809 ImageInfoSpecific
*spec_info
= g_new(ImageInfoSpecific
, 1);
1811 *spec_info
= (ImageInfoSpecific
){
1812 .kind
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
1814 .qcow2
= g_new(ImageInfoSpecificQCow2
, 1),
1817 if (s
->qcow_version
== 2) {
1818 *spec_info
->qcow2
= (ImageInfoSpecificQCow2
){
1819 .compat
= g_strdup("0.10"),
1821 } else if (s
->qcow_version
== 3) {
1822 *spec_info
->qcow2
= (ImageInfoSpecificQCow2
){
1823 .compat
= g_strdup("1.1"),
1824 .lazy_refcounts
= s
->compatible_features
&
1825 QCOW2_COMPAT_LAZY_REFCOUNTS
,
1826 .has_lazy_refcounts
= true,
1834 static void dump_refcounts(BlockDriverState
*bs
)
1836 BDRVQcowState
*s
= bs
->opaque
;
1837 int64_t nb_clusters
, k
, k1
, size
;
1840 size
= bdrv_getlength(bs
->file
);
1841 nb_clusters
= size_to_clusters(s
, size
);
1842 for(k
= 0; k
< nb_clusters
;) {
1844 refcount
= get_refcount(bs
, k
);
1846 while (k
< nb_clusters
&& get_refcount(bs
, k
) == refcount
)
1848 printf("%" PRId64
": refcount=%d nb=%" PRId64
"\n", k
, refcount
,
1854 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
1857 BDRVQcowState
*s
= bs
->opaque
;
1858 int growable
= bs
->growable
;
1861 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
1863 ret
= bdrv_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
, qiov
);
1864 bs
->growable
= growable
;
1869 static int qcow2_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1870 int64_t pos
, int size
)
1872 BDRVQcowState
*s
= bs
->opaque
;
1873 int growable
= bs
->growable
;
1874 bool zero_beyond_eof
= bs
->zero_beyond_eof
;
1877 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
1879 bs
->zero_beyond_eof
= false;
1880 ret
= bdrv_pread(bs
, qcow2_vm_state_offset(s
) + pos
, buf
, size
);
1881 bs
->growable
= growable
;
1882 bs
->zero_beyond_eof
= zero_beyond_eof
;
1888 * Downgrades an image's version. To achieve this, any incompatible features
1889 * have to be removed.
1891 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
)
1893 BDRVQcowState
*s
= bs
->opaque
;
1894 int current_version
= s
->qcow_version
;
1897 if (target_version
== current_version
) {
1899 } else if (target_version
> current_version
) {
1901 } else if (target_version
!= 2) {
1905 if (s
->refcount_order
!= 4) {
1906 /* we would have to convert the image to a refcount_order == 4 image
1907 * here; however, since qemu (at the time of writing this) does not
1908 * support anything different than 4 anyway, there is no point in doing
1909 * so right now; however, we should error out (if qemu supports this in
1910 * the future and this code has not been adapted) */
1911 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
1912 "currently not supported.");
1916 /* clear incompatible features */
1917 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
1918 ret
= qcow2_mark_clean(bs
);
1924 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
1925 * the first place; if that happens nonetheless, returning -ENOTSUP is the
1926 * best thing to do anyway */
1928 if (s
->incompatible_features
) {
1932 /* since we can ignore compatible features, we can set them to 0 as well */
1933 s
->compatible_features
= 0;
1934 /* if lazy refcounts have been used, they have already been fixed through
1935 * clearing the dirty flag */
1937 /* clearing autoclear features is trivial */
1938 s
->autoclear_features
= 0;
1940 ret
= qcow2_expand_zero_clusters(bs
);
1945 s
->qcow_version
= target_version
;
1946 ret
= qcow2_update_header(bs
);
1948 s
->qcow_version
= current_version
;
1954 static int qcow2_amend_options(BlockDriverState
*bs
,
1955 QEMUOptionParameter
*options
)
1957 BDRVQcowState
*s
= bs
->opaque
;
1958 int old_version
= s
->qcow_version
, new_version
= old_version
;
1959 uint64_t new_size
= 0;
1960 const char *backing_file
= NULL
, *backing_format
= NULL
;
1961 bool lazy_refcounts
= s
->use_lazy_refcounts
;
1965 for (i
= 0; options
[i
].name
; i
++)
1967 if (!options
[i
].assigned
) {
1968 /* only change explicitly defined options */
1972 if (!strcmp(options
[i
].name
, "compat")) {
1973 if (!options
[i
].value
.s
) {
1974 /* preserve default */
1975 } else if (!strcmp(options
[i
].value
.s
, "0.10")) {
1977 } else if (!strcmp(options
[i
].value
.s
, "1.1")) {
1980 fprintf(stderr
, "Unknown compatibility level %s.\n",
1981 options
[i
].value
.s
);
1984 } else if (!strcmp(options
[i
].name
, "preallocation")) {
1985 fprintf(stderr
, "Cannot change preallocation mode.\n");
1987 } else if (!strcmp(options
[i
].name
, "size")) {
1988 new_size
= options
[i
].value
.n
;
1989 } else if (!strcmp(options
[i
].name
, "backing_file")) {
1990 backing_file
= options
[i
].value
.s
;
1991 } else if (!strcmp(options
[i
].name
, "backing_fmt")) {
1992 backing_format
= options
[i
].value
.s
;
1993 } else if (!strcmp(options
[i
].name
, "encryption")) {
1994 if ((options
[i
].value
.n
!= !!s
->crypt_method
)) {
1995 fprintf(stderr
, "Changing the encryption flag is not "
1999 } else if (!strcmp(options
[i
].name
, "cluster_size")) {
2000 if (options
[i
].value
.n
!= s
->cluster_size
) {
2001 fprintf(stderr
, "Changing the cluster size is not "
2005 } else if (!strcmp(options
[i
].name
, "lazy_refcounts")) {
2006 lazy_refcounts
= options
[i
].value
.n
;
2008 /* if this assertion fails, this probably means a new option was
2009 * added without having it covered here */
2014 if (new_version
!= old_version
) {
2015 if (new_version
> old_version
) {
2017 s
->qcow_version
= new_version
;
2018 ret
= qcow2_update_header(bs
);
2020 s
->qcow_version
= old_version
;
2024 ret
= qcow2_downgrade(bs
, new_version
);
2031 if (backing_file
|| backing_format
) {
2032 ret
= qcow2_change_backing_file(bs
, backing_file
?: bs
->backing_file
,
2033 backing_format
?: bs
->backing_format
);
2039 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
2040 if (lazy_refcounts
) {
2041 if (s
->qcow_version
< 3) {
2042 fprintf(stderr
, "Lazy refcounts only supported with compatibility "
2043 "level 1.1 and above (use compat=1.1 or greater)\n");
2046 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2047 ret
= qcow2_update_header(bs
);
2049 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2052 s
->use_lazy_refcounts
= true;
2054 /* make image clean first */
2055 ret
= qcow2_mark_clean(bs
);
2059 /* now disallow lazy refcounts */
2060 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2061 ret
= qcow2_update_header(bs
);
2063 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2066 s
->use_lazy_refcounts
= false;
2071 ret
= bdrv_truncate(bs
, new_size
);
2080 static QEMUOptionParameter qcow2_create_options
[] = {
2082 .name
= BLOCK_OPT_SIZE
,
2084 .help
= "Virtual disk size"
2087 .name
= BLOCK_OPT_COMPAT_LEVEL
,
2089 .help
= "Compatibility level (0.10 or 1.1)"
2092 .name
= BLOCK_OPT_BACKING_FILE
,
2094 .help
= "File name of a base image"
2097 .name
= BLOCK_OPT_BACKING_FMT
,
2099 .help
= "Image format of the base image"
2102 .name
= BLOCK_OPT_ENCRYPT
,
2104 .help
= "Encrypt the image"
2107 .name
= BLOCK_OPT_CLUSTER_SIZE
,
2109 .help
= "qcow2 cluster size",
2110 .value
= { .n
= DEFAULT_CLUSTER_SIZE
},
2113 .name
= BLOCK_OPT_PREALLOC
,
2115 .help
= "Preallocation mode (allowed values: off, metadata)"
2118 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
2120 .help
= "Postpone refcount updates",
2125 static BlockDriver bdrv_qcow2
= {
2126 .format_name
= "qcow2",
2127 .instance_size
= sizeof(BDRVQcowState
),
2128 .bdrv_probe
= qcow2_probe
,
2129 .bdrv_open
= qcow2_open
,
2130 .bdrv_close
= qcow2_close
,
2131 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
2132 .bdrv_create
= qcow2_create
,
2133 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
2134 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
2135 .bdrv_set_key
= qcow2_set_key
,
2136 .bdrv_make_empty
= qcow2_make_empty
,
2138 .bdrv_co_readv
= qcow2_co_readv
,
2139 .bdrv_co_writev
= qcow2_co_writev
,
2140 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
2142 .bdrv_co_write_zeroes
= qcow2_co_write_zeroes
,
2143 .bdrv_co_discard
= qcow2_co_discard
,
2144 .bdrv_truncate
= qcow2_truncate
,
2145 .bdrv_write_compressed
= qcow2_write_compressed
,
2147 .bdrv_snapshot_create
= qcow2_snapshot_create
,
2148 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
2149 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
2150 .bdrv_snapshot_list
= qcow2_snapshot_list
,
2151 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
2152 .bdrv_get_info
= qcow2_get_info
,
2153 .bdrv_get_specific_info
= qcow2_get_specific_info
,
2155 .bdrv_save_vmstate
= qcow2_save_vmstate
,
2156 .bdrv_load_vmstate
= qcow2_load_vmstate
,
2158 .bdrv_change_backing_file
= qcow2_change_backing_file
,
2160 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
2162 .create_options
= qcow2_create_options
,
2163 .bdrv_check
= qcow2_check
,
2164 .bdrv_amend_options
= qcow2_amend_options
,
2167 static void bdrv_qcow2_init(void)
2169 bdrv_register(&bdrv_qcow2
);
2172 block_init(bdrv_qcow2_init
);