virtio-ccw: use ccw data stream
[qemu/ar7.git] / block / qcow.c
blobf450b00cfc787a8399a1226ca8edd62a0014d488
1 /*
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
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu-common.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/bswap.h"
32 #include <zlib.h>
33 #include "qapi/qmp/qerror.h"
34 #include "qapi/qmp/qstring.h"
35 #include "crypto/block.h"
36 #include "migration/blocker.h"
37 #include "block/crypto.h"
39 /**************************************************************/
40 /* QEMU COW block driver with compression and encryption support */
42 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
43 #define QCOW_VERSION 1
45 #define QCOW_CRYPT_NONE 0
46 #define QCOW_CRYPT_AES 1
48 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
50 typedef struct QCowHeader {
51 uint32_t magic;
52 uint32_t version;
53 uint64_t backing_file_offset;
54 uint32_t backing_file_size;
55 uint32_t mtime;
56 uint64_t size; /* in bytes */
57 uint8_t cluster_bits;
58 uint8_t l2_bits;
59 uint16_t padding;
60 uint32_t crypt_method;
61 uint64_t l1_table_offset;
62 } QEMU_PACKED QCowHeader;
64 #define L2_CACHE_SIZE 16
66 typedef struct BDRVQcowState {
67 int cluster_bits;
68 int cluster_size;
69 int cluster_sectors;
70 int l2_bits;
71 int l2_size;
72 unsigned int l1_size;
73 uint64_t cluster_offset_mask;
74 uint64_t l1_table_offset;
75 uint64_t *l1_table;
76 uint64_t *l2_cache;
77 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
78 uint32_t l2_cache_counts[L2_CACHE_SIZE];
79 uint8_t *cluster_cache;
80 uint8_t *cluster_data;
81 uint64_t cluster_cache_offset;
82 QCryptoBlock *crypto; /* Disk encryption format driver */
83 uint32_t crypt_method_header;
84 CoMutex lock;
85 Error *migration_blocker;
86 } BDRVQcowState;
88 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
90 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
92 const QCowHeader *cow_header = (const void *)buf;
94 if (buf_size >= sizeof(QCowHeader) &&
95 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
96 be32_to_cpu(cow_header->version) == QCOW_VERSION)
97 return 100;
98 else
99 return 0;
102 static QemuOptsList qcow_runtime_opts = {
103 .name = "qcow",
104 .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head),
105 .desc = {
106 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
107 { /* end of list */ }
111 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
112 Error **errp)
114 BDRVQcowState *s = bs->opaque;
115 unsigned int len, i, shift;
116 int ret;
117 QCowHeader header;
118 Error *local_err = NULL;
119 QCryptoBlockOpenOptions *crypto_opts = NULL;
120 unsigned int cflags = 0;
121 QDict *encryptopts = NULL;
122 const char *encryptfmt;
124 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
125 encryptfmt = qdict_get_try_str(encryptopts, "format");
127 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
128 false, errp);
129 if (!bs->file) {
130 ret = -EINVAL;
131 goto fail;
134 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
135 if (ret < 0) {
136 goto fail;
138 be32_to_cpus(&header.magic);
139 be32_to_cpus(&header.version);
140 be64_to_cpus(&header.backing_file_offset);
141 be32_to_cpus(&header.backing_file_size);
142 be32_to_cpus(&header.mtime);
143 be64_to_cpus(&header.size);
144 be32_to_cpus(&header.crypt_method);
145 be64_to_cpus(&header.l1_table_offset);
147 if (header.magic != QCOW_MAGIC) {
148 error_setg(errp, "Image not in qcow format");
149 ret = -EINVAL;
150 goto fail;
152 if (header.version != QCOW_VERSION) {
153 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
154 ret = -ENOTSUP;
155 goto fail;
158 if (header.size <= 1) {
159 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
160 ret = -EINVAL;
161 goto fail;
163 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
164 error_setg(errp, "Cluster size must be between 512 and 64k");
165 ret = -EINVAL;
166 goto fail;
169 /* l2_bits specifies number of entries; storing a uint64_t in each entry,
170 * so bytes = num_entries << 3. */
171 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
172 error_setg(errp, "L2 table size must be between 512 and 64k");
173 ret = -EINVAL;
174 goto fail;
177 s->crypt_method_header = header.crypt_method;
178 if (s->crypt_method_header) {
179 if (bdrv_uses_whitelist() &&
180 s->crypt_method_header == QCOW_CRYPT_AES) {
181 error_setg(errp,
182 "Use of AES-CBC encrypted qcow images is no longer "
183 "supported in system emulators");
184 error_append_hint(errp,
185 "You can use 'qemu-img convert' to convert your "
186 "image to an alternative supported format, such "
187 "as unencrypted qcow, or raw with the LUKS "
188 "format instead.\n");
189 ret = -ENOSYS;
190 goto fail;
192 if (s->crypt_method_header == QCOW_CRYPT_AES) {
193 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
194 error_setg(errp,
195 "Header reported 'aes' encryption format but "
196 "options specify '%s'", encryptfmt);
197 ret = -EINVAL;
198 goto fail;
200 qdict_del(encryptopts, "format");
201 crypto_opts = block_crypto_open_opts_init(
202 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
203 if (!crypto_opts) {
204 ret = -EINVAL;
205 goto fail;
208 if (flags & BDRV_O_NO_IO) {
209 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
211 s->crypto = qcrypto_block_open(crypto_opts, "encrypt.",
212 NULL, NULL, cflags, errp);
213 if (!s->crypto) {
214 ret = -EINVAL;
215 goto fail;
217 } else {
218 error_setg(errp, "invalid encryption method in qcow header");
219 ret = -EINVAL;
220 goto fail;
222 bs->encrypted = true;
223 } else {
224 if (encryptfmt) {
225 error_setg(errp, "No encryption in image header, but options "
226 "specified format '%s'", encryptfmt);
227 ret = -EINVAL;
228 goto fail;
231 s->cluster_bits = header.cluster_bits;
232 s->cluster_size = 1 << s->cluster_bits;
233 s->cluster_sectors = 1 << (s->cluster_bits - 9);
234 s->l2_bits = header.l2_bits;
235 s->l2_size = 1 << s->l2_bits;
236 bs->total_sectors = header.size / 512;
237 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
239 /* read the level 1 table */
240 shift = s->cluster_bits + s->l2_bits;
241 if (header.size > UINT64_MAX - (1LL << shift)) {
242 error_setg(errp, "Image too large");
243 ret = -EINVAL;
244 goto fail;
245 } else {
246 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
247 if (l1_size > INT_MAX / sizeof(uint64_t)) {
248 error_setg(errp, "Image too large");
249 ret = -EINVAL;
250 goto fail;
252 s->l1_size = l1_size;
255 s->l1_table_offset = header.l1_table_offset;
256 s->l1_table = g_try_new(uint64_t, s->l1_size);
257 if (s->l1_table == NULL) {
258 error_setg(errp, "Could not allocate memory for L1 table");
259 ret = -ENOMEM;
260 goto fail;
263 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
264 s->l1_size * sizeof(uint64_t));
265 if (ret < 0) {
266 goto fail;
269 for(i = 0;i < s->l1_size; i++) {
270 be64_to_cpus(&s->l1_table[i]);
273 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
274 s->l2_cache =
275 qemu_try_blockalign(bs->file->bs,
276 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
277 if (s->l2_cache == NULL) {
278 error_setg(errp, "Could not allocate L2 table cache");
279 ret = -ENOMEM;
280 goto fail;
282 s->cluster_cache = g_malloc(s->cluster_size);
283 s->cluster_data = g_malloc(s->cluster_size);
284 s->cluster_cache_offset = -1;
286 /* read the backing file name */
287 if (header.backing_file_offset != 0) {
288 len = header.backing_file_size;
289 if (len > 1023 || len >= sizeof(bs->backing_file)) {
290 error_setg(errp, "Backing file name too long");
291 ret = -EINVAL;
292 goto fail;
294 ret = bdrv_pread(bs->file, header.backing_file_offset,
295 bs->backing_file, len);
296 if (ret < 0) {
297 goto fail;
299 bs->backing_file[len] = '\0';
302 /* Disable migration when qcow images are used */
303 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
304 "does not support live migration",
305 bdrv_get_device_or_node_name(bs));
306 ret = migrate_add_blocker(s->migration_blocker, &local_err);
307 if (local_err) {
308 error_propagate(errp, local_err);
309 error_free(s->migration_blocker);
310 goto fail;
313 QDECREF(encryptopts);
314 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
315 qemu_co_mutex_init(&s->lock);
316 return 0;
318 fail:
319 g_free(s->l1_table);
320 qemu_vfree(s->l2_cache);
321 g_free(s->cluster_cache);
322 g_free(s->cluster_data);
323 qcrypto_block_free(s->crypto);
324 QDECREF(encryptopts);
325 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
326 return ret;
330 /* We have nothing to do for QCOW reopen, stubs just return
331 * success */
332 static int qcow_reopen_prepare(BDRVReopenState *state,
333 BlockReopenQueue *queue, Error **errp)
335 return 0;
339 /* 'allocate' is:
341 * 0 to not allocate.
343 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
344 * 'n_end')
346 * 2 to allocate a compressed cluster of size
347 * 'compressed_size'. 'compressed_size' must be > 0 and <
348 * cluster_size
350 * return 0 if not allocated, 1 if *result is assigned, and negative
351 * errno on failure.
353 static int get_cluster_offset(BlockDriverState *bs,
354 uint64_t offset, int allocate,
355 int compressed_size,
356 int n_start, int n_end, uint64_t *result)
358 BDRVQcowState *s = bs->opaque;
359 int min_index, i, j, l1_index, l2_index, ret;
360 int64_t l2_offset;
361 uint64_t *l2_table, cluster_offset, tmp;
362 uint32_t min_count;
363 int new_l2_table;
365 *result = 0;
366 l1_index = offset >> (s->l2_bits + s->cluster_bits);
367 l2_offset = s->l1_table[l1_index];
368 new_l2_table = 0;
369 if (!l2_offset) {
370 if (!allocate)
371 return 0;
372 /* allocate a new l2 entry */
373 l2_offset = bdrv_getlength(bs->file->bs);
374 if (l2_offset < 0) {
375 return l2_offset;
377 /* round to cluster size */
378 l2_offset = QEMU_ALIGN_UP(l2_offset, s->cluster_size);
379 /* update the L1 entry */
380 s->l1_table[l1_index] = l2_offset;
381 tmp = cpu_to_be64(l2_offset);
382 ret = bdrv_pwrite_sync(bs->file,
383 s->l1_table_offset + l1_index * sizeof(tmp),
384 &tmp, sizeof(tmp));
385 if (ret < 0) {
386 return ret;
388 new_l2_table = 1;
390 for(i = 0; i < L2_CACHE_SIZE; i++) {
391 if (l2_offset == s->l2_cache_offsets[i]) {
392 /* increment the hit count */
393 if (++s->l2_cache_counts[i] == 0xffffffff) {
394 for(j = 0; j < L2_CACHE_SIZE; j++) {
395 s->l2_cache_counts[j] >>= 1;
398 l2_table = s->l2_cache + (i << s->l2_bits);
399 goto found;
402 /* not found: load a new entry in the least used one */
403 min_index = 0;
404 min_count = 0xffffffff;
405 for(i = 0; i < L2_CACHE_SIZE; i++) {
406 if (s->l2_cache_counts[i] < min_count) {
407 min_count = s->l2_cache_counts[i];
408 min_index = i;
411 l2_table = s->l2_cache + (min_index << s->l2_bits);
412 if (new_l2_table) {
413 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
414 ret = bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
415 s->l2_size * sizeof(uint64_t));
416 if (ret < 0) {
417 return ret;
419 } else {
420 ret = bdrv_pread(bs->file, l2_offset, l2_table,
421 s->l2_size * sizeof(uint64_t));
422 if (ret < 0) {
423 return ret;
426 s->l2_cache_offsets[min_index] = l2_offset;
427 s->l2_cache_counts[min_index] = 1;
428 found:
429 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
430 cluster_offset = be64_to_cpu(l2_table[l2_index]);
431 if (!cluster_offset ||
432 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
433 if (!allocate)
434 return 0;
435 /* allocate a new cluster */
436 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
437 (n_end - n_start) < s->cluster_sectors) {
438 /* if the cluster is already compressed, we must
439 decompress it in the case it is not completely
440 overwritten */
441 if (decompress_cluster(bs, cluster_offset) < 0) {
442 return -EIO;
444 cluster_offset = bdrv_getlength(bs->file->bs);
445 if ((int64_t) cluster_offset < 0) {
446 return cluster_offset;
448 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
449 /* write the cluster content */
450 ret = bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
451 s->cluster_size);
452 if (ret < 0) {
453 return ret;
455 } else {
456 cluster_offset = bdrv_getlength(bs->file->bs);
457 if ((int64_t) cluster_offset < 0) {
458 return cluster_offset;
460 if (allocate == 1) {
461 /* round to cluster size */
462 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
463 if (cluster_offset + s->cluster_size > INT64_MAX) {
464 return -E2BIG;
466 ret = bdrv_truncate(bs->file, cluster_offset + s->cluster_size,
467 PREALLOC_MODE_OFF, NULL);
468 if (ret < 0) {
469 return ret;
471 /* if encrypted, we must initialize the cluster
472 content which won't be written */
473 if (bs->encrypted &&
474 (n_end - n_start) < s->cluster_sectors) {
475 uint64_t start_sect;
476 assert(s->crypto);
477 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
478 for(i = 0; i < s->cluster_sectors; i++) {
479 if (i < n_start || i >= n_end) {
480 memset(s->cluster_data, 0x00, 512);
481 if (qcrypto_block_encrypt(s->crypto, start_sect + i,
482 s->cluster_data,
483 BDRV_SECTOR_SIZE,
484 NULL) < 0) {
485 return -EIO;
487 ret = bdrv_pwrite(bs->file,
488 cluster_offset + i * 512,
489 s->cluster_data, 512);
490 if (ret < 0) {
491 return ret;
496 } else if (allocate == 2) {
497 cluster_offset |= QCOW_OFLAG_COMPRESSED |
498 (uint64_t)compressed_size << (63 - s->cluster_bits);
501 /* update L2 table */
502 tmp = cpu_to_be64(cluster_offset);
503 l2_table[l2_index] = tmp;
504 ret = bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
505 &tmp, sizeof(tmp));
506 if (ret < 0) {
507 return ret;
510 *result = cluster_offset;
511 return 1;
514 static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
515 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
517 BDRVQcowState *s = bs->opaque;
518 int index_in_cluster, n, ret;
519 uint64_t cluster_offset;
521 qemu_co_mutex_lock(&s->lock);
522 ret = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0, &cluster_offset);
523 qemu_co_mutex_unlock(&s->lock);
524 if (ret < 0) {
525 return ret;
527 index_in_cluster = sector_num & (s->cluster_sectors - 1);
528 n = s->cluster_sectors - index_in_cluster;
529 if (n > nb_sectors)
530 n = nb_sectors;
531 *pnum = n;
532 if (!cluster_offset) {
533 return 0;
535 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) {
536 return BDRV_BLOCK_DATA;
538 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
539 *file = bs->file->bs;
540 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
543 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
544 const uint8_t *buf, int buf_size)
546 z_stream strm1, *strm = &strm1;
547 int ret, out_len;
549 memset(strm, 0, sizeof(*strm));
551 strm->next_in = (uint8_t *)buf;
552 strm->avail_in = buf_size;
553 strm->next_out = out_buf;
554 strm->avail_out = out_buf_size;
556 ret = inflateInit2(strm, -12);
557 if (ret != Z_OK)
558 return -1;
559 ret = inflate(strm, Z_FINISH);
560 out_len = strm->next_out - out_buf;
561 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
562 out_len != out_buf_size) {
563 inflateEnd(strm);
564 return -1;
566 inflateEnd(strm);
567 return 0;
570 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
572 BDRVQcowState *s = bs->opaque;
573 int ret, csize;
574 uint64_t coffset;
576 coffset = cluster_offset & s->cluster_offset_mask;
577 if (s->cluster_cache_offset != coffset) {
578 csize = cluster_offset >> (63 - s->cluster_bits);
579 csize &= (s->cluster_size - 1);
580 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
581 if (ret != csize)
582 return -1;
583 if (decompress_buffer(s->cluster_cache, s->cluster_size,
584 s->cluster_data, csize) < 0) {
585 return -1;
587 s->cluster_cache_offset = coffset;
589 return 0;
592 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
593 int nb_sectors, QEMUIOVector *qiov)
595 BDRVQcowState *s = bs->opaque;
596 int index_in_cluster;
597 int ret = 0, n;
598 uint64_t cluster_offset;
599 struct iovec hd_iov;
600 QEMUIOVector hd_qiov;
601 uint8_t *buf;
602 void *orig_buf;
604 if (qiov->niov > 1) {
605 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
606 if (buf == NULL) {
607 return -ENOMEM;
609 } else {
610 orig_buf = NULL;
611 buf = (uint8_t *)qiov->iov->iov_base;
614 qemu_co_mutex_lock(&s->lock);
616 while (nb_sectors != 0) {
617 /* prepare next request */
618 ret = get_cluster_offset(bs, sector_num << 9,
619 0, 0, 0, 0, &cluster_offset);
620 if (ret < 0) {
621 break;
623 index_in_cluster = sector_num & (s->cluster_sectors - 1);
624 n = s->cluster_sectors - index_in_cluster;
625 if (n > nb_sectors) {
626 n = nb_sectors;
629 if (!cluster_offset) {
630 if (bs->backing) {
631 /* read from the base image */
632 hd_iov.iov_base = (void *)buf;
633 hd_iov.iov_len = n * 512;
634 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
635 qemu_co_mutex_unlock(&s->lock);
636 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);
637 qemu_co_mutex_lock(&s->lock);
638 if (ret < 0) {
639 break;
641 } else {
642 /* Note: in this case, no need to wait */
643 memset(buf, 0, 512 * n);
645 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
646 /* add AIO support for compressed blocks ? */
647 if (decompress_cluster(bs, cluster_offset) < 0) {
648 ret = -EIO;
649 break;
651 memcpy(buf,
652 s->cluster_cache + index_in_cluster * 512, 512 * n);
653 } else {
654 if ((cluster_offset & 511) != 0) {
655 ret = -EIO;
656 break;
658 hd_iov.iov_base = (void *)buf;
659 hd_iov.iov_len = n * 512;
660 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
661 qemu_co_mutex_unlock(&s->lock);
662 ret = bdrv_co_readv(bs->file,
663 (cluster_offset >> 9) + index_in_cluster,
664 n, &hd_qiov);
665 qemu_co_mutex_lock(&s->lock);
666 if (ret < 0) {
667 break;
669 if (bs->encrypted) {
670 assert(s->crypto);
671 if (qcrypto_block_decrypt(s->crypto, sector_num, buf,
672 n * BDRV_SECTOR_SIZE, NULL) < 0) {
673 ret = -EIO;
674 break;
678 ret = 0;
680 nb_sectors -= n;
681 sector_num += n;
682 buf += n * 512;
685 qemu_co_mutex_unlock(&s->lock);
687 if (qiov->niov > 1) {
688 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
689 qemu_vfree(orig_buf);
692 return ret;
695 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
696 int nb_sectors, QEMUIOVector *qiov)
698 BDRVQcowState *s = bs->opaque;
699 int index_in_cluster;
700 uint64_t cluster_offset;
701 int ret = 0, n;
702 struct iovec hd_iov;
703 QEMUIOVector hd_qiov;
704 uint8_t *buf;
705 void *orig_buf;
707 s->cluster_cache_offset = -1; /* disable compressed cache */
709 /* We must always copy the iov when encrypting, so we
710 * don't modify the original data buffer during encryption */
711 if (bs->encrypted || qiov->niov > 1) {
712 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
713 if (buf == NULL) {
714 return -ENOMEM;
716 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
717 } else {
718 orig_buf = NULL;
719 buf = (uint8_t *)qiov->iov->iov_base;
722 qemu_co_mutex_lock(&s->lock);
724 while (nb_sectors != 0) {
726 index_in_cluster = sector_num & (s->cluster_sectors - 1);
727 n = s->cluster_sectors - index_in_cluster;
728 if (n > nb_sectors) {
729 n = nb_sectors;
731 ret = get_cluster_offset(bs, sector_num << 9, 1, 0,
732 index_in_cluster,
733 index_in_cluster + n, &cluster_offset);
734 if (ret < 0) {
735 break;
737 if (!cluster_offset || (cluster_offset & 511) != 0) {
738 ret = -EIO;
739 break;
741 if (bs->encrypted) {
742 assert(s->crypto);
743 if (qcrypto_block_encrypt(s->crypto, sector_num, buf,
744 n * BDRV_SECTOR_SIZE, NULL) < 0) {
745 ret = -EIO;
746 break;
750 hd_iov.iov_base = (void *)buf;
751 hd_iov.iov_len = n * 512;
752 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
753 qemu_co_mutex_unlock(&s->lock);
754 ret = bdrv_co_writev(bs->file,
755 (cluster_offset >> 9) + index_in_cluster,
756 n, &hd_qiov);
757 qemu_co_mutex_lock(&s->lock);
758 if (ret < 0) {
759 break;
761 ret = 0;
763 nb_sectors -= n;
764 sector_num += n;
765 buf += n * 512;
767 qemu_co_mutex_unlock(&s->lock);
769 qemu_vfree(orig_buf);
771 return ret;
774 static void qcow_close(BlockDriverState *bs)
776 BDRVQcowState *s = bs->opaque;
778 qcrypto_block_free(s->crypto);
779 s->crypto = NULL;
780 g_free(s->l1_table);
781 qemu_vfree(s->l2_cache);
782 g_free(s->cluster_cache);
783 g_free(s->cluster_data);
785 migrate_del_blocker(s->migration_blocker);
786 error_free(s->migration_blocker);
789 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
791 int header_size, backing_filename_len, l1_size, shift, i;
792 QCowHeader header;
793 uint8_t *tmp;
794 int64_t total_size = 0;
795 char *backing_file = NULL;
796 Error *local_err = NULL;
797 int ret;
798 BlockBackend *qcow_blk;
799 char *encryptfmt = NULL;
800 QDict *options;
801 QDict *encryptopts = NULL;
802 QCryptoBlockCreateOptions *crypto_opts = NULL;
803 QCryptoBlock *crypto = NULL;
805 /* Read out options */
806 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
807 BDRV_SECTOR_SIZE);
808 if (total_size == 0) {
809 error_setg(errp, "Image size is too small, cannot be zero length");
810 ret = -EINVAL;
811 goto cleanup;
814 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
815 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
816 if (encryptfmt) {
817 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
818 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
819 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
820 ret = -EINVAL;
821 goto cleanup;
823 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
824 encryptfmt = g_strdup("aes");
827 ret = bdrv_create_file(filename, opts, &local_err);
828 if (ret < 0) {
829 error_propagate(errp, local_err);
830 goto cleanup;
833 qcow_blk = blk_new_open(filename, NULL, NULL,
834 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
835 &local_err);
836 if (qcow_blk == NULL) {
837 error_propagate(errp, local_err);
838 ret = -EIO;
839 goto cleanup;
842 blk_set_allow_write_beyond_eof(qcow_blk, true);
844 ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp);
845 if (ret < 0) {
846 goto exit;
849 memset(&header, 0, sizeof(header));
850 header.magic = cpu_to_be32(QCOW_MAGIC);
851 header.version = cpu_to_be32(QCOW_VERSION);
852 header.size = cpu_to_be64(total_size);
853 header_size = sizeof(header);
854 backing_filename_len = 0;
855 if (backing_file) {
856 if (strcmp(backing_file, "fat:")) {
857 header.backing_file_offset = cpu_to_be64(header_size);
858 backing_filename_len = strlen(backing_file);
859 header.backing_file_size = cpu_to_be32(backing_filename_len);
860 header_size += backing_filename_len;
861 } else {
862 /* special backing file for vvfat */
863 g_free(backing_file);
864 backing_file = NULL;
866 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
867 unmodified sectors */
868 header.l2_bits = 12; /* 32 KB L2 tables */
869 } else {
870 header.cluster_bits = 12; /* 4 KB clusters */
871 header.l2_bits = 9; /* 4 KB L2 tables */
873 header_size = (header_size + 7) & ~7;
874 shift = header.cluster_bits + header.l2_bits;
875 l1_size = (total_size + (1LL << shift) - 1) >> shift;
877 header.l1_table_offset = cpu_to_be64(header_size);
879 options = qemu_opts_to_qdict(opts, NULL);
880 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
881 QDECREF(options);
882 if (encryptfmt) {
883 if (!g_str_equal(encryptfmt, "aes")) {
884 error_setg(errp, "Unknown encryption format '%s', expected 'aes'",
885 encryptfmt);
886 ret = -EINVAL;
887 goto exit;
889 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
891 crypto_opts = block_crypto_create_opts_init(
892 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
893 if (!crypto_opts) {
894 ret = -EINVAL;
895 goto exit;
898 crypto = qcrypto_block_create(crypto_opts, "encrypt.",
899 NULL, NULL, NULL, errp);
900 if (!crypto) {
901 ret = -EINVAL;
902 goto exit;
904 } else {
905 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
908 /* write all the data */
909 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
910 if (ret != sizeof(header)) {
911 goto exit;
914 if (backing_file) {
915 ret = blk_pwrite(qcow_blk, sizeof(header),
916 backing_file, backing_filename_len, 0);
917 if (ret != backing_filename_len) {
918 goto exit;
922 tmp = g_malloc0(BDRV_SECTOR_SIZE);
923 for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
924 i++) {
925 ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
926 tmp, BDRV_SECTOR_SIZE, 0);
927 if (ret != BDRV_SECTOR_SIZE) {
928 g_free(tmp);
929 goto exit;
933 g_free(tmp);
934 ret = 0;
935 exit:
936 blk_unref(qcow_blk);
937 cleanup:
938 QDECREF(encryptopts);
939 g_free(encryptfmt);
940 qcrypto_block_free(crypto);
941 qapi_free_QCryptoBlockCreateOptions(crypto_opts);
942 g_free(backing_file);
943 return ret;
946 static int qcow_make_empty(BlockDriverState *bs)
948 BDRVQcowState *s = bs->opaque;
949 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
950 int ret;
952 memset(s->l1_table, 0, l1_length);
953 if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
954 l1_length) < 0)
955 return -1;
956 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length,
957 PREALLOC_MODE_OFF, NULL);
958 if (ret < 0)
959 return ret;
961 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
962 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
963 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
965 return 0;
968 /* XXX: put compressed sectors first, then all the cluster aligned
969 tables to avoid losing bytes in alignment */
970 static coroutine_fn int
971 qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
972 uint64_t bytes, QEMUIOVector *qiov)
974 BDRVQcowState *s = bs->opaque;
975 QEMUIOVector hd_qiov;
976 struct iovec iov;
977 z_stream strm;
978 int ret, out_len;
979 uint8_t *buf, *out_buf;
980 uint64_t cluster_offset;
982 buf = qemu_blockalign(bs, s->cluster_size);
983 if (bytes != s->cluster_size) {
984 if (bytes > s->cluster_size ||
985 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
987 qemu_vfree(buf);
988 return -EINVAL;
990 /* Zero-pad last write if image size is not cluster aligned */
991 memset(buf + bytes, 0, s->cluster_size - bytes);
993 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
995 out_buf = g_malloc(s->cluster_size);
997 /* best compression, small window, no zlib header */
998 memset(&strm, 0, sizeof(strm));
999 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1000 Z_DEFLATED, -12,
1001 9, Z_DEFAULT_STRATEGY);
1002 if (ret != 0) {
1003 ret = -EINVAL;
1004 goto fail;
1007 strm.avail_in = s->cluster_size;
1008 strm.next_in = (uint8_t *)buf;
1009 strm.avail_out = s->cluster_size;
1010 strm.next_out = out_buf;
1012 ret = deflate(&strm, Z_FINISH);
1013 if (ret != Z_STREAM_END && ret != Z_OK) {
1014 deflateEnd(&strm);
1015 ret = -EINVAL;
1016 goto fail;
1018 out_len = strm.next_out - out_buf;
1020 deflateEnd(&strm);
1022 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1023 /* could not compress: write normal cluster */
1024 ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,
1025 bytes >> BDRV_SECTOR_BITS, qiov);
1026 if (ret < 0) {
1027 goto fail;
1029 goto success;
1031 qemu_co_mutex_lock(&s->lock);
1032 ret = get_cluster_offset(bs, offset, 2, out_len, 0, 0, &cluster_offset);
1033 qemu_co_mutex_unlock(&s->lock);
1034 if (ret < 0) {
1035 goto fail;
1037 if (cluster_offset == 0) {
1038 ret = -EIO;
1039 goto fail;
1041 cluster_offset &= s->cluster_offset_mask;
1043 iov = (struct iovec) {
1044 .iov_base = out_buf,
1045 .iov_len = out_len,
1047 qemu_iovec_init_external(&hd_qiov, &iov, 1);
1048 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
1049 if (ret < 0) {
1050 goto fail;
1052 success:
1053 ret = 0;
1054 fail:
1055 qemu_vfree(buf);
1056 g_free(out_buf);
1057 return ret;
1060 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1062 BDRVQcowState *s = bs->opaque;
1063 bdi->cluster_size = s->cluster_size;
1064 return 0;
1067 static QemuOptsList qcow_create_opts = {
1068 .name = "qcow-create-opts",
1069 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1070 .desc = {
1072 .name = BLOCK_OPT_SIZE,
1073 .type = QEMU_OPT_SIZE,
1074 .help = "Virtual disk size"
1077 .name = BLOCK_OPT_BACKING_FILE,
1078 .type = QEMU_OPT_STRING,
1079 .help = "File name of a base image"
1082 .name = BLOCK_OPT_ENCRYPT,
1083 .type = QEMU_OPT_BOOL,
1084 .help = "Encrypt the image with format 'aes'. (Deprecated "
1085 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
1088 .name = BLOCK_OPT_ENCRYPT_FORMAT,
1089 .type = QEMU_OPT_STRING,
1090 .help = "Encrypt the image, format choices: 'aes'",
1092 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
1093 { /* end of list */ }
1097 static BlockDriver bdrv_qcow = {
1098 .format_name = "qcow",
1099 .instance_size = sizeof(BDRVQcowState),
1100 .bdrv_probe = qcow_probe,
1101 .bdrv_open = qcow_open,
1102 .bdrv_close = qcow_close,
1103 .bdrv_child_perm = bdrv_format_default_perms,
1104 .bdrv_reopen_prepare = qcow_reopen_prepare,
1105 .bdrv_create = qcow_create,
1106 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1107 .supports_backing = true,
1109 .bdrv_co_readv = qcow_co_readv,
1110 .bdrv_co_writev = qcow_co_writev,
1111 .bdrv_co_get_block_status = qcow_co_get_block_status,
1113 .bdrv_make_empty = qcow_make_empty,
1114 .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed,
1115 .bdrv_get_info = qcow_get_info,
1117 .create_opts = &qcow_create_opts,
1120 static void bdrv_qcow_init(void)
1122 bdrv_register(&bdrv_qcow);
1125 block_init(bdrv_qcow_init);