hw/net/stellaris_enet: Fix a typo
[qemu/ar7.git] / block / qcow.c
blob5532731b9fcb08b33429b9a7232081991ba8940d
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.
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu/error-report.h"
28 #include "block/block_int.h"
29 #include "block/qdict.h"
30 #include "sysemu/block-backend.h"
31 #include "qemu/module.h"
32 #include "qemu/option.h"
33 #include "qemu/bswap.h"
34 #include <zlib.h>
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "qapi/qobject-input-visitor.h"
38 #include "qapi/qapi-visit-block-core.h"
39 #include "crypto/block.h"
40 #include "migration/blocker.h"
41 #include "crypto.h"
43 /**************************************************************/
44 /* QEMU COW block driver with compression and encryption support */
46 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
47 #define QCOW_VERSION 1
49 #define QCOW_CRYPT_NONE 0
50 #define QCOW_CRYPT_AES 1
52 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
54 typedef struct QCowHeader {
55 uint32_t magic;
56 uint32_t version;
57 uint64_t backing_file_offset;
58 uint32_t backing_file_size;
59 uint32_t mtime;
60 uint64_t size; /* in bytes */
61 uint8_t cluster_bits;
62 uint8_t l2_bits;
63 uint16_t padding;
64 uint32_t crypt_method;
65 uint64_t l1_table_offset;
66 } QEMU_PACKED QCowHeader;
68 #define L2_CACHE_SIZE 16
70 typedef struct BDRVQcowState {
71 int cluster_bits;
72 int cluster_size;
73 int cluster_sectors;
74 int l2_bits;
75 int l2_size;
76 unsigned int l1_size;
77 uint64_t cluster_offset_mask;
78 uint64_t l1_table_offset;
79 uint64_t *l1_table;
80 uint64_t *l2_cache;
81 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
82 uint32_t l2_cache_counts[L2_CACHE_SIZE];
83 uint8_t *cluster_cache;
84 uint8_t *cluster_data;
85 uint64_t cluster_cache_offset;
86 QCryptoBlock *crypto; /* Disk encryption format driver */
87 uint32_t crypt_method_header;
88 CoMutex lock;
89 Error *migration_blocker;
90 } BDRVQcowState;
92 static QemuOptsList qcow_create_opts;
94 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
96 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
98 const QCowHeader *cow_header = (const void *)buf;
100 if (buf_size >= sizeof(QCowHeader) &&
101 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
102 be32_to_cpu(cow_header->version) == QCOW_VERSION)
103 return 100;
104 else
105 return 0;
108 static QemuOptsList qcow_runtime_opts = {
109 .name = "qcow",
110 .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head),
111 .desc = {
112 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
113 { /* end of list */ }
117 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
118 Error **errp)
120 BDRVQcowState *s = bs->opaque;
121 unsigned int len, i, shift;
122 int ret;
123 QCowHeader header;
124 Error *local_err = NULL;
125 QCryptoBlockOpenOptions *crypto_opts = NULL;
126 unsigned int cflags = 0;
127 QDict *encryptopts = NULL;
128 const char *encryptfmt;
130 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
131 encryptfmt = qdict_get_try_str(encryptopts, "format");
133 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
134 false, errp);
135 if (!bs->file) {
136 ret = -EINVAL;
137 goto fail;
140 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
141 if (ret < 0) {
142 goto fail;
144 be32_to_cpus(&header.magic);
145 be32_to_cpus(&header.version);
146 be64_to_cpus(&header.backing_file_offset);
147 be32_to_cpus(&header.backing_file_size);
148 be32_to_cpus(&header.mtime);
149 be64_to_cpus(&header.size);
150 be32_to_cpus(&header.crypt_method);
151 be64_to_cpus(&header.l1_table_offset);
153 if (header.magic != QCOW_MAGIC) {
154 error_setg(errp, "Image not in qcow format");
155 ret = -EINVAL;
156 goto fail;
158 if (header.version != QCOW_VERSION) {
159 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
160 ret = -ENOTSUP;
161 goto fail;
164 if (header.size <= 1) {
165 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
166 ret = -EINVAL;
167 goto fail;
169 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
170 error_setg(errp, "Cluster size must be between 512 and 64k");
171 ret = -EINVAL;
172 goto fail;
175 /* l2_bits specifies number of entries; storing a uint64_t in each entry,
176 * so bytes = num_entries << 3. */
177 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
178 error_setg(errp, "L2 table size must be between 512 and 64k");
179 ret = -EINVAL;
180 goto fail;
183 s->crypt_method_header = header.crypt_method;
184 if (s->crypt_method_header) {
185 if (bdrv_uses_whitelist() &&
186 s->crypt_method_header == QCOW_CRYPT_AES) {
187 error_setg(errp,
188 "Use of AES-CBC encrypted qcow images is no longer "
189 "supported in system emulators");
190 error_append_hint(errp,
191 "You can use 'qemu-img convert' to convert your "
192 "image to an alternative supported format, such "
193 "as unencrypted qcow, or raw with the LUKS "
194 "format instead.\n");
195 ret = -ENOSYS;
196 goto fail;
198 if (s->crypt_method_header == QCOW_CRYPT_AES) {
199 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
200 error_setg(errp,
201 "Header reported 'aes' encryption format but "
202 "options specify '%s'", encryptfmt);
203 ret = -EINVAL;
204 goto fail;
206 qdict_del(encryptopts, "format");
207 crypto_opts = block_crypto_open_opts_init(
208 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
209 if (!crypto_opts) {
210 ret = -EINVAL;
211 goto fail;
214 if (flags & BDRV_O_NO_IO) {
215 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
217 s->crypto = qcrypto_block_open(crypto_opts, "encrypt.",
218 NULL, NULL, cflags, errp);
219 if (!s->crypto) {
220 ret = -EINVAL;
221 goto fail;
223 } else {
224 error_setg(errp, "invalid encryption method in qcow header");
225 ret = -EINVAL;
226 goto fail;
228 bs->encrypted = true;
229 } else {
230 if (encryptfmt) {
231 error_setg(errp, "No encryption in image header, but options "
232 "specified format '%s'", encryptfmt);
233 ret = -EINVAL;
234 goto fail;
237 s->cluster_bits = header.cluster_bits;
238 s->cluster_size = 1 << s->cluster_bits;
239 s->cluster_sectors = 1 << (s->cluster_bits - 9);
240 s->l2_bits = header.l2_bits;
241 s->l2_size = 1 << s->l2_bits;
242 bs->total_sectors = header.size / 512;
243 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
245 /* read the level 1 table */
246 shift = s->cluster_bits + s->l2_bits;
247 if (header.size > UINT64_MAX - (1LL << shift)) {
248 error_setg(errp, "Image too large");
249 ret = -EINVAL;
250 goto fail;
251 } else {
252 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
253 if (l1_size > INT_MAX / sizeof(uint64_t)) {
254 error_setg(errp, "Image too large");
255 ret = -EINVAL;
256 goto fail;
258 s->l1_size = l1_size;
261 s->l1_table_offset = header.l1_table_offset;
262 s->l1_table = g_try_new(uint64_t, s->l1_size);
263 if (s->l1_table == NULL) {
264 error_setg(errp, "Could not allocate memory for L1 table");
265 ret = -ENOMEM;
266 goto fail;
269 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
270 s->l1_size * sizeof(uint64_t));
271 if (ret < 0) {
272 goto fail;
275 for(i = 0;i < s->l1_size; i++) {
276 be64_to_cpus(&s->l1_table[i]);
279 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
280 s->l2_cache =
281 qemu_try_blockalign(bs->file->bs,
282 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
283 if (s->l2_cache == NULL) {
284 error_setg(errp, "Could not allocate L2 table cache");
285 ret = -ENOMEM;
286 goto fail;
288 s->cluster_cache = g_malloc(s->cluster_size);
289 s->cluster_data = g_malloc(s->cluster_size);
290 s->cluster_cache_offset = -1;
292 /* read the backing file name */
293 if (header.backing_file_offset != 0) {
294 len = header.backing_file_size;
295 if (len > 1023 || len >= sizeof(bs->backing_file)) {
296 error_setg(errp, "Backing file name too long");
297 ret = -EINVAL;
298 goto fail;
300 ret = bdrv_pread(bs->file, header.backing_file_offset,
301 bs->backing_file, len);
302 if (ret < 0) {
303 goto fail;
305 bs->backing_file[len] = '\0';
308 /* Disable migration when qcow images are used */
309 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
310 "does not support live migration",
311 bdrv_get_device_or_node_name(bs));
312 ret = migrate_add_blocker(s->migration_blocker, &local_err);
313 if (local_err) {
314 error_propagate(errp, local_err);
315 error_free(s->migration_blocker);
316 goto fail;
319 qobject_unref(encryptopts);
320 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
321 qemu_co_mutex_init(&s->lock);
322 return 0;
324 fail:
325 g_free(s->l1_table);
326 qemu_vfree(s->l2_cache);
327 g_free(s->cluster_cache);
328 g_free(s->cluster_data);
329 qcrypto_block_free(s->crypto);
330 qobject_unref(encryptopts);
331 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
332 return ret;
336 /* We have nothing to do for QCOW reopen, stubs just return
337 * success */
338 static int qcow_reopen_prepare(BDRVReopenState *state,
339 BlockReopenQueue *queue, Error **errp)
341 return 0;
345 /* 'allocate' is:
347 * 0 to not allocate.
349 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
350 * 'n_end')
352 * 2 to allocate a compressed cluster of size
353 * 'compressed_size'. 'compressed_size' must be > 0 and <
354 * cluster_size
356 * return 0 if not allocated, 1 if *result is assigned, and negative
357 * errno on failure.
359 static int get_cluster_offset(BlockDriverState *bs,
360 uint64_t offset, int allocate,
361 int compressed_size,
362 int n_start, int n_end, uint64_t *result)
364 BDRVQcowState *s = bs->opaque;
365 int min_index, i, j, l1_index, l2_index, ret;
366 int64_t l2_offset;
367 uint64_t *l2_table, cluster_offset, tmp;
368 uint32_t min_count;
369 int new_l2_table;
371 *result = 0;
372 l1_index = offset >> (s->l2_bits + s->cluster_bits);
373 l2_offset = s->l1_table[l1_index];
374 new_l2_table = 0;
375 if (!l2_offset) {
376 if (!allocate)
377 return 0;
378 /* allocate a new l2 entry */
379 l2_offset = bdrv_getlength(bs->file->bs);
380 if (l2_offset < 0) {
381 return l2_offset;
383 /* round to cluster size */
384 l2_offset = QEMU_ALIGN_UP(l2_offset, s->cluster_size);
385 /* update the L1 entry */
386 s->l1_table[l1_index] = l2_offset;
387 tmp = cpu_to_be64(l2_offset);
388 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
389 ret = bdrv_pwrite_sync(bs->file,
390 s->l1_table_offset + l1_index * sizeof(tmp),
391 &tmp, sizeof(tmp));
392 if (ret < 0) {
393 return ret;
395 new_l2_table = 1;
397 for(i = 0; i < L2_CACHE_SIZE; i++) {
398 if (l2_offset == s->l2_cache_offsets[i]) {
399 /* increment the hit count */
400 if (++s->l2_cache_counts[i] == 0xffffffff) {
401 for(j = 0; j < L2_CACHE_SIZE; j++) {
402 s->l2_cache_counts[j] >>= 1;
405 l2_table = s->l2_cache + (i << s->l2_bits);
406 goto found;
409 /* not found: load a new entry in the least used one */
410 min_index = 0;
411 min_count = 0xffffffff;
412 for(i = 0; i < L2_CACHE_SIZE; i++) {
413 if (s->l2_cache_counts[i] < min_count) {
414 min_count = s->l2_cache_counts[i];
415 min_index = i;
418 l2_table = s->l2_cache + (min_index << s->l2_bits);
419 BLKDBG_EVENT(bs->file, BLKDBG_L2_LOAD);
420 if (new_l2_table) {
421 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
422 ret = bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
423 s->l2_size * sizeof(uint64_t));
424 if (ret < 0) {
425 return ret;
427 } else {
428 ret = bdrv_pread(bs->file, l2_offset, l2_table,
429 s->l2_size * sizeof(uint64_t));
430 if (ret < 0) {
431 return ret;
434 s->l2_cache_offsets[min_index] = l2_offset;
435 s->l2_cache_counts[min_index] = 1;
436 found:
437 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
438 cluster_offset = be64_to_cpu(l2_table[l2_index]);
439 if (!cluster_offset ||
440 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
441 if (!allocate)
442 return 0;
443 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);
444 /* allocate a new cluster */
445 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
446 (n_end - n_start) < s->cluster_sectors) {
447 /* if the cluster is already compressed, we must
448 decompress it in the case it is not completely
449 overwritten */
450 if (decompress_cluster(bs, cluster_offset) < 0) {
451 return -EIO;
453 cluster_offset = bdrv_getlength(bs->file->bs);
454 if ((int64_t) cluster_offset < 0) {
455 return cluster_offset;
457 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
458 /* write the cluster content */
459 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
460 ret = bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
461 s->cluster_size);
462 if (ret < 0) {
463 return ret;
465 } else {
466 cluster_offset = bdrv_getlength(bs->file->bs);
467 if ((int64_t) cluster_offset < 0) {
468 return cluster_offset;
470 if (allocate == 1) {
471 /* round to cluster size */
472 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
473 if (cluster_offset + s->cluster_size > INT64_MAX) {
474 return -E2BIG;
476 ret = bdrv_truncate(bs->file, cluster_offset + s->cluster_size,
477 PREALLOC_MODE_OFF, NULL);
478 if (ret < 0) {
479 return ret;
481 /* if encrypted, we must initialize the cluster
482 content which won't be written */
483 if (bs->encrypted &&
484 (n_end - n_start) < s->cluster_sectors) {
485 uint64_t start_sect;
486 assert(s->crypto);
487 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
488 for(i = 0; i < s->cluster_sectors; i++) {
489 if (i < n_start || i >= n_end) {
490 memset(s->cluster_data, 0x00, 512);
491 if (qcrypto_block_encrypt(s->crypto,
492 (start_sect + i) *
493 BDRV_SECTOR_SIZE,
494 s->cluster_data,
495 BDRV_SECTOR_SIZE,
496 NULL) < 0) {
497 return -EIO;
499 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
500 ret = bdrv_pwrite(bs->file,
501 cluster_offset + i * 512,
502 s->cluster_data, 512);
503 if (ret < 0) {
504 return ret;
509 } else if (allocate == 2) {
510 cluster_offset |= QCOW_OFLAG_COMPRESSED |
511 (uint64_t)compressed_size << (63 - s->cluster_bits);
514 /* update L2 table */
515 tmp = cpu_to_be64(cluster_offset);
516 l2_table[l2_index] = tmp;
517 if (allocate == 2) {
518 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
519 } else {
520 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE);
522 ret = bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
523 &tmp, sizeof(tmp));
524 if (ret < 0) {
525 return ret;
528 *result = cluster_offset;
529 return 1;
532 static int coroutine_fn qcow_co_block_status(BlockDriverState *bs,
533 bool want_zero,
534 int64_t offset, int64_t bytes,
535 int64_t *pnum, int64_t *map,
536 BlockDriverState **file)
538 BDRVQcowState *s = bs->opaque;
539 int index_in_cluster, ret;
540 int64_t n;
541 uint64_t cluster_offset;
543 qemu_co_mutex_lock(&s->lock);
544 ret = get_cluster_offset(bs, offset, 0, 0, 0, 0, &cluster_offset);
545 qemu_co_mutex_unlock(&s->lock);
546 if (ret < 0) {
547 return ret;
549 index_in_cluster = offset & (s->cluster_size - 1);
550 n = s->cluster_size - index_in_cluster;
551 if (n > bytes) {
552 n = bytes;
554 *pnum = n;
555 if (!cluster_offset) {
556 return 0;
558 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) {
559 return BDRV_BLOCK_DATA;
561 *map = cluster_offset | index_in_cluster;
562 *file = bs->file->bs;
563 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
566 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
567 const uint8_t *buf, int buf_size)
569 z_stream strm1, *strm = &strm1;
570 int ret, out_len;
572 memset(strm, 0, sizeof(*strm));
574 strm->next_in = (uint8_t *)buf;
575 strm->avail_in = buf_size;
576 strm->next_out = out_buf;
577 strm->avail_out = out_buf_size;
579 ret = inflateInit2(strm, -12);
580 if (ret != Z_OK)
581 return -1;
582 ret = inflate(strm, Z_FINISH);
583 out_len = strm->next_out - out_buf;
584 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
585 out_len != out_buf_size) {
586 inflateEnd(strm);
587 return -1;
589 inflateEnd(strm);
590 return 0;
593 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
595 BDRVQcowState *s = bs->opaque;
596 int ret, csize;
597 uint64_t coffset;
599 coffset = cluster_offset & s->cluster_offset_mask;
600 if (s->cluster_cache_offset != coffset) {
601 csize = cluster_offset >> (63 - s->cluster_bits);
602 csize &= (s->cluster_size - 1);
603 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
604 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
605 if (ret != csize)
606 return -1;
607 if (decompress_buffer(s->cluster_cache, s->cluster_size,
608 s->cluster_data, csize) < 0) {
609 return -1;
611 s->cluster_cache_offset = coffset;
613 return 0;
616 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
617 int nb_sectors, QEMUIOVector *qiov)
619 BDRVQcowState *s = bs->opaque;
620 int index_in_cluster;
621 int ret = 0, n;
622 uint64_t cluster_offset;
623 struct iovec hd_iov;
624 QEMUIOVector hd_qiov;
625 uint8_t *buf;
626 void *orig_buf;
628 if (qiov->niov > 1) {
629 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
630 if (buf == NULL) {
631 return -ENOMEM;
633 } else {
634 orig_buf = NULL;
635 buf = (uint8_t *)qiov->iov->iov_base;
638 qemu_co_mutex_lock(&s->lock);
640 while (nb_sectors != 0) {
641 /* prepare next request */
642 ret = get_cluster_offset(bs, sector_num << 9,
643 0, 0, 0, 0, &cluster_offset);
644 if (ret < 0) {
645 break;
647 index_in_cluster = sector_num & (s->cluster_sectors - 1);
648 n = s->cluster_sectors - index_in_cluster;
649 if (n > nb_sectors) {
650 n = nb_sectors;
653 if (!cluster_offset) {
654 if (bs->backing) {
655 /* read from the base image */
656 hd_iov.iov_base = (void *)buf;
657 hd_iov.iov_len = n * 512;
658 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
659 qemu_co_mutex_unlock(&s->lock);
660 /* qcow2 emits this on bs->file instead of bs->backing */
661 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
662 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);
663 qemu_co_mutex_lock(&s->lock);
664 if (ret < 0) {
665 break;
667 } else {
668 /* Note: in this case, no need to wait */
669 memset(buf, 0, 512 * n);
671 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
672 /* add AIO support for compressed blocks ? */
673 if (decompress_cluster(bs, cluster_offset) < 0) {
674 ret = -EIO;
675 break;
677 memcpy(buf,
678 s->cluster_cache + index_in_cluster * 512, 512 * n);
679 } else {
680 if ((cluster_offset & 511) != 0) {
681 ret = -EIO;
682 break;
684 hd_iov.iov_base = (void *)buf;
685 hd_iov.iov_len = n * 512;
686 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
687 qemu_co_mutex_unlock(&s->lock);
688 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
689 ret = bdrv_co_readv(bs->file,
690 (cluster_offset >> 9) + index_in_cluster,
691 n, &hd_qiov);
692 qemu_co_mutex_lock(&s->lock);
693 if (ret < 0) {
694 break;
696 if (bs->encrypted) {
697 assert(s->crypto);
698 if (qcrypto_block_decrypt(s->crypto,
699 sector_num * BDRV_SECTOR_SIZE, buf,
700 n * BDRV_SECTOR_SIZE, NULL) < 0) {
701 ret = -EIO;
702 break;
706 ret = 0;
708 nb_sectors -= n;
709 sector_num += n;
710 buf += n * 512;
713 qemu_co_mutex_unlock(&s->lock);
715 if (qiov->niov > 1) {
716 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
717 qemu_vfree(orig_buf);
720 return ret;
723 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
724 int nb_sectors, QEMUIOVector *qiov,
725 int flags)
727 BDRVQcowState *s = bs->opaque;
728 int index_in_cluster;
729 uint64_t cluster_offset;
730 int ret = 0, n;
731 struct iovec hd_iov;
732 QEMUIOVector hd_qiov;
733 uint8_t *buf;
734 void *orig_buf;
736 assert(!flags);
737 s->cluster_cache_offset = -1; /* disable compressed cache */
739 /* We must always copy the iov when encrypting, so we
740 * don't modify the original data buffer during encryption */
741 if (bs->encrypted || qiov->niov > 1) {
742 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
743 if (buf == NULL) {
744 return -ENOMEM;
746 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
747 } else {
748 orig_buf = NULL;
749 buf = (uint8_t *)qiov->iov->iov_base;
752 qemu_co_mutex_lock(&s->lock);
754 while (nb_sectors != 0) {
756 index_in_cluster = sector_num & (s->cluster_sectors - 1);
757 n = s->cluster_sectors - index_in_cluster;
758 if (n > nb_sectors) {
759 n = nb_sectors;
761 ret = get_cluster_offset(bs, sector_num << 9, 1, 0,
762 index_in_cluster,
763 index_in_cluster + n, &cluster_offset);
764 if (ret < 0) {
765 break;
767 if (!cluster_offset || (cluster_offset & 511) != 0) {
768 ret = -EIO;
769 break;
771 if (bs->encrypted) {
772 assert(s->crypto);
773 if (qcrypto_block_encrypt(s->crypto, sector_num * BDRV_SECTOR_SIZE,
774 buf, n * BDRV_SECTOR_SIZE, NULL) < 0) {
775 ret = -EIO;
776 break;
780 hd_iov.iov_base = (void *)buf;
781 hd_iov.iov_len = n * 512;
782 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
783 qemu_co_mutex_unlock(&s->lock);
784 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
785 ret = bdrv_co_writev(bs->file,
786 (cluster_offset >> 9) + index_in_cluster,
787 n, &hd_qiov);
788 qemu_co_mutex_lock(&s->lock);
789 if (ret < 0) {
790 break;
792 ret = 0;
794 nb_sectors -= n;
795 sector_num += n;
796 buf += n * 512;
798 qemu_co_mutex_unlock(&s->lock);
800 qemu_vfree(orig_buf);
802 return ret;
805 static void qcow_close(BlockDriverState *bs)
807 BDRVQcowState *s = bs->opaque;
809 qcrypto_block_free(s->crypto);
810 s->crypto = NULL;
811 g_free(s->l1_table);
812 qemu_vfree(s->l2_cache);
813 g_free(s->cluster_cache);
814 g_free(s->cluster_data);
816 migrate_del_blocker(s->migration_blocker);
817 error_free(s->migration_blocker);
820 static int coroutine_fn qcow_co_create(BlockdevCreateOptions *opts,
821 Error **errp)
823 BlockdevCreateOptionsQcow *qcow_opts;
824 int header_size, backing_filename_len, l1_size, shift, i;
825 QCowHeader header;
826 uint8_t *tmp;
827 int64_t total_size = 0;
828 int ret;
829 BlockDriverState *bs;
830 BlockBackend *qcow_blk;
831 QCryptoBlock *crypto = NULL;
833 assert(opts->driver == BLOCKDEV_DRIVER_QCOW);
834 qcow_opts = &opts->u.qcow;
836 /* Sanity checks */
837 total_size = qcow_opts->size;
838 if (total_size == 0) {
839 error_setg(errp, "Image size is too small, cannot be zero length");
840 return -EINVAL;
843 if (qcow_opts->has_encrypt &&
844 qcow_opts->encrypt->format != Q_CRYPTO_BLOCK_FORMAT_QCOW)
846 error_setg(errp, "Unsupported encryption format");
847 return -EINVAL;
850 /* Create BlockBackend to write to the image */
851 bs = bdrv_open_blockdev_ref(qcow_opts->file, errp);
852 if (bs == NULL) {
853 return -EIO;
856 qcow_blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
857 ret = blk_insert_bs(qcow_blk, bs, errp);
858 if (ret < 0) {
859 goto exit;
861 blk_set_allow_write_beyond_eof(qcow_blk, true);
863 /* Create image format */
864 ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp);
865 if (ret < 0) {
866 goto exit;
869 memset(&header, 0, sizeof(header));
870 header.magic = cpu_to_be32(QCOW_MAGIC);
871 header.version = cpu_to_be32(QCOW_VERSION);
872 header.size = cpu_to_be64(total_size);
873 header_size = sizeof(header);
874 backing_filename_len = 0;
875 if (qcow_opts->has_backing_file) {
876 if (strcmp(qcow_opts->backing_file, "fat:")) {
877 header.backing_file_offset = cpu_to_be64(header_size);
878 backing_filename_len = strlen(qcow_opts->backing_file);
879 header.backing_file_size = cpu_to_be32(backing_filename_len);
880 header_size += backing_filename_len;
881 } else {
882 /* special backing file for vvfat */
883 qcow_opts->has_backing_file = false;
885 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
886 unmodified sectors */
887 header.l2_bits = 12; /* 32 KB L2 tables */
888 } else {
889 header.cluster_bits = 12; /* 4 KB clusters */
890 header.l2_bits = 9; /* 4 KB L2 tables */
892 header_size = (header_size + 7) & ~7;
893 shift = header.cluster_bits + header.l2_bits;
894 l1_size = (total_size + (1LL << shift) - 1) >> shift;
896 header.l1_table_offset = cpu_to_be64(header_size);
898 if (qcow_opts->has_encrypt) {
899 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
901 crypto = qcrypto_block_create(qcow_opts->encrypt, "encrypt.",
902 NULL, NULL, NULL, errp);
903 if (!crypto) {
904 ret = -EINVAL;
905 goto exit;
907 } else {
908 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
911 /* write all the data */
912 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
913 if (ret != sizeof(header)) {
914 goto exit;
917 if (qcow_opts->has_backing_file) {
918 ret = blk_pwrite(qcow_blk, sizeof(header),
919 qcow_opts->backing_file, backing_filename_len, 0);
920 if (ret != backing_filename_len) {
921 goto exit;
925 tmp = g_malloc0(BDRV_SECTOR_SIZE);
926 for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
927 i++) {
928 ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
929 tmp, BDRV_SECTOR_SIZE, 0);
930 if (ret != BDRV_SECTOR_SIZE) {
931 g_free(tmp);
932 goto exit;
936 g_free(tmp);
937 ret = 0;
938 exit:
939 blk_unref(qcow_blk);
940 qcrypto_block_free(crypto);
941 return ret;
944 static int coroutine_fn qcow_co_create_opts(const char *filename,
945 QemuOpts *opts, Error **errp)
947 BlockdevCreateOptions *create_options = NULL;
948 BlockDriverState *bs = NULL;
949 QDict *qdict;
950 Visitor *v;
951 const char *val;
952 Error *local_err = NULL;
953 int ret;
955 static const QDictRenames opt_renames[] = {
956 { BLOCK_OPT_BACKING_FILE, "backing-file" },
957 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
958 { NULL, NULL },
961 /* Parse options and convert legacy syntax */
962 qdict = qemu_opts_to_qdict_filtered(opts, NULL, &qcow_create_opts, true);
964 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
965 if (val && !strcmp(val, "on")) {
966 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
967 } else if (val && !strcmp(val, "off")) {
968 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
971 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
972 if (val && !strcmp(val, "aes")) {
973 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
976 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
977 ret = -EINVAL;
978 goto fail;
981 /* Create and open the file (protocol layer) */
982 ret = bdrv_create_file(filename, opts, &local_err);
983 if (ret < 0) {
984 error_propagate(errp, local_err);
985 goto fail;
988 bs = bdrv_open(filename, NULL, NULL,
989 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
990 if (bs == NULL) {
991 ret = -EIO;
992 goto fail;
995 /* Now get the QAPI type BlockdevCreateOptions */
996 qdict_put_str(qdict, "driver", "qcow");
997 qdict_put_str(qdict, "file", bs->node_name);
999 v = qobject_input_visitor_new_flat_confused(qdict, errp);
1000 if (!v) {
1001 ret = -EINVAL;
1002 goto fail;
1005 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
1006 visit_free(v);
1008 if (local_err) {
1009 error_propagate(errp, local_err);
1010 ret = -EINVAL;
1011 goto fail;
1014 /* Silently round up size */
1015 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW);
1016 create_options->u.qcow.size =
1017 ROUND_UP(create_options->u.qcow.size, BDRV_SECTOR_SIZE);
1019 /* Create the qcow image (format layer) */
1020 ret = qcow_co_create(create_options, errp);
1021 if (ret < 0) {
1022 goto fail;
1025 ret = 0;
1026 fail:
1027 qobject_unref(qdict);
1028 bdrv_unref(bs);
1029 qapi_free_BlockdevCreateOptions(create_options);
1030 return ret;
1033 static int qcow_make_empty(BlockDriverState *bs)
1035 BDRVQcowState *s = bs->opaque;
1036 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1037 int ret;
1039 memset(s->l1_table, 0, l1_length);
1040 if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
1041 l1_length) < 0)
1042 return -1;
1043 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length,
1044 PREALLOC_MODE_OFF, NULL);
1045 if (ret < 0)
1046 return ret;
1048 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
1049 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
1050 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
1052 return 0;
1055 /* XXX: put compressed sectors first, then all the cluster aligned
1056 tables to avoid losing bytes in alignment */
1057 static coroutine_fn int
1058 qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1059 uint64_t bytes, QEMUIOVector *qiov)
1061 BDRVQcowState *s = bs->opaque;
1062 QEMUIOVector hd_qiov;
1063 struct iovec iov;
1064 z_stream strm;
1065 int ret, out_len;
1066 uint8_t *buf, *out_buf;
1067 uint64_t cluster_offset;
1069 buf = qemu_blockalign(bs, s->cluster_size);
1070 if (bytes != s->cluster_size) {
1071 if (bytes > s->cluster_size ||
1072 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
1074 qemu_vfree(buf);
1075 return -EINVAL;
1077 /* Zero-pad last write if image size is not cluster aligned */
1078 memset(buf + bytes, 0, s->cluster_size - bytes);
1080 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
1082 out_buf = g_malloc(s->cluster_size);
1084 /* best compression, small window, no zlib header */
1085 memset(&strm, 0, sizeof(strm));
1086 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1087 Z_DEFLATED, -12,
1088 9, Z_DEFAULT_STRATEGY);
1089 if (ret != 0) {
1090 ret = -EINVAL;
1091 goto fail;
1094 strm.avail_in = s->cluster_size;
1095 strm.next_in = (uint8_t *)buf;
1096 strm.avail_out = s->cluster_size;
1097 strm.next_out = out_buf;
1099 ret = deflate(&strm, Z_FINISH);
1100 if (ret != Z_STREAM_END && ret != Z_OK) {
1101 deflateEnd(&strm);
1102 ret = -EINVAL;
1103 goto fail;
1105 out_len = strm.next_out - out_buf;
1107 deflateEnd(&strm);
1109 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1110 /* could not compress: write normal cluster */
1111 ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,
1112 bytes >> BDRV_SECTOR_BITS, qiov, 0);
1113 if (ret < 0) {
1114 goto fail;
1116 goto success;
1118 qemu_co_mutex_lock(&s->lock);
1119 ret = get_cluster_offset(bs, offset, 2, out_len, 0, 0, &cluster_offset);
1120 qemu_co_mutex_unlock(&s->lock);
1121 if (ret < 0) {
1122 goto fail;
1124 if (cluster_offset == 0) {
1125 ret = -EIO;
1126 goto fail;
1128 cluster_offset &= s->cluster_offset_mask;
1130 iov = (struct iovec) {
1131 .iov_base = out_buf,
1132 .iov_len = out_len,
1134 qemu_iovec_init_external(&hd_qiov, &iov, 1);
1135 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1136 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
1137 if (ret < 0) {
1138 goto fail;
1140 success:
1141 ret = 0;
1142 fail:
1143 qemu_vfree(buf);
1144 g_free(out_buf);
1145 return ret;
1148 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1150 BDRVQcowState *s = bs->opaque;
1151 bdi->cluster_size = s->cluster_size;
1152 return 0;
1155 static QemuOptsList qcow_create_opts = {
1156 .name = "qcow-create-opts",
1157 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1158 .desc = {
1160 .name = BLOCK_OPT_SIZE,
1161 .type = QEMU_OPT_SIZE,
1162 .help = "Virtual disk size"
1165 .name = BLOCK_OPT_BACKING_FILE,
1166 .type = QEMU_OPT_STRING,
1167 .help = "File name of a base image"
1170 .name = BLOCK_OPT_ENCRYPT,
1171 .type = QEMU_OPT_BOOL,
1172 .help = "Encrypt the image with format 'aes'. (Deprecated "
1173 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
1176 .name = BLOCK_OPT_ENCRYPT_FORMAT,
1177 .type = QEMU_OPT_STRING,
1178 .help = "Encrypt the image, format choices: 'aes'",
1180 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
1181 { /* end of list */ }
1185 static BlockDriver bdrv_qcow = {
1186 .format_name = "qcow",
1187 .instance_size = sizeof(BDRVQcowState),
1188 .bdrv_probe = qcow_probe,
1189 .bdrv_open = qcow_open,
1190 .bdrv_close = qcow_close,
1191 .bdrv_child_perm = bdrv_format_default_perms,
1192 .bdrv_reopen_prepare = qcow_reopen_prepare,
1193 .bdrv_co_create = qcow_co_create,
1194 .bdrv_co_create_opts = qcow_co_create_opts,
1195 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1196 .supports_backing = true,
1198 .bdrv_co_readv = qcow_co_readv,
1199 .bdrv_co_writev = qcow_co_writev,
1200 .bdrv_co_block_status = qcow_co_block_status,
1202 .bdrv_make_empty = qcow_make_empty,
1203 .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed,
1204 .bdrv_get_info = qcow_get_info,
1206 .create_opts = &qcow_create_opts,
1209 static void bdrv_qcow_init(void)
1211 bdrv_register(&bdrv_qcow);
1214 block_init(bdrv_qcow_init);