2 * Block driver for the QCOW 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
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu/error-report.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/module.h"
31 #include "qemu/option.h"
32 #include "qemu/bswap.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "crypto/block.h"
37 #include "migration/blocker.h"
38 #include "block/crypto.h"
40 /**************************************************************/
41 /* QEMU COW block driver with compression and encryption support */
43 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
44 #define QCOW_VERSION 1
46 #define QCOW_CRYPT_NONE 0
47 #define QCOW_CRYPT_AES 1
49 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
51 typedef struct QCowHeader {
54 uint64_t backing_file_offset;
55 uint32_t backing_file_size;
57 uint64_t size; /* in bytes */
61 uint32_t crypt_method;
62 uint64_t l1_table_offset;
63 } QEMU_PACKED QCowHeader;
65 #define L2_CACHE_SIZE 16
67 typedef struct BDRVQcowState {
74 uint64_t cluster_offset_mask;
75 uint64_t l1_table_offset;
78 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
79 uint32_t l2_cache_counts[L2_CACHE_SIZE];
80 uint8_t *cluster_cache;
81 uint8_t *cluster_data;
82 uint64_t cluster_cache_offset;
83 QCryptoBlock *crypto; /* Disk encryption format driver */
84 uint32_t crypt_method_header;
86 Error *migration_blocker;
89 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
91 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
93 const QCowHeader *cow_header = (const void *)buf;
95 if (buf_size >= sizeof(QCowHeader) &&
96 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
97 be32_to_cpu(cow_header->version) == QCOW_VERSION)
103 static QemuOptsList qcow_runtime_opts = {
105 .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head),
107 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
108 { /* end of list */ }
112 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
115 BDRVQcowState *s = bs->opaque;
116 unsigned int len, i, shift;
119 Error *local_err = NULL;
120 QCryptoBlockOpenOptions *crypto_opts = NULL;
121 unsigned int cflags = 0;
122 QDict *encryptopts = NULL;
123 const char *encryptfmt;
125 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
126 encryptfmt = qdict_get_try_str(encryptopts, "format");
128 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
135 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
139 be32_to_cpus(&header.magic);
140 be32_to_cpus(&header.version);
141 be64_to_cpus(&header.backing_file_offset);
142 be32_to_cpus(&header.backing_file_size);
143 be32_to_cpus(&header.mtime);
144 be64_to_cpus(&header.size);
145 be32_to_cpus(&header.crypt_method);
146 be64_to_cpus(&header.l1_table_offset);
148 if (header.magic != QCOW_MAGIC) {
149 error_setg(errp, "Image not in qcow format");
153 if (header.version != QCOW_VERSION) {
154 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
159 if (header.size <= 1) {
160 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
164 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
165 error_setg(errp, "Cluster size must be between 512 and 64k");
170 /* l2_bits specifies number of entries; storing a uint64_t in each entry,
171 * so bytes = num_entries << 3. */
172 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
173 error_setg(errp, "L2 table size must be between 512 and 64k");
178 s->crypt_method_header = header.crypt_method;
179 if (s->crypt_method_header) {
180 if (bdrv_uses_whitelist() &&
181 s->crypt_method_header == QCOW_CRYPT_AES) {
183 "Use of AES-CBC encrypted qcow images is no longer "
184 "supported in system emulators");
185 error_append_hint(errp,
186 "You can use 'qemu-img convert' to convert your "
187 "image to an alternative supported format, such "
188 "as unencrypted qcow, or raw with the LUKS "
189 "format instead.\n");
193 if (s->crypt_method_header == QCOW_CRYPT_AES) {
194 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
196 "Header reported 'aes' encryption format but "
197 "options specify '%s'", encryptfmt);
201 qdict_del(encryptopts, "format");
202 crypto_opts = block_crypto_open_opts_init(
203 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
209 if (flags & BDRV_O_NO_IO) {
210 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
212 s->crypto = qcrypto_block_open(crypto_opts, "encrypt.",
213 NULL, NULL, cflags, errp);
219 error_setg(errp, "invalid encryption method in qcow header");
223 bs->encrypted = true;
226 error_setg(errp, "No encryption in image header, but options "
227 "specified format '%s'", encryptfmt);
232 s->cluster_bits = header.cluster_bits;
233 s->cluster_size = 1 << s->cluster_bits;
234 s->cluster_sectors = 1 << (s->cluster_bits - 9);
235 s->l2_bits = header.l2_bits;
236 s->l2_size = 1 << s->l2_bits;
237 bs->total_sectors = header.size / 512;
238 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
240 /* read the level 1 table */
241 shift = s->cluster_bits + s->l2_bits;
242 if (header.size > UINT64_MAX - (1LL << shift)) {
243 error_setg(errp, "Image too large");
247 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
248 if (l1_size > INT_MAX / sizeof(uint64_t)) {
249 error_setg(errp, "Image too large");
253 s->l1_size = l1_size;
256 s->l1_table_offset = header.l1_table_offset;
257 s->l1_table = g_try_new(uint64_t, s->l1_size);
258 if (s->l1_table == NULL) {
259 error_setg(errp, "Could not allocate memory for L1 table");
264 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
265 s->l1_size * sizeof(uint64_t));
270 for(i = 0;i < s->l1_size; i++) {
271 be64_to_cpus(&s->l1_table[i]);
274 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
276 qemu_try_blockalign(bs->file->bs,
277 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
278 if (s->l2_cache == NULL) {
279 error_setg(errp, "Could not allocate L2 table cache");
283 s->cluster_cache = g_malloc(s->cluster_size);
284 s->cluster_data = g_malloc(s->cluster_size);
285 s->cluster_cache_offset = -1;
287 /* read the backing file name */
288 if (header.backing_file_offset != 0) {
289 len = header.backing_file_size;
290 if (len > 1023 || len >= sizeof(bs->backing_file)) {
291 error_setg(errp, "Backing file name too long");
295 ret = bdrv_pread(bs->file, header.backing_file_offset,
296 bs->backing_file, len);
300 bs->backing_file[len] = '\0';
303 /* Disable migration when qcow images are used */
304 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
305 "does not support live migration",
306 bdrv_get_device_or_node_name(bs));
307 ret = migrate_add_blocker(s->migration_blocker, &local_err);
309 error_propagate(errp, local_err);
310 error_free(s->migration_blocker);
314 QDECREF(encryptopts);
315 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
316 qemu_co_mutex_init(&s->lock);
321 qemu_vfree(s->l2_cache);
322 g_free(s->cluster_cache);
323 g_free(s->cluster_data);
324 qcrypto_block_free(s->crypto);
325 QDECREF(encryptopts);
326 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
331 /* We have nothing to do for QCOW reopen, stubs just return
333 static int qcow_reopen_prepare(BDRVReopenState *state,
334 BlockReopenQueue *queue, Error **errp)
344 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
347 * 2 to allocate a compressed cluster of size
348 * 'compressed_size'. 'compressed_size' must be > 0 and <
351 * return 0 if not allocated, 1 if *result is assigned, and negative
354 static int get_cluster_offset(BlockDriverState *bs,
355 uint64_t offset, int allocate,
357 int n_start, int n_end, uint64_t *result)
359 BDRVQcowState *s = bs->opaque;
360 int min_index, i, j, l1_index, l2_index, ret;
362 uint64_t *l2_table, cluster_offset, tmp;
367 l1_index = offset >> (s->l2_bits + s->cluster_bits);
368 l2_offset = s->l1_table[l1_index];
373 /* allocate a new l2 entry */
374 l2_offset = bdrv_getlength(bs->file->bs);
378 /* round to cluster size */
379 l2_offset = QEMU_ALIGN_UP(l2_offset, s->cluster_size);
380 /* update the L1 entry */
381 s->l1_table[l1_index] = l2_offset;
382 tmp = cpu_to_be64(l2_offset);
383 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
384 ret = bdrv_pwrite_sync(bs->file,
385 s->l1_table_offset + l1_index * sizeof(tmp),
392 for(i = 0; i < L2_CACHE_SIZE; i++) {
393 if (l2_offset == s->l2_cache_offsets[i]) {
394 /* increment the hit count */
395 if (++s->l2_cache_counts[i] == 0xffffffff) {
396 for(j = 0; j < L2_CACHE_SIZE; j++) {
397 s->l2_cache_counts[j] >>= 1;
400 l2_table = s->l2_cache + (i << s->l2_bits);
404 /* not found: load a new entry in the least used one */
406 min_count = 0xffffffff;
407 for(i = 0; i < L2_CACHE_SIZE; i++) {
408 if (s->l2_cache_counts[i] < min_count) {
409 min_count = s->l2_cache_counts[i];
413 l2_table = s->l2_cache + (min_index << s->l2_bits);
414 BLKDBG_EVENT(bs->file, BLKDBG_L2_LOAD);
416 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
417 ret = bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
418 s->l2_size * sizeof(uint64_t));
423 ret = bdrv_pread(bs->file, l2_offset, l2_table,
424 s->l2_size * sizeof(uint64_t));
429 s->l2_cache_offsets[min_index] = l2_offset;
430 s->l2_cache_counts[min_index] = 1;
432 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
433 cluster_offset = be64_to_cpu(l2_table[l2_index]);
434 if (!cluster_offset ||
435 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
438 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);
439 /* allocate a new cluster */
440 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
441 (n_end - n_start) < s->cluster_sectors) {
442 /* if the cluster is already compressed, we must
443 decompress it in the case it is not completely
445 if (decompress_cluster(bs, cluster_offset) < 0) {
448 cluster_offset = bdrv_getlength(bs->file->bs);
449 if ((int64_t) cluster_offset < 0) {
450 return cluster_offset;
452 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
453 /* write the cluster content */
454 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
455 ret = bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
461 cluster_offset = bdrv_getlength(bs->file->bs);
462 if ((int64_t) cluster_offset < 0) {
463 return cluster_offset;
466 /* round to cluster size */
467 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
468 if (cluster_offset + s->cluster_size > INT64_MAX) {
471 ret = bdrv_truncate(bs->file, cluster_offset + s->cluster_size,
472 PREALLOC_MODE_OFF, NULL);
476 /* if encrypted, we must initialize the cluster
477 content which won't be written */
479 (n_end - n_start) < s->cluster_sectors) {
482 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
483 for(i = 0; i < s->cluster_sectors; i++) {
484 if (i < n_start || i >= n_end) {
485 memset(s->cluster_data, 0x00, 512);
486 if (qcrypto_block_encrypt(s->crypto,
494 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
495 ret = bdrv_pwrite(bs->file,
496 cluster_offset + i * 512,
497 s->cluster_data, 512);
504 } else if (allocate == 2) {
505 cluster_offset |= QCOW_OFLAG_COMPRESSED |
506 (uint64_t)compressed_size << (63 - s->cluster_bits);
509 /* update L2 table */
510 tmp = cpu_to_be64(cluster_offset);
511 l2_table[l2_index] = tmp;
513 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
515 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE);
517 ret = bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
523 *result = cluster_offset;
527 static int coroutine_fn qcow_co_block_status(BlockDriverState *bs,
529 int64_t offset, int64_t bytes,
530 int64_t *pnum, int64_t *map,
531 BlockDriverState **file)
533 BDRVQcowState *s = bs->opaque;
534 int index_in_cluster, ret;
536 uint64_t cluster_offset;
538 qemu_co_mutex_lock(&s->lock);
539 ret = get_cluster_offset(bs, offset, 0, 0, 0, 0, &cluster_offset);
540 qemu_co_mutex_unlock(&s->lock);
544 index_in_cluster = offset & (s->cluster_size - 1);
545 n = s->cluster_size - index_in_cluster;
550 if (!cluster_offset) {
553 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) {
554 return BDRV_BLOCK_DATA;
556 *map = cluster_offset | index_in_cluster;
557 *file = bs->file->bs;
558 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
561 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
562 const uint8_t *buf, int buf_size)
564 z_stream strm1, *strm = &strm1;
567 memset(strm, 0, sizeof(*strm));
569 strm->next_in = (uint8_t *)buf;
570 strm->avail_in = buf_size;
571 strm->next_out = out_buf;
572 strm->avail_out = out_buf_size;
574 ret = inflateInit2(strm, -12);
577 ret = inflate(strm, Z_FINISH);
578 out_len = strm->next_out - out_buf;
579 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
580 out_len != out_buf_size) {
588 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
590 BDRVQcowState *s = bs->opaque;
594 coffset = cluster_offset & s->cluster_offset_mask;
595 if (s->cluster_cache_offset != coffset) {
596 csize = cluster_offset >> (63 - s->cluster_bits);
597 csize &= (s->cluster_size - 1);
598 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
599 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
602 if (decompress_buffer(s->cluster_cache, s->cluster_size,
603 s->cluster_data, csize) < 0) {
606 s->cluster_cache_offset = coffset;
611 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
612 int nb_sectors, QEMUIOVector *qiov)
614 BDRVQcowState *s = bs->opaque;
615 int index_in_cluster;
617 uint64_t cluster_offset;
619 QEMUIOVector hd_qiov;
623 if (qiov->niov > 1) {
624 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
630 buf = (uint8_t *)qiov->iov->iov_base;
633 qemu_co_mutex_lock(&s->lock);
635 while (nb_sectors != 0) {
636 /* prepare next request */
637 ret = get_cluster_offset(bs, sector_num << 9,
638 0, 0, 0, 0, &cluster_offset);
642 index_in_cluster = sector_num & (s->cluster_sectors - 1);
643 n = s->cluster_sectors - index_in_cluster;
644 if (n > nb_sectors) {
648 if (!cluster_offset) {
650 /* read from the base image */
651 hd_iov.iov_base = (void *)buf;
652 hd_iov.iov_len = n * 512;
653 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
654 qemu_co_mutex_unlock(&s->lock);
655 /* qcow2 emits this on bs->file instead of bs->backing */
656 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
657 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);
658 qemu_co_mutex_lock(&s->lock);
663 /* Note: in this case, no need to wait */
664 memset(buf, 0, 512 * n);
666 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
667 /* add AIO support for compressed blocks ? */
668 if (decompress_cluster(bs, cluster_offset) < 0) {
673 s->cluster_cache + index_in_cluster * 512, 512 * n);
675 if ((cluster_offset & 511) != 0) {
679 hd_iov.iov_base = (void *)buf;
680 hd_iov.iov_len = n * 512;
681 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
682 qemu_co_mutex_unlock(&s->lock);
683 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
684 ret = bdrv_co_readv(bs->file,
685 (cluster_offset >> 9) + index_in_cluster,
687 qemu_co_mutex_lock(&s->lock);
693 if (qcrypto_block_decrypt(s->crypto,
694 sector_num * BDRV_SECTOR_SIZE, buf,
695 n * BDRV_SECTOR_SIZE, NULL) < 0) {
708 qemu_co_mutex_unlock(&s->lock);
710 if (qiov->niov > 1) {
711 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
712 qemu_vfree(orig_buf);
718 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
719 int nb_sectors, QEMUIOVector *qiov)
721 BDRVQcowState *s = bs->opaque;
722 int index_in_cluster;
723 uint64_t cluster_offset;
726 QEMUIOVector hd_qiov;
730 s->cluster_cache_offset = -1; /* disable compressed cache */
732 /* We must always copy the iov when encrypting, so we
733 * don't modify the original data buffer during encryption */
734 if (bs->encrypted || qiov->niov > 1) {
735 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
739 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
742 buf = (uint8_t *)qiov->iov->iov_base;
745 qemu_co_mutex_lock(&s->lock);
747 while (nb_sectors != 0) {
749 index_in_cluster = sector_num & (s->cluster_sectors - 1);
750 n = s->cluster_sectors - index_in_cluster;
751 if (n > nb_sectors) {
754 ret = get_cluster_offset(bs, sector_num << 9, 1, 0,
756 index_in_cluster + n, &cluster_offset);
760 if (!cluster_offset || (cluster_offset & 511) != 0) {
766 if (qcrypto_block_encrypt(s->crypto, sector_num * BDRV_SECTOR_SIZE,
767 buf, n * BDRV_SECTOR_SIZE, NULL) < 0) {
773 hd_iov.iov_base = (void *)buf;
774 hd_iov.iov_len = n * 512;
775 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
776 qemu_co_mutex_unlock(&s->lock);
777 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
778 ret = bdrv_co_writev(bs->file,
779 (cluster_offset >> 9) + index_in_cluster,
781 qemu_co_mutex_lock(&s->lock);
791 qemu_co_mutex_unlock(&s->lock);
793 qemu_vfree(orig_buf);
798 static void qcow_close(BlockDriverState *bs)
800 BDRVQcowState *s = bs->opaque;
802 qcrypto_block_free(s->crypto);
805 qemu_vfree(s->l2_cache);
806 g_free(s->cluster_cache);
807 g_free(s->cluster_data);
809 migrate_del_blocker(s->migration_blocker);
810 error_free(s->migration_blocker);
813 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
815 int header_size, backing_filename_len, l1_size, shift, i;
818 int64_t total_size = 0;
819 char *backing_file = NULL;
820 Error *local_err = NULL;
822 BlockBackend *qcow_blk;
823 char *encryptfmt = NULL;
825 QDict *encryptopts = NULL;
826 QCryptoBlockCreateOptions *crypto_opts = NULL;
827 QCryptoBlock *crypto = NULL;
829 /* Read out options */
830 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
832 if (total_size == 0) {
833 error_setg(errp, "Image size is too small, cannot be zero length");
838 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
839 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
841 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
842 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
843 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
847 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
848 encryptfmt = g_strdup("aes");
851 ret = bdrv_create_file(filename, opts, &local_err);
853 error_propagate(errp, local_err);
857 qcow_blk = blk_new_open(filename, NULL, NULL,
858 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
860 if (qcow_blk == NULL) {
861 error_propagate(errp, local_err);
866 blk_set_allow_write_beyond_eof(qcow_blk, true);
868 ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp);
873 memset(&header, 0, sizeof(header));
874 header.magic = cpu_to_be32(QCOW_MAGIC);
875 header.version = cpu_to_be32(QCOW_VERSION);
876 header.size = cpu_to_be64(total_size);
877 header_size = sizeof(header);
878 backing_filename_len = 0;
880 if (strcmp(backing_file, "fat:")) {
881 header.backing_file_offset = cpu_to_be64(header_size);
882 backing_filename_len = strlen(backing_file);
883 header.backing_file_size = cpu_to_be32(backing_filename_len);
884 header_size += backing_filename_len;
886 /* special backing file for vvfat */
887 g_free(backing_file);
890 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
891 unmodified sectors */
892 header.l2_bits = 12; /* 32 KB L2 tables */
894 header.cluster_bits = 12; /* 4 KB clusters */
895 header.l2_bits = 9; /* 4 KB L2 tables */
897 header_size = (header_size + 7) & ~7;
898 shift = header.cluster_bits + header.l2_bits;
899 l1_size = (total_size + (1LL << shift) - 1) >> shift;
901 header.l1_table_offset = cpu_to_be64(header_size);
903 options = qemu_opts_to_qdict(opts, NULL);
904 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
907 if (!g_str_equal(encryptfmt, "aes")) {
908 error_setg(errp, "Unknown encryption format '%s', expected 'aes'",
913 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
915 crypto_opts = block_crypto_create_opts_init(
916 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
922 crypto = qcrypto_block_create(crypto_opts, "encrypt.",
923 NULL, NULL, NULL, errp);
929 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
932 /* write all the data */
933 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
934 if (ret != sizeof(header)) {
939 ret = blk_pwrite(qcow_blk, sizeof(header),
940 backing_file, backing_filename_len, 0);
941 if (ret != backing_filename_len) {
946 tmp = g_malloc0(BDRV_SECTOR_SIZE);
947 for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
949 ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
950 tmp, BDRV_SECTOR_SIZE, 0);
951 if (ret != BDRV_SECTOR_SIZE) {
962 QDECREF(encryptopts);
964 qcrypto_block_free(crypto);
965 qapi_free_QCryptoBlockCreateOptions(crypto_opts);
966 g_free(backing_file);
970 static int qcow_make_empty(BlockDriverState *bs)
972 BDRVQcowState *s = bs->opaque;
973 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
976 memset(s->l1_table, 0, l1_length);
977 if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
980 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length,
981 PREALLOC_MODE_OFF, NULL);
985 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
986 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
987 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
992 /* XXX: put compressed sectors first, then all the cluster aligned
993 tables to avoid losing bytes in alignment */
994 static coroutine_fn int
995 qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
996 uint64_t bytes, QEMUIOVector *qiov)
998 BDRVQcowState *s = bs->opaque;
999 QEMUIOVector hd_qiov;
1003 uint8_t *buf, *out_buf;
1004 uint64_t cluster_offset;
1006 buf = qemu_blockalign(bs, s->cluster_size);
1007 if (bytes != s->cluster_size) {
1008 if (bytes > s->cluster_size ||
1009 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
1014 /* Zero-pad last write if image size is not cluster aligned */
1015 memset(buf + bytes, 0, s->cluster_size - bytes);
1017 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
1019 out_buf = g_malloc(s->cluster_size);
1021 /* best compression, small window, no zlib header */
1022 memset(&strm, 0, sizeof(strm));
1023 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1025 9, Z_DEFAULT_STRATEGY);
1031 strm.avail_in = s->cluster_size;
1032 strm.next_in = (uint8_t *)buf;
1033 strm.avail_out = s->cluster_size;
1034 strm.next_out = out_buf;
1036 ret = deflate(&strm, Z_FINISH);
1037 if (ret != Z_STREAM_END && ret != Z_OK) {
1042 out_len = strm.next_out - out_buf;
1046 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1047 /* could not compress: write normal cluster */
1048 ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,
1049 bytes >> BDRV_SECTOR_BITS, qiov);
1055 qemu_co_mutex_lock(&s->lock);
1056 ret = get_cluster_offset(bs, offset, 2, out_len, 0, 0, &cluster_offset);
1057 qemu_co_mutex_unlock(&s->lock);
1061 if (cluster_offset == 0) {
1065 cluster_offset &= s->cluster_offset_mask;
1067 iov = (struct iovec) {
1068 .iov_base = out_buf,
1071 qemu_iovec_init_external(&hd_qiov, &iov, 1);
1072 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1073 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
1085 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1087 BDRVQcowState *s = bs->opaque;
1088 bdi->cluster_size = s->cluster_size;
1092 static QemuOptsList qcow_create_opts = {
1093 .name = "qcow-create-opts",
1094 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1097 .name = BLOCK_OPT_SIZE,
1098 .type = QEMU_OPT_SIZE,
1099 .help = "Virtual disk size"
1102 .name = BLOCK_OPT_BACKING_FILE,
1103 .type = QEMU_OPT_STRING,
1104 .help = "File name of a base image"
1107 .name = BLOCK_OPT_ENCRYPT,
1108 .type = QEMU_OPT_BOOL,
1109 .help = "Encrypt the image with format 'aes'. (Deprecated "
1110 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
1113 .name = BLOCK_OPT_ENCRYPT_FORMAT,
1114 .type = QEMU_OPT_STRING,
1115 .help = "Encrypt the image, format choices: 'aes'",
1117 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
1118 { /* end of list */ }
1122 static BlockDriver bdrv_qcow = {
1123 .format_name = "qcow",
1124 .instance_size = sizeof(BDRVQcowState),
1125 .bdrv_probe = qcow_probe,
1126 .bdrv_open = qcow_open,
1127 .bdrv_close = qcow_close,
1128 .bdrv_child_perm = bdrv_format_default_perms,
1129 .bdrv_reopen_prepare = qcow_reopen_prepare,
1130 .bdrv_create = qcow_create,
1131 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1132 .supports_backing = true,
1134 .bdrv_co_readv = qcow_co_readv,
1135 .bdrv_co_writev = qcow_co_writev,
1136 .bdrv_co_block_status = qcow_co_block_status,
1138 .bdrv_make_empty = qcow_make_empty,
1139 .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed,
1140 .bdrv_get_info = qcow_get_info,
1142 .create_opts = &qcow_create_opts,
1145 static void bdrv_qcow_init(void)
1147 bdrv_register(&bdrv_qcow);
1150 block_init(bdrv_qcow_init);