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
)
84 BDRVQcowState
*s
= bs
->opaque
;
90 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
92 offset
= start_offset
;
93 while (offset
< end_offset
) {
97 if (offset
> s
->cluster_size
)
98 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
100 printf("attempting to read extended header in offset %lu\n", offset
);
103 if (bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
)) != sizeof(ext
)) {
104 fprintf(stderr
, "qcow2_read_extension: ERROR: "
105 "pread fail from offset %" PRIu64
"\n",
109 be32_to_cpus(&ext
.magic
);
110 be32_to_cpus(&ext
.len
);
111 offset
+= sizeof(ext
);
113 printf("ext.magic = 0x%x\n", ext
.magic
);
115 if (ext
.len
> end_offset
- offset
) {
116 error_report("Header extension too large");
121 case QCOW2_EXT_MAGIC_END
:
124 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
125 if (ext
.len
>= sizeof(bs
->backing_format
)) {
126 fprintf(stderr
, "ERROR: ext_backing_format: len=%u too large"
128 ext
.len
, sizeof(bs
->backing_format
));
131 if (bdrv_pread(bs
->file
, offset
, bs
->backing_format
,
134 bs
->backing_format
[ext
.len
] = '\0';
136 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
140 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
141 if (p_feature_table
!= NULL
) {
142 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
143 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
148 *p_feature_table
= feature_table
;
153 /* unknown magic - save it in case we need to rewrite the header */
155 Qcow2UnknownHeaderExtension
*uext
;
157 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
158 uext
->magic
= ext
.magic
;
160 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
162 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
170 offset
+= ((ext
.len
+ 7) & ~7);
176 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
178 BDRVQcowState
*s
= bs
->opaque
;
179 Qcow2UnknownHeaderExtension
*uext
, *next
;
181 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
182 QLIST_REMOVE(uext
, next
);
187 static void GCC_FMT_ATTR(2, 3) report_unsupported(BlockDriverState
*bs
,
188 const char *fmt
, ...)
194 vsnprintf(msg
, sizeof(msg
), fmt
, ap
);
197 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE
,
198 bs
->device_name
, "qcow2", msg
);
201 static void report_unsupported_feature(BlockDriverState
*bs
,
202 Qcow2Feature
*table
, uint64_t mask
)
204 while (table
&& table
->name
[0] != '\0') {
205 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
206 if (mask
& (1 << table
->bit
)) {
207 report_unsupported(bs
, "%.46s",table
->name
);
208 mask
&= ~(1 << table
->bit
);
215 report_unsupported(bs
, "Unknown incompatible feature: %" PRIx64
, mask
);
220 * Sets the dirty bit and flushes afterwards if necessary.
222 * The incompatible_features bit is only set if the image file header was
223 * updated successfully. Therefore it is not required to check the return
224 * value of this function.
226 int qcow2_mark_dirty(BlockDriverState
*bs
)
228 BDRVQcowState
*s
= bs
->opaque
;
232 assert(s
->qcow_version
>= 3);
234 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
235 return 0; /* already dirty */
238 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
239 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
244 ret
= bdrv_flush(bs
->file
);
249 /* Only treat image as dirty if the header was updated successfully */
250 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
255 * Clears the dirty bit and flushes before if necessary. Only call this
256 * function when there are no pending requests, it does not guard against
257 * concurrent requests dirtying the image.
259 static int qcow2_mark_clean(BlockDriverState
*bs
)
261 BDRVQcowState
*s
= bs
->opaque
;
263 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
264 int ret
= bdrv_flush(bs
);
269 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
270 return qcow2_update_header(bs
);
275 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
278 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
283 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
284 return qcow2_mark_clean(bs
);
289 static QemuOptsList qcow2_runtime_opts
= {
291 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
294 .name
= "lazy_refcounts",
295 .type
= QEMU_OPT_BOOL
,
296 .help
= "Postpone refcount updates",
299 .name
= QCOW2_OPT_DISCARD_REQUEST
,
300 .type
= QEMU_OPT_BOOL
,
301 .help
= "Pass guest discard requests to the layer below",
304 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
305 .type
= QEMU_OPT_BOOL
,
306 .help
= "Generate discard requests when snapshot related space "
310 .name
= QCOW2_OPT_DISCARD_OTHER
,
311 .type
= QEMU_OPT_BOOL
,
312 .help
= "Generate discard requests when other clusters are freed",
314 { /* end of list */ }
318 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
)
320 BDRVQcowState
*s
= bs
->opaque
;
324 Error
*local_err
= NULL
;
326 uint64_t l1_vm_state_index
;
328 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
332 be32_to_cpus(&header
.magic
);
333 be32_to_cpus(&header
.version
);
334 be64_to_cpus(&header
.backing_file_offset
);
335 be32_to_cpus(&header
.backing_file_size
);
336 be64_to_cpus(&header
.size
);
337 be32_to_cpus(&header
.cluster_bits
);
338 be32_to_cpus(&header
.crypt_method
);
339 be64_to_cpus(&header
.l1_table_offset
);
340 be32_to_cpus(&header
.l1_size
);
341 be64_to_cpus(&header
.refcount_table_offset
);
342 be32_to_cpus(&header
.refcount_table_clusters
);
343 be64_to_cpus(&header
.snapshots_offset
);
344 be32_to_cpus(&header
.nb_snapshots
);
346 if (header
.magic
!= QCOW_MAGIC
) {
350 if (header
.version
< 2 || header
.version
> 3) {
351 report_unsupported(bs
, "QCOW version %d", header
.version
);
356 s
->qcow_version
= header
.version
;
358 /* Initialise version 3 header fields */
359 if (header
.version
== 2) {
360 header
.incompatible_features
= 0;
361 header
.compatible_features
= 0;
362 header
.autoclear_features
= 0;
363 header
.refcount_order
= 4;
364 header
.header_length
= 72;
366 be64_to_cpus(&header
.incompatible_features
);
367 be64_to_cpus(&header
.compatible_features
);
368 be64_to_cpus(&header
.autoclear_features
);
369 be32_to_cpus(&header
.refcount_order
);
370 be32_to_cpus(&header
.header_length
);
373 if (header
.header_length
> sizeof(header
)) {
374 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
375 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
376 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
377 s
->unknown_header_fields_size
);
383 if (header
.backing_file_offset
) {
384 ext_end
= header
.backing_file_offset
;
386 ext_end
= 1 << header
.cluster_bits
;
389 /* Handle feature bits */
390 s
->incompatible_features
= header
.incompatible_features
;
391 s
->compatible_features
= header
.compatible_features
;
392 s
->autoclear_features
= header
.autoclear_features
;
394 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
395 void *feature_table
= NULL
;
396 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
398 report_unsupported_feature(bs
, feature_table
,
399 s
->incompatible_features
&
400 ~QCOW2_INCOMPAT_MASK
);
405 /* Check support for various header values */
406 if (header
.refcount_order
!= 4) {
407 report_unsupported(bs
, "%d bit reference counts",
408 1 << header
.refcount_order
);
413 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
414 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
418 if (header
.crypt_method
> QCOW_CRYPT_AES
) {
422 s
->crypt_method_header
= header
.crypt_method
;
423 if (s
->crypt_method_header
) {
426 s
->cluster_bits
= header
.cluster_bits
;
427 s
->cluster_size
= 1 << s
->cluster_bits
;
428 s
->cluster_sectors
= 1 << (s
->cluster_bits
- 9);
429 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
430 s
->l2_size
= 1 << s
->l2_bits
;
431 bs
->total_sectors
= header
.size
/ 512;
432 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
433 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
434 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
435 s
->refcount_table_offset
= header
.refcount_table_offset
;
436 s
->refcount_table_size
=
437 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
439 s
->snapshots_offset
= header
.snapshots_offset
;
440 s
->nb_snapshots
= header
.nb_snapshots
;
442 /* read the level 1 table */
443 s
->l1_size
= header
.l1_size
;
445 l1_vm_state_index
= size_to_l1(s
, header
.size
);
446 if (l1_vm_state_index
> INT_MAX
) {
450 s
->l1_vm_state_index
= l1_vm_state_index
;
452 /* the L1 table must contain at least enough entries to put
454 if (s
->l1_size
< s
->l1_vm_state_index
) {
458 s
->l1_table_offset
= header
.l1_table_offset
;
459 if (s
->l1_size
> 0) {
460 s
->l1_table
= g_malloc0(
461 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
462 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
463 s
->l1_size
* sizeof(uint64_t));
467 for(i
= 0;i
< s
->l1_size
; i
++) {
468 be64_to_cpus(&s
->l1_table
[i
]);
472 /* alloc L2 table/refcount block cache */
473 s
->l2_table_cache
= qcow2_cache_create(bs
, L2_CACHE_SIZE
);
474 s
->refcount_block_cache
= qcow2_cache_create(bs
, REFCOUNT_CACHE_SIZE
);
476 s
->cluster_cache
= g_malloc(s
->cluster_size
);
477 /* one more sector for decompressed data alignment */
478 s
->cluster_data
= qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
480 s
->cluster_cache_offset
= -1;
483 ret
= qcow2_refcount_init(bs
);
488 QLIST_INIT(&s
->cluster_allocs
);
490 /* read qcow2 extensions */
491 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
)) {
496 /* read the backing file name */
497 if (header
.backing_file_offset
!= 0) {
498 len
= header
.backing_file_size
;
502 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
503 bs
->backing_file
, len
);
507 bs
->backing_file
[len
] = '\0';
510 ret
= qcow2_read_snapshots(bs
);
515 /* Clear unknown autoclear feature bits */
516 if (!bs
->read_only
&& s
->autoclear_features
!= 0) {
517 s
->autoclear_features
= 0;
518 ret
= qcow2_update_header(bs
);
524 /* Initialise locks */
525 qemu_co_mutex_init(&s
->lock
);
527 /* Repair image if dirty */
528 if (!(flags
& BDRV_O_CHECK
) && !bs
->read_only
&&
529 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
530 BdrvCheckResult result
= {0};
532 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
);
538 /* Enable lazy_refcounts according to image and command line options */
539 opts
= qemu_opts_create_nofail(&qcow2_runtime_opts
);
540 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
541 if (error_is_set(&local_err
)) {
542 qerror_report_err(local_err
);
543 error_free(local_err
);
548 s
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
549 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
551 s
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
552 s
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
553 s
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
554 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
555 flags
& BDRV_O_UNMAP
);
556 s
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
557 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
558 s
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
559 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
563 if (s
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
564 qerror_report(ERROR_CLASS_GENERIC_ERROR
, "Lazy refcounts require "
565 "a qcow2 image with at least qemu 1.1 compatibility level");
572 BdrvCheckResult result
= {0};
573 qcow2_check_refcounts(bs
, &result
, 0);
579 g_free(s
->unknown_header_fields
);
580 cleanup_unknown_header_ext(bs
);
581 qcow2_free_snapshots(bs
);
582 qcow2_refcount_close(bs
);
584 if (s
->l2_table_cache
) {
585 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
587 g_free(s
->cluster_cache
);
588 qemu_vfree(s
->cluster_data
);
592 static int qcow2_set_key(BlockDriverState
*bs
, const char *key
)
594 BDRVQcowState
*s
= bs
->opaque
;
598 memset(keybuf
, 0, 16);
602 /* XXX: we could compress the chars to 7 bits to increase
604 for(i
= 0;i
< len
;i
++) {
607 s
->crypt_method
= s
->crypt_method_header
;
609 if (AES_set_encrypt_key(keybuf
, 128, &s
->aes_encrypt_key
) != 0)
611 if (AES_set_decrypt_key(keybuf
, 128, &s
->aes_decrypt_key
) != 0)
621 AES_encrypt(in
, tmp
, &s
->aes_encrypt_key
);
622 AES_decrypt(tmp
, out
, &s
->aes_decrypt_key
);
623 for(i
= 0; i
< 16; i
++)
624 printf(" %02x", tmp
[i
]);
626 for(i
= 0; i
< 16; i
++)
627 printf(" %02x", out
[i
]);
634 /* We have nothing to do for QCOW2 reopen, stubs just return
636 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
637 BlockReopenQueue
*queue
, Error
**errp
)
642 static int coroutine_fn
qcow2_co_is_allocated(BlockDriverState
*bs
,
643 int64_t sector_num
, int nb_sectors
, int *pnum
)
645 BDRVQcowState
*s
= bs
->opaque
;
646 uint64_t cluster_offset
;
650 /* FIXME We can get errors here, but the bdrv_co_is_allocated interface
651 * can't pass them on today */
652 qemu_co_mutex_lock(&s
->lock
);
653 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9, pnum
, &cluster_offset
);
654 qemu_co_mutex_unlock(&s
->lock
);
659 return (cluster_offset
!= 0) || (ret
== QCOW2_CLUSTER_ZERO
);
662 /* handle reading after the end of the backing file */
663 int qcow2_backing_read1(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
664 int64_t sector_num
, int nb_sectors
)
667 if ((sector_num
+ nb_sectors
) <= bs
->total_sectors
)
669 if (sector_num
>= bs
->total_sectors
)
672 n1
= bs
->total_sectors
- sector_num
;
674 qemu_iovec_memset(qiov
, 512 * n1
, 0, 512 * (nb_sectors
- n1
));
679 static coroutine_fn
int qcow2_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
680 int remaining_sectors
, QEMUIOVector
*qiov
)
682 BDRVQcowState
*s
= bs
->opaque
;
683 int index_in_cluster
, n1
;
685 int cur_nr_sectors
; /* number of sectors in current iteration */
686 uint64_t cluster_offset
= 0;
687 uint64_t bytes_done
= 0;
688 QEMUIOVector hd_qiov
;
689 uint8_t *cluster_data
= NULL
;
691 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
693 qemu_co_mutex_lock(&s
->lock
);
695 while (remaining_sectors
!= 0) {
697 /* prepare next request */
698 cur_nr_sectors
= remaining_sectors
;
699 if (s
->crypt_method
) {
700 cur_nr_sectors
= MIN(cur_nr_sectors
,
701 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
704 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< 9,
705 &cur_nr_sectors
, &cluster_offset
);
710 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
712 qemu_iovec_reset(&hd_qiov
);
713 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
714 cur_nr_sectors
* 512);
717 case QCOW2_CLUSTER_UNALLOCATED
:
719 if (bs
->backing_hd
) {
720 /* read from the base image */
721 n1
= qcow2_backing_read1(bs
->backing_hd
, &hd_qiov
,
722 sector_num
, cur_nr_sectors
);
724 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
725 qemu_co_mutex_unlock(&s
->lock
);
726 ret
= bdrv_co_readv(bs
->backing_hd
, sector_num
,
728 qemu_co_mutex_lock(&s
->lock
);
734 /* Note: in this case, no need to wait */
735 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
739 case QCOW2_CLUSTER_ZERO
:
740 qemu_iovec_memset(&hd_qiov
, 0, 0, 512 * cur_nr_sectors
);
743 case QCOW2_CLUSTER_COMPRESSED
:
744 /* add AIO support for compressed blocks ? */
745 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
750 qemu_iovec_from_buf(&hd_qiov
, 0,
751 s
->cluster_cache
+ index_in_cluster
* 512,
752 512 * cur_nr_sectors
);
755 case QCOW2_CLUSTER_NORMAL
:
756 if ((cluster_offset
& 511) != 0) {
761 if (s
->crypt_method
) {
763 * For encrypted images, read everything into a temporary
764 * contiguous buffer on which the AES functions can work.
768 qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
771 assert(cur_nr_sectors
<=
772 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
);
773 qemu_iovec_reset(&hd_qiov
);
774 qemu_iovec_add(&hd_qiov
, cluster_data
,
775 512 * cur_nr_sectors
);
778 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
779 qemu_co_mutex_unlock(&s
->lock
);
780 ret
= bdrv_co_readv(bs
->file
,
781 (cluster_offset
>> 9) + index_in_cluster
,
782 cur_nr_sectors
, &hd_qiov
);
783 qemu_co_mutex_lock(&s
->lock
);
787 if (s
->crypt_method
) {
788 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
789 cluster_data
, cur_nr_sectors
, 0, &s
->aes_decrypt_key
);
790 qemu_iovec_from_buf(qiov
, bytes_done
,
791 cluster_data
, 512 * cur_nr_sectors
);
796 g_assert_not_reached();
801 remaining_sectors
-= cur_nr_sectors
;
802 sector_num
+= cur_nr_sectors
;
803 bytes_done
+= cur_nr_sectors
* 512;
808 qemu_co_mutex_unlock(&s
->lock
);
810 qemu_iovec_destroy(&hd_qiov
);
811 qemu_vfree(cluster_data
);
816 static coroutine_fn
int qcow2_co_writev(BlockDriverState
*bs
,
818 int remaining_sectors
,
821 BDRVQcowState
*s
= bs
->opaque
;
822 int index_in_cluster
;
825 int cur_nr_sectors
; /* number of sectors in current iteration */
826 uint64_t cluster_offset
;
827 QEMUIOVector hd_qiov
;
828 uint64_t bytes_done
= 0;
829 uint8_t *cluster_data
= NULL
;
830 QCowL2Meta
*l2meta
= NULL
;
832 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num
,
835 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
837 s
->cluster_cache_offset
= -1; /* disable compressed cache */
839 qemu_co_mutex_lock(&s
->lock
);
841 while (remaining_sectors
!= 0) {
845 trace_qcow2_writev_start_part(qemu_coroutine_self());
846 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
847 n_end
= index_in_cluster
+ remaining_sectors
;
848 if (s
->crypt_method
&&
849 n_end
> QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
) {
850 n_end
= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_sectors
;
853 ret
= qcow2_alloc_cluster_offset(bs
, sector_num
<< 9,
854 index_in_cluster
, n_end
, &cur_nr_sectors
, &cluster_offset
, &l2meta
);
859 assert((cluster_offset
& 511) == 0);
861 qemu_iovec_reset(&hd_qiov
);
862 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
,
863 cur_nr_sectors
* 512);
865 if (s
->crypt_method
) {
867 cluster_data
= qemu_blockalign(bs
, QCOW_MAX_CRYPT_CLUSTERS
*
871 assert(hd_qiov
.size
<=
872 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
873 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
875 qcow2_encrypt_sectors(s
, sector_num
, cluster_data
,
876 cluster_data
, cur_nr_sectors
, 1, &s
->aes_encrypt_key
);
878 qemu_iovec_reset(&hd_qiov
);
879 qemu_iovec_add(&hd_qiov
, cluster_data
,
880 cur_nr_sectors
* 512);
883 qemu_co_mutex_unlock(&s
->lock
);
884 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
885 trace_qcow2_writev_data(qemu_coroutine_self(),
886 (cluster_offset
>> 9) + index_in_cluster
);
887 ret
= bdrv_co_writev(bs
->file
,
888 (cluster_offset
>> 9) + index_in_cluster
,
889 cur_nr_sectors
, &hd_qiov
);
890 qemu_co_mutex_lock(&s
->lock
);
895 while (l2meta
!= NULL
) {
898 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
903 /* Take the request off the list of running requests */
904 if (l2meta
->nb_clusters
!= 0) {
905 QLIST_REMOVE(l2meta
, next_in_flight
);
908 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
915 remaining_sectors
-= cur_nr_sectors
;
916 sector_num
+= cur_nr_sectors
;
917 bytes_done
+= cur_nr_sectors
* 512;
918 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors
);
923 qemu_co_mutex_unlock(&s
->lock
);
925 while (l2meta
!= NULL
) {
928 if (l2meta
->nb_clusters
!= 0) {
929 QLIST_REMOVE(l2meta
, next_in_flight
);
931 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
938 qemu_iovec_destroy(&hd_qiov
);
939 qemu_vfree(cluster_data
);
940 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
945 static void qcow2_close(BlockDriverState
*bs
)
947 BDRVQcowState
*s
= bs
->opaque
;
950 qcow2_cache_flush(bs
, s
->l2_table_cache
);
951 qcow2_cache_flush(bs
, s
->refcount_block_cache
);
953 qcow2_mark_clean(bs
);
955 qcow2_cache_destroy(bs
, s
->l2_table_cache
);
956 qcow2_cache_destroy(bs
, s
->refcount_block_cache
);
958 g_free(s
->unknown_header_fields
);
959 cleanup_unknown_header_ext(bs
);
961 g_free(s
->cluster_cache
);
962 qemu_vfree(s
->cluster_data
);
963 qcow2_refcount_close(bs
);
964 qcow2_free_snapshots(bs
);
967 static void qcow2_invalidate_cache(BlockDriverState
*bs
)
969 BDRVQcowState
*s
= bs
->opaque
;
970 int flags
= s
->flags
;
971 AES_KEY aes_encrypt_key
;
972 AES_KEY aes_decrypt_key
;
973 uint32_t crypt_method
= 0;
977 * Backing files are read-only which makes all of their metadata immutable,
978 * that means we don't have to worry about reopening them here.
981 if (s
->crypt_method
) {
982 crypt_method
= s
->crypt_method
;
983 memcpy(&aes_encrypt_key
, &s
->aes_encrypt_key
, sizeof(aes_encrypt_key
));
984 memcpy(&aes_decrypt_key
, &s
->aes_decrypt_key
, sizeof(aes_decrypt_key
));
989 options
= qdict_new();
990 qdict_put(options
, QCOW2_OPT_LAZY_REFCOUNTS
,
991 qbool_from_int(s
->use_lazy_refcounts
));
993 memset(s
, 0, sizeof(BDRVQcowState
));
994 qcow2_open(bs
, options
, flags
);
999 s
->crypt_method
= crypt_method
;
1000 memcpy(&s
->aes_encrypt_key
, &aes_encrypt_key
, sizeof(aes_encrypt_key
));
1001 memcpy(&s
->aes_decrypt_key
, &aes_decrypt_key
, sizeof(aes_decrypt_key
));
1005 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
1006 size_t len
, size_t buflen
)
1008 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
1009 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
1011 if (buflen
< ext_len
) {
1015 *ext_backing_fmt
= (QCowExtension
) {
1016 .magic
= cpu_to_be32(magic
),
1017 .len
= cpu_to_be32(len
),
1019 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
1025 * Updates the qcow2 header, including the variable length parts of it, i.e.
1026 * the backing file name and all extensions. qcow2 was not designed to allow
1027 * such changes, so if we run out of space (we can only use the first cluster)
1028 * this function may fail.
1030 * Returns 0 on success, -errno in error cases.
1032 int qcow2_update_header(BlockDriverState
*bs
)
1034 BDRVQcowState
*s
= bs
->opaque
;
1037 size_t buflen
= s
->cluster_size
;
1039 uint64_t total_size
;
1040 uint32_t refcount_table_clusters
;
1041 size_t header_length
;
1042 Qcow2UnknownHeaderExtension
*uext
;
1044 buf
= qemu_blockalign(bs
, buflen
);
1046 /* Header structure */
1047 header
= (QCowHeader
*) buf
;
1049 if (buflen
< sizeof(*header
)) {
1054 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
1055 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1056 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
1058 *header
= (QCowHeader
) {
1059 /* Version 2 fields */
1060 .magic
= cpu_to_be32(QCOW_MAGIC
),
1061 .version
= cpu_to_be32(s
->qcow_version
),
1062 .backing_file_offset
= 0,
1063 .backing_file_size
= 0,
1064 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
1065 .size
= cpu_to_be64(total_size
),
1066 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
1067 .l1_size
= cpu_to_be32(s
->l1_size
),
1068 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
1069 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
1070 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
1071 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
1072 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
1074 /* Version 3 fields */
1075 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
1076 .compatible_features
= cpu_to_be64(s
->compatible_features
),
1077 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
1078 .refcount_order
= cpu_to_be32(3 + REFCOUNT_SHIFT
),
1079 .header_length
= cpu_to_be32(header_length
),
1082 /* For older versions, write a shorter header */
1083 switch (s
->qcow_version
) {
1085 ret
= offsetof(QCowHeader
, incompatible_features
);
1088 ret
= sizeof(*header
);
1097 memset(buf
, 0, buflen
);
1099 /* Preserve any unknown field in the header */
1100 if (s
->unknown_header_fields_size
) {
1101 if (buflen
< s
->unknown_header_fields_size
) {
1106 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
1107 buf
+= s
->unknown_header_fields_size
;
1108 buflen
-= s
->unknown_header_fields_size
;
1111 /* Backing file format header extension */
1112 if (*bs
->backing_format
) {
1113 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
1114 bs
->backing_format
, strlen(bs
->backing_format
),
1125 Qcow2Feature features
[] = {
1127 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
1128 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
1129 .name
= "dirty bit",
1132 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
1133 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
1134 .name
= "lazy refcounts",
1138 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
1139 features
, sizeof(features
), buflen
);
1146 /* Keep unknown header extensions */
1147 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
1148 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
1157 /* End of header extensions */
1158 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
1166 /* Backing file name */
1167 if (*bs
->backing_file
) {
1168 size_t backing_file_len
= strlen(bs
->backing_file
);
1170 if (buflen
< backing_file_len
) {
1175 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1176 strncpy(buf
, bs
->backing_file
, buflen
);
1178 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
1179 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
1182 /* Write the new header */
1183 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
1194 static int qcow2_change_backing_file(BlockDriverState
*bs
,
1195 const char *backing_file
, const char *backing_fmt
)
1197 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
1198 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
1200 return qcow2_update_header(bs
);
1203 static int preallocate(BlockDriverState
*bs
)
1205 uint64_t nb_sectors
;
1207 uint64_t host_offset
= 0;
1212 nb_sectors
= bdrv_getlength(bs
) >> 9;
1215 while (nb_sectors
) {
1216 num
= MIN(nb_sectors
, INT_MAX
>> 9);
1217 ret
= qcow2_alloc_cluster_offset(bs
, offset
, 0, num
, &num
,
1218 &host_offset
, &meta
);
1223 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
1225 qcow2_free_any_clusters(bs
, meta
->alloc_offset
, meta
->nb_clusters
,
1226 QCOW2_DISCARD_NEVER
);
1230 /* There are no dependent requests, but we need to remove our request
1231 * from the list of in-flight requests */
1233 QLIST_REMOVE(meta
, next_in_flight
);
1236 /* TODO Preallocate data if requested */
1243 * It is expected that the image file is large enough to actually contain
1244 * all of the allocated clusters (otherwise we get failing reads after
1245 * EOF). Extend the image to the last allocated sector.
1247 if (host_offset
!= 0) {
1249 memset(buf
, 0, 512);
1250 ret
= bdrv_write(bs
->file
, (host_offset
>> 9) + num
- 1, buf
, 1);
1259 static int qcow2_create2(const char *filename
, int64_t total_size
,
1260 const char *backing_file
, const char *backing_format
,
1261 int flags
, size_t cluster_size
, int prealloc
,
1262 QEMUOptionParameter
*options
, int version
)
1264 /* Calculate cluster_bits */
1266 cluster_bits
= ffs(cluster_size
) - 1;
1267 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
1268 (1 << cluster_bits
) != cluster_size
)
1271 "Cluster size must be a power of two between %d and %dk",
1272 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
1277 * Open the image file and write a minimal qcow2 header.
1279 * We keep things simple and start with a zero-sized image. We also
1280 * do without refcount blocks or a L1 table for now. We'll fix the
1281 * inconsistency later.
1283 * We do need a refcount table because growing the refcount table means
1284 * allocating two new refcount blocks - the seconds of which would be at
1285 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1286 * size for any qcow2 image.
1288 BlockDriverState
* bs
;
1290 uint8_t* refcount_table
;
1293 ret
= bdrv_create_file(filename
, options
);
1298 ret
= bdrv_file_open(&bs
, filename
, NULL
, BDRV_O_RDWR
);
1303 /* Write the header */
1304 memset(&header
, 0, sizeof(header
));
1305 header
.magic
= cpu_to_be32(QCOW_MAGIC
);
1306 header
.version
= cpu_to_be32(version
);
1307 header
.cluster_bits
= cpu_to_be32(cluster_bits
);
1308 header
.size
= cpu_to_be64(0);
1309 header
.l1_table_offset
= cpu_to_be64(0);
1310 header
.l1_size
= cpu_to_be32(0);
1311 header
.refcount_table_offset
= cpu_to_be64(cluster_size
);
1312 header
.refcount_table_clusters
= cpu_to_be32(1);
1313 header
.refcount_order
= cpu_to_be32(3 + REFCOUNT_SHIFT
);
1314 header
.header_length
= cpu_to_be32(sizeof(header
));
1316 if (flags
& BLOCK_FLAG_ENCRYPT
) {
1317 header
.crypt_method
= cpu_to_be32(QCOW_CRYPT_AES
);
1319 header
.crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
1322 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
1323 header
.compatible_features
|=
1324 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
1327 ret
= bdrv_pwrite(bs
, 0, &header
, sizeof(header
));
1332 /* Write an empty refcount table */
1333 refcount_table
= g_malloc0(cluster_size
);
1334 ret
= bdrv_pwrite(bs
, cluster_size
, refcount_table
, cluster_size
);
1335 g_free(refcount_table
);
1344 * And now open the image and make it consistent first (i.e. increase the
1345 * refcount of the cluster that is occupied by the header and the refcount
1348 BlockDriver
* drv
= bdrv_find_format("qcow2");
1349 assert(drv
!= NULL
);
1350 ret
= bdrv_open(bs
, filename
, NULL
,
1351 BDRV_O_RDWR
| BDRV_O_CACHE_WB
| BDRV_O_NO_FLUSH
, drv
);
1356 ret
= qcow2_alloc_clusters(bs
, 2 * cluster_size
);
1360 } else if (ret
!= 0) {
1361 error_report("Huh, first cluster in empty image is already in use?");
1365 /* Okay, now that we have a valid image, let's give it the right size */
1366 ret
= bdrv_truncate(bs
, total_size
* BDRV_SECTOR_SIZE
);
1371 /* Want a backing file? There you go.*/
1373 ret
= bdrv_change_backing_file(bs
, backing_file
, backing_format
);
1379 /* And if we're supposed to preallocate metadata, do that now */
1381 BDRVQcowState
*s
= bs
->opaque
;
1382 qemu_co_mutex_lock(&s
->lock
);
1383 ret
= preallocate(bs
);
1384 qemu_co_mutex_unlock(&s
->lock
);
1396 static int qcow2_create(const char *filename
, QEMUOptionParameter
*options
)
1398 const char *backing_file
= NULL
;
1399 const char *backing_fmt
= NULL
;
1400 uint64_t sectors
= 0;
1402 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
1406 /* Read out options */
1407 while (options
&& options
->name
) {
1408 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1409 sectors
= options
->value
.n
/ 512;
1410 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FILE
)) {
1411 backing_file
= options
->value
.s
;
1412 } else if (!strcmp(options
->name
, BLOCK_OPT_BACKING_FMT
)) {
1413 backing_fmt
= options
->value
.s
;
1414 } else if (!strcmp(options
->name
, BLOCK_OPT_ENCRYPT
)) {
1415 flags
|= options
->value
.n
? BLOCK_FLAG_ENCRYPT
: 0;
1416 } else if (!strcmp(options
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
1417 if (options
->value
.n
) {
1418 cluster_size
= options
->value
.n
;
1420 } else if (!strcmp(options
->name
, BLOCK_OPT_PREALLOC
)) {
1421 if (!options
->value
.s
|| !strcmp(options
->value
.s
, "off")) {
1423 } else if (!strcmp(options
->value
.s
, "metadata")) {
1426 fprintf(stderr
, "Invalid preallocation mode: '%s'\n",
1430 } else if (!strcmp(options
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
1431 if (!options
->value
.s
|| !strcmp(options
->value
.s
, "0.10")) {
1433 } else if (!strcmp(options
->value
.s
, "1.1")) {
1436 fprintf(stderr
, "Invalid compatibility level: '%s'\n",
1440 } else if (!strcmp(options
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
1441 flags
|= options
->value
.n
? BLOCK_FLAG_LAZY_REFCOUNTS
: 0;
1446 if (backing_file
&& prealloc
) {
1447 fprintf(stderr
, "Backing file and preallocation cannot be used at "
1452 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
1453 fprintf(stderr
, "Lazy refcounts only supported with compatibility "
1454 "level 1.1 and above (use compat=1.1 or greater)\n");
1458 return qcow2_create2(filename
, sectors
, backing_file
, backing_fmt
, flags
,
1459 cluster_size
, prealloc
, options
, version
);
1462 static int qcow2_make_empty(BlockDriverState
*bs
)
1465 /* XXX: not correct */
1466 BDRVQcowState
*s
= bs
->opaque
;
1467 uint32_t l1_length
= s
->l1_size
* sizeof(uint64_t);
1470 memset(s
->l1_table
, 0, l1_length
);
1471 if (bdrv_pwrite(bs
->file
, s
->l1_table_offset
, s
->l1_table
, l1_length
) < 0)
1473 ret
= bdrv_truncate(bs
->file
, s
->l1_table_offset
+ l1_length
);
1482 static coroutine_fn
int qcow2_co_write_zeroes(BlockDriverState
*bs
,
1483 int64_t sector_num
, int nb_sectors
)
1486 BDRVQcowState
*s
= bs
->opaque
;
1488 /* Emulate misaligned zero writes */
1489 if (sector_num
% s
->cluster_sectors
|| nb_sectors
% s
->cluster_sectors
) {
1493 /* Whatever is left can use real zero clusters */
1494 qemu_co_mutex_lock(&s
->lock
);
1495 ret
= qcow2_zero_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1497 qemu_co_mutex_unlock(&s
->lock
);
1502 static coroutine_fn
int qcow2_co_discard(BlockDriverState
*bs
,
1503 int64_t sector_num
, int nb_sectors
)
1506 BDRVQcowState
*s
= bs
->opaque
;
1508 qemu_co_mutex_lock(&s
->lock
);
1509 ret
= qcow2_discard_clusters(bs
, sector_num
<< BDRV_SECTOR_BITS
,
1511 qemu_co_mutex_unlock(&s
->lock
);
1515 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
)
1517 BDRVQcowState
*s
= bs
->opaque
;
1518 int64_t new_l1_size
;
1522 error_report("The new size must be a multiple of 512");
1526 /* cannot proceed if image has snapshots */
1527 if (s
->nb_snapshots
) {
1528 error_report("Can't resize an image which has snapshots");
1532 /* shrinking is currently not supported */
1533 if (offset
< bs
->total_sectors
* 512) {
1534 error_report("qcow2 doesn't support shrinking images yet");
1538 new_l1_size
= size_to_l1(s
, offset
);
1539 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
1544 /* write updated header.size */
1545 offset
= cpu_to_be64(offset
);
1546 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
1547 &offset
, sizeof(uint64_t));
1552 s
->l1_vm_state_index
= new_l1_size
;
1556 /* XXX: put compressed sectors first, then all the cluster aligned
1557 tables to avoid losing bytes in alignment */
1558 static int qcow2_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1559 const uint8_t *buf
, int nb_sectors
)
1561 BDRVQcowState
*s
= bs
->opaque
;
1565 uint64_t cluster_offset
;
1567 if (nb_sectors
== 0) {
1568 /* align end of file to a sector boundary to ease reading with
1569 sector based I/Os */
1570 cluster_offset
= bdrv_getlength(bs
->file
);
1571 cluster_offset
= (cluster_offset
+ 511) & ~511;
1572 bdrv_truncate(bs
->file
, cluster_offset
);
1576 if (nb_sectors
!= s
->cluster_sectors
) {
1579 /* Zero-pad last write if image size is not cluster aligned */
1580 if (sector_num
+ nb_sectors
== bs
->total_sectors
&&
1581 nb_sectors
< s
->cluster_sectors
) {
1582 uint8_t *pad_buf
= qemu_blockalign(bs
, s
->cluster_size
);
1583 memset(pad_buf
, 0, s
->cluster_size
);
1584 memcpy(pad_buf
, buf
, nb_sectors
* BDRV_SECTOR_SIZE
);
1585 ret
= qcow2_write_compressed(bs
, sector_num
,
1586 pad_buf
, s
->cluster_sectors
);
1587 qemu_vfree(pad_buf
);
1592 out_buf
= g_malloc(s
->cluster_size
+ (s
->cluster_size
/ 1000) + 128);
1594 /* best compression, small window, no zlib header */
1595 memset(&strm
, 0, sizeof(strm
));
1596 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
1598 9, Z_DEFAULT_STRATEGY
);
1604 strm
.avail_in
= s
->cluster_size
;
1605 strm
.next_in
= (uint8_t *)buf
;
1606 strm
.avail_out
= s
->cluster_size
;
1607 strm
.next_out
= out_buf
;
1609 ret
= deflate(&strm
, Z_FINISH
);
1610 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
1615 out_len
= strm
.next_out
- out_buf
;
1619 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
1620 /* could not compress: write normal cluster */
1621 ret
= bdrv_write(bs
, sector_num
, buf
, s
->cluster_sectors
);
1626 cluster_offset
= qcow2_alloc_compressed_cluster_offset(bs
,
1627 sector_num
<< 9, out_len
);
1628 if (!cluster_offset
) {
1632 cluster_offset
&= s
->cluster_offset_mask
;
1633 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
1634 ret
= bdrv_pwrite(bs
->file
, cluster_offset
, out_buf
, out_len
);
1646 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
1648 BDRVQcowState
*s
= bs
->opaque
;
1651 qemu_co_mutex_lock(&s
->lock
);
1652 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
1654 qemu_co_mutex_unlock(&s
->lock
);
1658 if (qcow2_need_accurate_refcounts(s
)) {
1659 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1661 qemu_co_mutex_unlock(&s
->lock
);
1665 qemu_co_mutex_unlock(&s
->lock
);
1670 static int64_t qcow2_vm_state_offset(BDRVQcowState
*s
)
1672 return (int64_t)s
->l1_vm_state_index
<< (s
->cluster_bits
+ s
->l2_bits
);
1675 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1677 BDRVQcowState
*s
= bs
->opaque
;
1678 bdi
->cluster_size
= s
->cluster_size
;
1679 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
1684 static void dump_refcounts(BlockDriverState
*bs
)
1686 BDRVQcowState
*s
= bs
->opaque
;
1687 int64_t nb_clusters
, k
, k1
, size
;
1690 size
= bdrv_getlength(bs
->file
);
1691 nb_clusters
= size_to_clusters(s
, size
);
1692 for(k
= 0; k
< nb_clusters
;) {
1694 refcount
= get_refcount(bs
, k
);
1696 while (k
< nb_clusters
&& get_refcount(bs
, k
) == refcount
)
1698 printf("%" PRId64
": refcount=%d nb=%" PRId64
"\n", k
, refcount
,
1704 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
1707 BDRVQcowState
*s
= bs
->opaque
;
1708 int growable
= bs
->growable
;
1711 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
1713 ret
= bdrv_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
, qiov
);
1714 bs
->growable
= growable
;
1719 static int qcow2_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1720 int64_t pos
, int size
)
1722 BDRVQcowState
*s
= bs
->opaque
;
1723 int growable
= bs
->growable
;
1726 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
1728 ret
= bdrv_pread(bs
, qcow2_vm_state_offset(s
) + pos
, buf
, size
);
1729 bs
->growable
= growable
;
1734 static QEMUOptionParameter qcow2_create_options
[] = {
1736 .name
= BLOCK_OPT_SIZE
,
1738 .help
= "Virtual disk size"
1741 .name
= BLOCK_OPT_COMPAT_LEVEL
,
1743 .help
= "Compatibility level (0.10 or 1.1)"
1746 .name
= BLOCK_OPT_BACKING_FILE
,
1748 .help
= "File name of a base image"
1751 .name
= BLOCK_OPT_BACKING_FMT
,
1753 .help
= "Image format of the base image"
1756 .name
= BLOCK_OPT_ENCRYPT
,
1758 .help
= "Encrypt the image"
1761 .name
= BLOCK_OPT_CLUSTER_SIZE
,
1763 .help
= "qcow2 cluster size",
1764 .value
= { .n
= DEFAULT_CLUSTER_SIZE
},
1767 .name
= BLOCK_OPT_PREALLOC
,
1769 .help
= "Preallocation mode (allowed values: off, metadata)"
1772 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
1774 .help
= "Postpone refcount updates",
1779 static BlockDriver bdrv_qcow2
= {
1780 .format_name
= "qcow2",
1781 .instance_size
= sizeof(BDRVQcowState
),
1782 .bdrv_probe
= qcow2_probe
,
1783 .bdrv_open
= qcow2_open
,
1784 .bdrv_close
= qcow2_close
,
1785 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
1786 .bdrv_create
= qcow2_create
,
1787 .bdrv_co_is_allocated
= qcow2_co_is_allocated
,
1788 .bdrv_set_key
= qcow2_set_key
,
1789 .bdrv_make_empty
= qcow2_make_empty
,
1791 .bdrv_co_readv
= qcow2_co_readv
,
1792 .bdrv_co_writev
= qcow2_co_writev
,
1793 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
1795 .bdrv_co_write_zeroes
= qcow2_co_write_zeroes
,
1796 .bdrv_co_discard
= qcow2_co_discard
,
1797 .bdrv_truncate
= qcow2_truncate
,
1798 .bdrv_write_compressed
= qcow2_write_compressed
,
1800 .bdrv_snapshot_create
= qcow2_snapshot_create
,
1801 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
1802 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
1803 .bdrv_snapshot_list
= qcow2_snapshot_list
,
1804 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
1805 .bdrv_get_info
= qcow2_get_info
,
1807 .bdrv_save_vmstate
= qcow2_save_vmstate
,
1808 .bdrv_load_vmstate
= qcow2_load_vmstate
,
1810 .bdrv_change_backing_file
= qcow2_change_backing_file
,
1812 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
1814 .create_options
= qcow2_create_options
,
1815 .bdrv_check
= qcow2_check
,
1818 static void bdrv_qcow2_init(void)
1820 bdrv_register(&bdrv_qcow2
);
1823 block_init(bdrv_qcow2_init
);