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.
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);
636 if (s
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
637 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
638 "qemu 1.1 compatibility level");
645 BdrvCheckResult result
= {0};
646 qcow2_check_refcounts(bs
, &result
, 0);
652 g_free(s
->unknown_header_fields
);
653 cleanup_unknown_header_ext(bs
);
654 qcow2_free_snapshots(bs
);
655 qcow2_refcount_close(bs
);
657 /* else pre-write overlap checks in cache_destroy may crash */
659 if (s
->l2_table_cache
) {
660 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
662 g_free(s
->cluster_cache
);
663 qemu_vfree(s
->cluster_data
);
667 static int qcow2_set_key(BlockDriverState
*bs
, const char *key
)
669 BDRVQcowState
*s
= bs
->opaque
;
673 memset(keybuf
, 0, 16);
677 /* XXX: we could compress the chars to 7 bits to increase
679 for(i
= 0;i
< len
;i
++) {
682 s
->crypt_method
= s
->crypt_method_header
;
684 if (AES_set_encrypt_key(keybuf
, 128, &s
->aes_encrypt_key
) != 0)
686 if (AES_set_decrypt_key(keybuf
, 128, &s
->aes_decrypt_key
) != 0)
696 AES_encrypt(in
, tmp
, &s
->aes_encrypt_key
);
697 AES_decrypt(tmp
, out
, &s
->aes_decrypt_key
);
698 for(i
= 0; i
< 16; i
++)
699 printf(" %02x", tmp
[i
]);
701 for(i
= 0; i
< 16; i
++)
702 printf(" %02x", out
[i
]);
709 /* We have nothing to do for QCOW2 reopen, stubs just return
711 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
712 BlockReopenQueue
*queue
, Error
**errp
)
717 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
718 int64_t sector_num
, int nb_sectors
, int *pnum
)
720 BDRVQcowState
*s
= bs
->opaque
;
721 uint64_t cluster_offset
;
722 int index_in_cluster
, ret
;
726 qemu_co_mutex_lock(&s
->lock
);
727 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9, pnum
, &cluster_offset
);
728 qemu_co_mutex_unlock(&s
->lock
);
733 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
735 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
736 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
737 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
739 if (ret
== QCOW2_CLUSTER_ZERO
) {
740 status
|= BDRV_BLOCK_ZERO
;
741 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
742 status
|= BDRV_BLOCK_DATA
;
747 /* handle reading after the end of the backing file */
748 int qcow2_backing_read1(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
749 int64_t sector_num
, int nb_sectors
)
752 if ((sector_num
+ nb_sectors
) <= bs
->total_sectors
)
754 if (sector_num
>= bs
->total_sectors
)
757 n1
= bs
->total_sectors
- sector_num
;
759 qemu_iovec_memset(qiov
, 512 * n1
, 0, 512 * (nb_sectors
- n1
));
764 static coroutine_fn
int qcow2_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
765 int remaining_sectors
, QEMUIOVector
*qiov
)
767 BDRVQcowState
*s
= bs
->opaque
;
768 int index_in_cluster
, n1
;
770 int cur_nr_sectors
; /* number of sectors in current iteration */
771 uint64_t cluster_offset
= 0;
772 uint64_t bytes_done
= 0;
773 QEMUIOVector hd_qiov
;
774 uint8_t *cluster_data
= NULL
;
776 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
778 qemu_co_mutex_lock(&s
->lock
);
780 while (remaining_sectors
!= 0) {
782 /* prepare next request */
783 cur_nr_sectors
= remaining_sectors
;
784 if (s
->crypt_method
) {
785 cur_nr_sectors
= MIN(cur_nr_sectors
,
786 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
789 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9,
790 &cur_nr_sectors
, &cluster_offset
);
795 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
797 qemu_iovec_reset(&hd_qiov
);
798 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
799 cur_nr_sectors
* 512);
802 case QCOW2_CLUSTER_UNALLOCATED
:
804 if (bs
->backing_hd
) {
805 /* read from the base image */
806 n1
= qcow2_backing_read1(bs
->backing_hd
, &hd_qiov
,
807 sector_num
, cur_nr_sectors
);
809 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
810 qemu_co_mutex_unlock(&s
->lock
);
811 ret
= bdrv_co_readv(bs
->backing_hd
, sector_num
,
813 qemu_co_mutex_lock(&s
->lock
);
819 /* Note: in this case, no need to wait */
820 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
824 case QCOW2_CLUSTER_ZERO
:
825 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
828 case QCOW2_CLUSTER_COMPRESSED
:
829 /* add AIO support for compressed blocks ? */
830 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
835 qemu_iovec_from_buf(&hd_qiov
, 0,
836 s
->cluster_cache
+ index_in_cluster
* 512,
837 512 * cur_nr_sectors
);
840 case QCOW2_CLUSTER_NORMAL
:
841 if ((cluster_offset
& 511) != 0) {
846 if (s
->crypt_method
) {
848 * For encrypted images, read everything into a temporary
849 * contiguous buffer on which the AES functions can work.
853 qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
856 assert(cur_nr_sectors
<=
857 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
858 qemu_iovec_reset(&hd_qiov
);
859 qemu_iovec_add(&hd_qiov
, cluster_data
,
860 512 * cur_nr_sectors
);
863 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
864 qemu_co_mutex_unlock(&s
->lock
);
865 ret
= bdrv_co_readv(bs
->file
,
866 (cluster_offset
>> 9) + index_in_cluster
,
867 cur_nr_sectors
, &hd_qiov
);
868 qemu_co_mutex_lock(&s
->lock
);
872 if (s
->crypt_method
) {
873 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
874 cluster_data
, cur_nr_sectors
, 0, &s
->aes_decrypt_key
);
875 qemu_iovec_from_buf(qiov
, bytes_done
,
876 cluster_data
, 512 * cur_nr_sectors
);
881 g_assert_not_reached();
886 remaining_sectors
-= cur_nr_sectors
;
887 sector_num
+= cur_nr_sectors
;
888 bytes_done
+= cur_nr_sectors
* 512;
893 qemu_co_mutex_unlock(&s
->lock
);
895 qemu_iovec_destroy(&hd_qiov
);
896 qemu_vfree(cluster_data
);
901 static coroutine_fn
int qcow2_co_writev(BlockDriverState
*bs
,
903 int remaining_sectors
,
906 BDRVQcowState
*s
= bs
->opaque
;
907 int index_in_cluster
;
910 int cur_nr_sectors
; /* number of sectors in current iteration */
911 uint64_t cluster_offset
;
912 QEMUIOVector hd_qiov
;
913 uint64_t bytes_done
= 0;
914 uint8_t *cluster_data
= NULL
;
915 QCowL2Meta
*l2meta
= NULL
;
917 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num
,
920 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
922 s
->cluster_cache_offset
= -1; /* disable compressed cache */
924 qemu_co_mutex_lock(&s
->lock
);
926 while (remaining_sectors
!= 0) {
930 trace_qcow2_writev_start_part(qemu_coroutine_self());
931 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
932 n_end
= index_in_cluster
+ remaining_sectors
;
933 if (s
->crypt_method
&&
934 n_end
> QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
) {
935 n_end
= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
;
938 ret
= qcow2_alloc_cluster_offset(bs
, sector_num
<< 9,
939 index_in_cluster
, n_end
, &cur_nr_sectors
, &cluster_offset
, &l2meta
);
944 assert((cluster_offset
& 511) == 0);
946 qemu_iovec_reset(&hd_qiov
);
947 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
948 cur_nr_sectors
* 512);
950 if (s
->crypt_method
) {
952 cluster_data
= qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
*
956 assert(hd_qiov
.size
<=
957 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
958 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
960 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
961 cluster_data
, cur_nr_sectors
, 1, &s
->aes_encrypt_key
);
963 qemu_iovec_reset(&hd_qiov
);
964 qemu_iovec_add(&hd_qiov
, cluster_data
,
965 cur_nr_sectors
* 512);
968 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_DEFAULT
,
969 cluster_offset
+ index_in_cluster
* BDRV_SECTOR_SIZE
,
970 cur_nr_sectors
* BDRV_SECTOR_SIZE
);
975 qemu_co_mutex_unlock(&s
->lock
);
976 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
977 trace_qcow2_writev_data(qemu_coroutine_self(),
978 (cluster_offset
>> 9) + index_in_cluster
);
979 ret
= bdrv_co_writev(bs
->file
,
980 (cluster_offset
>> 9) + index_in_cluster
,
981 cur_nr_sectors
, &hd_qiov
);
982 qemu_co_mutex_lock(&s
->lock
);
987 while (l2meta
!= NULL
) {
990 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
995 /* Take the request off the list of running requests */
996 if (l2meta
->nb_clusters
!= 0) {
997 QLIST_REMOVE(l2meta
, next_in_flight
);
1000 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1002 next
= l2meta
->next
;
1007 remaining_sectors
-= cur_nr_sectors
;
1008 sector_num
+= cur_nr_sectors
;
1009 bytes_done
+= cur_nr_sectors
* 512;
1010 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors
);
1015 qemu_co_mutex_unlock(&s
->lock
);
1017 while (l2meta
!= NULL
) {
1020 if (l2meta
->nb_clusters
!= 0) {
1021 QLIST_REMOVE(l2meta
, next_in_flight
);
1023 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1025 next
= l2meta
->next
;
1030 qemu_iovec_destroy(&hd_qiov
);
1031 qemu_vfree(cluster_data
);
1032 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
1037 static void qcow2_close(BlockDriverState
*bs
)
1039 BDRVQcowState
*s
= bs
->opaque
;
1040 g_free(s
->l1_table
);
1041 /* else pre-write overlap checks in cache_destroy may crash */
1044 qcow2_cache_flush(bs
, s
->l2_table_cache
);
1045 qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1047 qcow2_mark_clean(bs
);
1049 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
1050 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
1052 g_free(s
->unknown_header_fields
);
1053 cleanup_unknown_header_ext(bs
);
1055 g_free(s
->cluster_cache
);
1056 qemu_vfree(s
->cluster_data
);
1057 qcow2_refcount_close(bs
);
1058 qcow2_free_snapshots(bs
);
1061 static void qcow2_invalidate_cache(BlockDriverState
*bs
)
1063 BDRVQcowState
*s
= bs
->opaque
;
1064 int flags
= s
->flags
;
1065 AES_KEY aes_encrypt_key
;
1066 AES_KEY aes_decrypt_key
;
1067 uint32_t crypt_method
= 0;
1071 * Backing files are read-only which makes all of their metadata immutable,
1072 * that means we don't have to worry about reopening them here.
1075 if (s
->crypt_method
) {
1076 crypt_method
= s
->crypt_method
;
1077 memcpy(&aes_encrypt_key
, &s
->aes_encrypt_key
, sizeof(aes_encrypt_key
));
1078 memcpy(&aes_decrypt_key
, &s
->aes_decrypt_key
, sizeof(aes_decrypt_key
));
1083 options
= qdict_new();
1084 qdict_put(options
, QCOW2_OPT_LAZY_REFCOUNTS
,
1085 qbool_from_int(s
->use_lazy_refcounts
));
1087 memset(s
, 0, sizeof(BDRVQcowState
));
1088 qcow2_open(bs
, options
, flags
, NULL
);
1093 s
->crypt_method
= crypt_method
;
1094 memcpy(&s
->aes_encrypt_key
, &aes_encrypt_key
, sizeof(aes_encrypt_key
));
1095 memcpy(&s
->aes_decrypt_key
, &aes_decrypt_key
, sizeof(aes_decrypt_key
));
1099 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
1100 size_t len
, size_t buflen
)
1102 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
1103 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
1105 if (buflen
< ext_len
) {
1109 *ext_backing_fmt
= (QCowExtension
) {
1110 .magic
= cpu_to_be32(magic
),
1111 .len
= cpu_to_be32(len
),
1113 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
1119 * Updates the qcow2 header, including the variable length parts of it, i.e.
1120 * the backing file name and all extensions. qcow2 was not designed to allow
1121 * such changes, so if we run out of space (we can only use the first cluster)
1122 * this function may fail.
1124 * Returns 0 on success, -errno in error cases.
1126 int qcow2_update_header(BlockDriverState
*bs
)
1128 BDRVQcowState
*s
= bs
->opaque
;
1131 size_t buflen
= s
->cluster_size
;
1133 uint64_t total_size
;
1134 uint32_t refcount_table_clusters
;
1135 size_t header_length
;
1136 Qcow2UnknownHeaderExtension
*uext
;
1138 buf
= qemu_blockalign(bs
, buflen
);
1140 /* Header structure */
1141 header
= (QCowHeader
*) buf
;
1143 if (buflen
< sizeof(*header
)) {
1148 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
1149 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1150 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
1152 *header
= (QCowHeader
) {
1153 /* Version 2 fields */
1154 .magic
= cpu_to_be32(QCOW_MAGIC
),
1155 .version
= cpu_to_be32(s
->qcow_version
),
1156 .backing_file_offset
= 0,
1157 .backing_file_size
= 0,
1158 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
1159 .size
= cpu_to_be64(total_size
),
1160 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
1161 .l1_size
= cpu_to_be32(s
->l1_size
),
1162 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
1163 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
1164 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
1165 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
1166 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
1168 /* Version 3 fields */
1169 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
1170 .compatible_features
= cpu_to_be64(s
->compatible_features
),
1171 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
1172 .refcount_order
= cpu_to_be32(s
->refcount_order
),
1173 .header_length
= cpu_to_be32(header_length
),
1176 /* For older versions, write a shorter header */
1177 switch (s
->qcow_version
) {
1179 ret
= offsetof(QCowHeader
, incompatible_features
);
1182 ret
= sizeof(*header
);
1191 memset(buf
, 0, buflen
);
1193 /* Preserve any unknown field in the header */
1194 if (s
->unknown_header_fields_size
) {
1195 if (buflen
< s
->unknown_header_fields_size
) {
1200 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
1201 buf
+= s
->unknown_header_fields_size
;
1202 buflen
-= s
->unknown_header_fields_size
;
1205 /* Backing file format header extension */
1206 if (*bs
->backing_format
) {
1207 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
1208 bs
->backing_format
, strlen(bs
->backing_format
),
1219 Qcow2Feature features
[] = {
1221 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1222 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
1223 .name
= "dirty bit",
1226 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1227 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
1228 .name
= "corrupt bit",
1231 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
1232 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
1233 .name
= "lazy refcounts",
1237 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
1238 features
, sizeof(features
), buflen
);
1245 /* Keep unknown header extensions */
1246 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
1247 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
1256 /* End of header extensions */
1257 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
1265 /* Backing file name */
1266 if (*bs
->backing_file
) {
1267 size_t backing_file_len
= strlen(bs
->backing_file
);
1269 if (buflen
< backing_file_len
) {
1274 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1275 strncpy(buf
, bs
->backing_file
, buflen
);
1277 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
1278 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
1281 /* Write the new header */
1282 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
1293 static int qcow2_change_backing_file(BlockDriverState
*bs
,
1294 const char *backing_file
, const char *backing_fmt
)
1296 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
1297 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
1299 return qcow2_update_header(bs
);
1302 static int preallocate(BlockDriverState
*bs
)
1304 uint64_t nb_sectors
;
1306 uint64_t host_offset
= 0;
1311 nb_sectors
= bdrv_getlength(bs
) >> 9;
1314 while (nb_sectors
) {
1315 num
= MIN(nb_sectors
, INT_MAX
>> 9);
1316 ret
= qcow2_alloc_cluster_offset(bs
, offset
, 0, num
, &num
,
1317 &host_offset
, &meta
);
1322 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
1324 qcow2_free_any_clusters(bs
, meta
->alloc_offset
, meta
->nb_clusters
,
1325 QCOW2_DISCARD_NEVER
);
1329 /* There are no dependent requests, but we need to remove our request
1330 * from the list of in-flight requests */
1332 QLIST_REMOVE(meta
, next_in_flight
);
1335 /* TODO Preallocate data if requested */
1342 * It is expected that the image file is large enough to actually contain
1343 * all of the allocated clusters (otherwise we get failing reads after
1344 * EOF). Extend the image to the last allocated sector.
1346 if (host_offset
!= 0) {
1348 memset(buf
, 0, 512);
1349 ret
= bdrv_write(bs
->file
, (host_offset
>> 9) + num
- 1, buf
, 1);
1358 static int qcow2_create2(const char *filename
, int64_t total_size
,
1359 const char *backing_file
, const char *backing_format
,
1360 int flags
, size_t cluster_size
, int prealloc
,
1361 QEMUOptionParameter
*options
, int version
,
1364 /* Calculate cluster_bits */
1366 cluster_bits
= ffs(cluster_size
) - 1;
1367 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
1368 (1 << cluster_bits
) != cluster_size
)
1370 error_setg(errp
, "Cluster size must be a power of two between %d and "
1371 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
1376 * Open the image file and write a minimal qcow2 header.
1378 * We keep things simple and start with a zero-sized image. We also
1379 * do without refcount blocks or a L1 table for now. We'll fix the
1380 * inconsistency later.
1382 * We do need a refcount table because growing the refcount table means
1383 * allocating two new refcount blocks - the seconds of which would be at
1384 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1385 * size for any qcow2 image.
1387 BlockDriverState
* bs
;
1389 uint8_t* refcount_table
;
1390 Error
*local_err
= NULL
;
1393 ret
= bdrv_create_file(filename
, options
, &local_err
);
1395 error_propagate(errp
, local_err
);
1399 ret
= bdrv_file_open(&bs
, filename
, NULL
, BDRV_O_RDWR
, &local_err
);
1401 error_propagate(errp
, local_err
);
1405 /* Write the header */
1406 memset(&header
, 0, sizeof(header
));
1407 header
.magic
= cpu_to_be32(QCOW_MAGIC
);
1408 header
.version
= cpu_to_be32(version
);
1409 header
.cluster_bits
= cpu_to_be32(cluster_bits
);
1410 header
.size
= cpu_to_be64(0);
1411 header
.l1_table_offset
= cpu_to_be64(0);
1412 header
.l1_size
= cpu_to_be32(0);
1413 header
.refcount_table_offset
= cpu_to_be64(cluster_size
);
1414 header
.refcount_table_clusters
= cpu_to_be32(1);
1415 header
.refcount_order
= cpu_to_be32(3 + REFCOUNT_SHIFT
);
1416 header
.header_length
= cpu_to_be32(sizeof(header
));
1418 if (flags
& BLOCK_FLAG_ENCRYPT
) {
1419 header
.crypt_method
= cpu_to_be32(QCOW_CRYPT_AES
);
1421 header
.crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
1424 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
1425 header
.compatible_features
|=
1426 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
1429 ret
= bdrv_pwrite(bs
, 0, &header
, sizeof(header
));
1431 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
1435 /* Write an empty refcount table */
1436 refcount_table
= g_malloc0(cluster_size
);
1437 ret
= bdrv_pwrite(bs
, cluster_size
, refcount_table
, cluster_size
);
1438 g_free(refcount_table
);
1441 error_setg_errno(errp
, -ret
, "Could not write refcount table");
1448 * And now open the image and make it consistent first (i.e. increase the
1449 * refcount of the cluster that is occupied by the header and the refcount
1452 BlockDriver
* drv
= bdrv_find_format("qcow2");
1453 assert(drv
!= NULL
);
1454 ret
= bdrv_open(bs
, filename
, NULL
,
1455 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_NO_FLUSH
, drv
, &local_err
);
1457 error_propagate(errp
, local_err
);
1461 ret
= qcow2_alloc_clusters(bs
, 2 * cluster_size
);
1463 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
1464 "header and refcount table");
1467 } else if (ret
!= 0) {
1468 error_report("Huh, first cluster in empty image is already in use?");
1472 /* Okay, now that we have a valid image, let's give it the right size */
1473 ret
= bdrv_truncate(bs
, total_size
* BDRV_SECTOR_SIZE
);
1475 error_setg_errno(errp
, -ret
, "Could not resize image");
1479 /* Want a backing file? There you go.*/
1481 ret
= bdrv_change_backing_file(bs
, backing_file
, backing_format
);
1483 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
1484 "with format '%s'", backing_file
, backing_format
);
1489 /* And if we're supposed to preallocate metadata, do that now */
1491 BDRVQcowState
*s
= bs
->opaque
;
1492 qemu_co_mutex_lock(&s
->lock
);
1493 ret
= preallocate(bs
);
1494 qemu_co_mutex_unlock(&s
->lock
);
1496 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
1507 static int qcow2_create(const char *filename
, QEMUOptionParameter
*options
,
1510 const char *backing_file
= NULL
;
1511 const char *backing_fmt
= NULL
;
1512 uint64_t sectors
= 0;
1514 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
1517 Error
*local_err
= NULL
;
1520 /* Read out options */
1521 while (options
&& options
->name
) {
1522 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1523 sectors
= options
->value
.n
/ 512;
1524 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FILE
)) {
1525 backing_file
= options
->value
.s
;
1526 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FMT
)) {
1527 backing_fmt
= options
->value
.s
;
1528 } else if (!strcmp(options
->name
, BLOCK_OPT_ENCRYPT
)) {
1529 flags
|= options
->value
.n
? BLOCK_FLAG_ENCRYPT
: 0;
1530 } else if (!strcmp(options
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
1531 if (options
->value
.n
) {
1532 cluster_size
= options
->value
.n
;
1534 } else if (!strcmp(options
->name
, BLOCK_OPT_PREALLOC
)) {
1535 if (!options
->value
.s
|| !strcmp(options
->value
.s
, "off")) {
1537 } else if (!strcmp(options
->value
.s
, "metadata")) {
1540 error_setg(errp
, "Invalid preallocation mode: '%s'",
1544 } else if (!strcmp(options
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
1545 if (!options
->value
.s
) {
1546 /* keep the default */
1547 } else if (!strcmp(options
->value
.s
, "0.10")) {
1549 } else if (!strcmp(options
->value
.s
, "1.1")) {
1552 error_setg(errp
, "Invalid compatibility level: '%s'",
1556 } else if (!strcmp(options
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
1557 flags
|= options
->value
.n
? BLOCK_FLAG_LAZY_REFCOUNTS
: 0;
1562 if (backing_file
&& prealloc
) {
1563 error_setg(errp
, "Backing file and preallocation cannot be used at "
1568 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
1569 error_setg(errp
, "Lazy refcounts only supported with compatibility "
1570 "level 1.1 and above (use compat=1.1 or greater)");
1574 ret
= qcow2_create2(filename
, sectors
, backing_file
, backing_fmt
, flags
,
1575 cluster_size
, prealloc
, options
, version
, &local_err
);
1576 if (error_is_set(&local_err
)) {
1577 error_propagate(errp
, local_err
);
1582 static int qcow2_make_empty(BlockDriverState
*bs
)
1585 /* XXX: not correct */
1586 BDRVQcowState
*s
= bs
->opaque
;
1587 uint32_t l1_length
= s
->l1_size
* sizeof(uint64_t);
1590 memset(s
->l1_table
, 0, l1_length
);
1591 if (bdrv_pwrite(bs
->file
, s
->l1_table_offset
, s
->l1_table
, l1_length
) < 0)
1593 ret
= bdrv_truncate(bs
->file
, s
->l1_table_offset
+ l1_length
);
1602 static coroutine_fn
int qcow2_co_write_zeroes(BlockDriverState
*bs
,
1603 int64_t sector_num
, int nb_sectors
)
1606 BDRVQcowState
*s
= bs
->opaque
;
1608 /* Emulate misaligned zero writes */
1609 if (sector_num
% s
->cluster_sectors
|| nb_sectors
% s
->cluster_sectors
) {
1613 /* Whatever is left can use real zero clusters */
1614 qemu_co_mutex_lock(&s
->lock
);
1615 ret
= qcow2_zero_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1617 qemu_co_mutex_unlock(&s
->lock
);
1622 static coroutine_fn
int qcow2_co_discard(BlockDriverState
*bs
,
1623 int64_t sector_num
, int nb_sectors
)
1626 BDRVQcowState
*s
= bs
->opaque
;
1628 qemu_co_mutex_lock(&s
->lock
);
1629 ret
= qcow2_discard_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1630 nb_sectors
, QCOW2_DISCARD_REQUEST
);
1631 qemu_co_mutex_unlock(&s
->lock
);
1635 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
)
1637 BDRVQcowState
*s
= bs
->opaque
;
1638 int64_t new_l1_size
;
1642 error_report("The new size must be a multiple of 512");
1646 /* cannot proceed if image has snapshots */
1647 if (s
->nb_snapshots
) {
1648 error_report("Can't resize an image which has snapshots");
1652 /* shrinking is currently not supported */
1653 if (offset
< bs
->total_sectors
* 512) {
1654 error_report("qcow2 doesn't support shrinking images yet");
1658 new_l1_size
= size_to_l1(s
, offset
);
1659 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
1664 /* write updated header.size */
1665 offset
= cpu_to_be64(offset
);
1666 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
1667 &offset
, sizeof(uint64_t));
1672 s
->l1_vm_state_index
= new_l1_size
;
1676 /* XXX: put compressed sectors first, then all the cluster aligned
1677 tables to avoid losing bytes in alignment */
1678 static int qcow2_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1679 const uint8_t *buf
, int nb_sectors
)
1681 BDRVQcowState
*s
= bs
->opaque
;
1685 uint64_t cluster_offset
;
1687 if (nb_sectors
== 0) {
1688 /* align end of file to a sector boundary to ease reading with
1689 sector based I/Os */
1690 cluster_offset
= bdrv_getlength(bs
->file
);
1691 cluster_offset
= (cluster_offset
+ 511) & ~511;
1692 bdrv_truncate(bs
->file
, cluster_offset
);
1696 if (nb_sectors
!= s
->cluster_sectors
) {
1699 /* Zero-pad last write if image size is not cluster aligned */
1700 if (sector_num
+ nb_sectors
== bs
->total_sectors
&&
1701 nb_sectors
< s
->cluster_sectors
) {
1702 uint8_t *pad_buf
= qemu_blockalign(bs
, s
->cluster_size
);
1703 memset(pad_buf
, 0, s
->cluster_size
);
1704 memcpy(pad_buf
, buf
, nb_sectors
* BDRV_SECTOR_SIZE
);
1705 ret
= qcow2_write_compressed(bs
, sector_num
,
1706 pad_buf
, s
->cluster_sectors
);
1707 qemu_vfree(pad_buf
);
1712 out_buf
= g_malloc(s
->cluster_size
+ (s
->cluster_size
/ 1000) + 128);
1714 /* best compression, small window, no zlib header */
1715 memset(&strm
, 0, sizeof(strm
));
1716 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
1718 9, Z_DEFAULT_STRATEGY
);
1724 strm
.avail_in
= s
->cluster_size
;
1725 strm
.next_in
= (uint8_t *)buf
;
1726 strm
.avail_out
= s
->cluster_size
;
1727 strm
.next_out
= out_buf
;
1729 ret
= deflate(&strm
, Z_FINISH
);
1730 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
1735 out_len
= strm
.next_out
- out_buf
;
1739 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
1740 /* could not compress: write normal cluster */
1742 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_DEFAULT
,
1743 sector_num
* BDRV_SECTOR_SIZE
,
1744 s
->cluster_sectors
* BDRV_SECTOR_SIZE
);
1749 ret
= bdrv_write(bs
, sector_num
, buf
, s
->cluster_sectors
);
1754 cluster_offset
= qcow2_alloc_compressed_cluster_offset(bs
,
1755 sector_num
<< 9, out_len
);
1756 if (!cluster_offset
) {
1760 cluster_offset
&= s
->cluster_offset_mask
;
1762 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_DEFAULT
,
1763 cluster_offset
, out_len
);
1768 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
1769 ret
= bdrv_pwrite(bs
->file
, cluster_offset
, out_buf
, out_len
);
1781 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
1783 BDRVQcowState
*s
= bs
->opaque
;
1786 qemu_co_mutex_lock(&s
->lock
);
1787 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
1789 qemu_co_mutex_unlock(&s
->lock
);
1793 if (qcow2_need_accurate_refcounts(s
)) {
1794 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1796 qemu_co_mutex_unlock(&s
->lock
);
1800 qemu_co_mutex_unlock(&s
->lock
);
1805 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1807 BDRVQcowState
*s
= bs
->opaque
;
1808 bdi
->cluster_size
= s
->cluster_size
;
1809 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
1814 static void dump_refcounts(BlockDriverState
*bs
)
1816 BDRVQcowState
*s
= bs
->opaque
;
1817 int64_t nb_clusters
, k
, k1
, size
;
1820 size
= bdrv_getlength(bs
->file
);
1821 nb_clusters
= size_to_clusters(s
, size
);
1822 for(k
= 0; k
< nb_clusters
;) {
1824 refcount
= get_refcount(bs
, k
);
1826 while (k
< nb_clusters
&& get_refcount(bs
, k
) == refcount
)
1828 printf("%" PRId64
": refcount=%d nb=%" PRId64
"\n", k
, refcount
,
1834 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
1837 BDRVQcowState
*s
= bs
->opaque
;
1838 int growable
= bs
->growable
;
1841 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
1843 ret
= bdrv_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
, qiov
);
1844 bs
->growable
= growable
;
1849 static int qcow2_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1850 int64_t pos
, int size
)
1852 BDRVQcowState
*s
= bs
->opaque
;
1853 int growable
= bs
->growable
;
1854 bool zero_beyond_eof
= bs
->zero_beyond_eof
;
1857 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
1859 bs
->zero_beyond_eof
= false;
1860 ret
= bdrv_pread(bs
, qcow2_vm_state_offset(s
) + pos
, buf
, size
);
1861 bs
->growable
= growable
;
1862 bs
->zero_beyond_eof
= zero_beyond_eof
;
1868 * Downgrades an image's version. To achieve this, any incompatible features
1869 * have to be removed.
1871 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
)
1873 BDRVQcowState
*s
= bs
->opaque
;
1874 int current_version
= s
->qcow_version
;
1877 if (target_version
== current_version
) {
1879 } else if (target_version
> current_version
) {
1881 } else if (target_version
!= 2) {
1885 if (s
->refcount_order
!= 4) {
1886 /* we would have to convert the image to a refcount_order == 4 image
1887 * here; however, since qemu (at the time of writing this) does not
1888 * support anything different than 4 anyway, there is no point in doing
1889 * so right now; however, we should error out (if qemu supports this in
1890 * the future and this code has not been adapted) */
1891 error_report("qcow2_downgrade: Image refcount orders other than 4 are"
1892 "currently not supported.");
1896 /* clear incompatible features */
1897 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
1898 ret
= qcow2_mark_clean(bs
);
1904 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
1905 * the first place; if that happens nonetheless, returning -ENOTSUP is the
1906 * best thing to do anyway */
1908 if (s
->incompatible_features
) {
1912 /* since we can ignore compatible features, we can set them to 0 as well */
1913 s
->compatible_features
= 0;
1914 /* if lazy refcounts have been used, they have already been fixed through
1915 * clearing the dirty flag */
1917 /* clearing autoclear features is trivial */
1918 s
->autoclear_features
= 0;
1920 ret
= qcow2_expand_zero_clusters(bs
);
1925 s
->qcow_version
= target_version
;
1926 ret
= qcow2_update_header(bs
);
1928 s
->qcow_version
= current_version
;
1934 static int qcow2_amend_options(BlockDriverState
*bs
,
1935 QEMUOptionParameter
*options
)
1937 BDRVQcowState
*s
= bs
->opaque
;
1938 int old_version
= s
->qcow_version
, new_version
= old_version
;
1939 uint64_t new_size
= 0;
1940 const char *backing_file
= NULL
, *backing_format
= NULL
;
1941 bool lazy_refcounts
= s
->use_lazy_refcounts
;
1945 for (i
= 0; options
[i
].name
; i
++)
1947 if (!options
[i
].assigned
) {
1948 /* only change explicitly defined options */
1952 if (!strcmp(options
[i
].name
, "compat")) {
1953 if (!options
[i
].value
.s
) {
1954 /* preserve default */
1955 } else if (!strcmp(options
[i
].value
.s
, "0.10")) {
1957 } else if (!strcmp(options
[i
].value
.s
, "1.1")) {
1960 fprintf(stderr
, "Unknown compatibility level %s.\n",
1961 options
[i
].value
.s
);
1964 } else if (!strcmp(options
[i
].name
, "preallocation")) {
1965 fprintf(stderr
, "Cannot change preallocation mode.\n");
1967 } else if (!strcmp(options
[i
].name
, "size")) {
1968 new_size
= options
[i
].value
.n
;
1969 } else if (!strcmp(options
[i
].name
, "backing_file")) {
1970 backing_file
= options
[i
].value
.s
;
1971 } else if (!strcmp(options
[i
].name
, "backing_fmt")) {
1972 backing_format
= options
[i
].value
.s
;
1973 } else if (!strcmp(options
[i
].name
, "encryption")) {
1974 if ((options
[i
].value
.n
!= !!s
->crypt_method
)) {
1975 fprintf(stderr
, "Changing the encryption flag is not "
1979 } else if (!strcmp(options
[i
].name
, "cluster_size")) {
1980 if (options
[i
].value
.n
!= s
->cluster_size
) {
1981 fprintf(stderr
, "Changing the cluster size is not "
1985 } else if (!strcmp(options
[i
].name
, "lazy_refcounts")) {
1986 lazy_refcounts
= options
[i
].value
.n
;
1988 /* if this assertion fails, this probably means a new option was
1989 * added without having it covered here */
1994 if (new_version
!= old_version
) {
1995 if (new_version
> old_version
) {
1997 s
->qcow_version
= new_version
;
1998 ret
= qcow2_update_header(bs
);
2000 s
->qcow_version
= old_version
;
2004 ret
= qcow2_downgrade(bs
, new_version
);
2011 if (backing_file
|| backing_format
) {
2012 ret
= qcow2_change_backing_file(bs
, backing_file
?: bs
->backing_file
,
2013 backing_format
?: bs
->backing_format
);
2019 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
2020 if (lazy_refcounts
) {
2021 if (s
->qcow_version
< 3) {
2022 fprintf(stderr
, "Lazy refcounts only supported with compatibility "
2023 "level 1.1 and above (use compat=1.1 or greater)\n");
2026 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2027 ret
= qcow2_update_header(bs
);
2029 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2032 s
->use_lazy_refcounts
= true;
2034 /* make image clean first */
2035 ret
= qcow2_mark_clean(bs
);
2039 /* now disallow lazy refcounts */
2040 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
2041 ret
= qcow2_update_header(bs
);
2043 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
2046 s
->use_lazy_refcounts
= false;
2051 ret
= bdrv_truncate(bs
, new_size
);
2060 static QEMUOptionParameter qcow2_create_options
[] = {
2062 .name
= BLOCK_OPT_SIZE
,
2064 .help
= "Virtual disk size"
2067 .name
= BLOCK_OPT_COMPAT_LEVEL
,
2069 .help
= "Compatibility level (0.10 or 1.1)"
2072 .name
= BLOCK_OPT_BACKING_FILE
,
2074 .help
= "File name of a base image"
2077 .name
= BLOCK_OPT_BACKING_FMT
,
2079 .help
= "Image format of the base image"
2082 .name
= BLOCK_OPT_ENCRYPT
,
2084 .help
= "Encrypt the image"
2087 .name
= BLOCK_OPT_CLUSTER_SIZE
,
2089 .help
= "qcow2 cluster size",
2090 .value
= { .n
= DEFAULT_CLUSTER_SIZE
},
2093 .name
= BLOCK_OPT_PREALLOC
,
2095 .help
= "Preallocation mode (allowed values: off, metadata)"
2098 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
2100 .help
= "Postpone refcount updates",
2105 static BlockDriver bdrv_qcow2
= {
2106 .format_name
= "qcow2",
2107 .instance_size
= sizeof(BDRVQcowState
),
2108 .bdrv_probe
= qcow2_probe
,
2109 .bdrv_open
= qcow2_open
,
2110 .bdrv_close
= qcow2_close
,
2111 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
2112 .bdrv_create
= qcow2_create
,
2113 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
2114 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
2115 .bdrv_set_key
= qcow2_set_key
,
2116 .bdrv_make_empty
= qcow2_make_empty
,
2118 .bdrv_co_readv
= qcow2_co_readv
,
2119 .bdrv_co_writev
= qcow2_co_writev
,
2120 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
2122 .bdrv_co_write_zeroes
= qcow2_co_write_zeroes
,
2123 .bdrv_co_discard
= qcow2_co_discard
,
2124 .bdrv_truncate
= qcow2_truncate
,
2125 .bdrv_write_compressed
= qcow2_write_compressed
,
2127 .bdrv_snapshot_create
= qcow2_snapshot_create
,
2128 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
2129 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
2130 .bdrv_snapshot_list
= qcow2_snapshot_list
,
2131 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
2132 .bdrv_get_info
= qcow2_get_info
,
2134 .bdrv_save_vmstate
= qcow2_save_vmstate
,
2135 .bdrv_load_vmstate
= qcow2_load_vmstate
,
2137 .bdrv_change_backing_file
= qcow2_change_backing_file
,
2139 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
2141 .create_options
= qcow2_create_options
,
2142 .bdrv_check
= qcow2_check
,
2143 .bdrv_amend_options
= qcow2_amend_options
,
2146 static void bdrv_qcow2_init(void)
2148 bdrv_register(&bdrv_qcow2
);
2151 block_init(bdrv_qcow2_init
);