qcow: make encrypt_sectors encrypt in place
[qemu/ar7.git] / block / qcow.c
blob3a3dbf94390ebeb3233cfa3024ca04d64cc313d6
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 "crypto/cipher.h"
35 #include "migration/blocker.h"
37 /**************************************************************/
38 /* QEMU COW block driver with compression and encryption support */
40 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
41 #define QCOW_VERSION 1
43 #define QCOW_CRYPT_NONE 0
44 #define QCOW_CRYPT_AES 1
46 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
48 typedef struct QCowHeader {
49 uint32_t magic;
50 uint32_t version;
51 uint64_t backing_file_offset;
52 uint32_t backing_file_size;
53 uint32_t mtime;
54 uint64_t size; /* in bytes */
55 uint8_t cluster_bits;
56 uint8_t l2_bits;
57 uint16_t padding;
58 uint32_t crypt_method;
59 uint64_t l1_table_offset;
60 } QEMU_PACKED QCowHeader;
62 #define L2_CACHE_SIZE 16
64 typedef struct BDRVQcowState {
65 int cluster_bits;
66 int cluster_size;
67 int cluster_sectors;
68 int l2_bits;
69 int l2_size;
70 unsigned int l1_size;
71 uint64_t cluster_offset_mask;
72 uint64_t l1_table_offset;
73 uint64_t *l1_table;
74 uint64_t *l2_cache;
75 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
76 uint32_t l2_cache_counts[L2_CACHE_SIZE];
77 uint8_t *cluster_cache;
78 uint8_t *cluster_data;
79 uint64_t cluster_cache_offset;
80 QCryptoCipher *cipher; /* NULL if no key yet */
81 uint32_t crypt_method_header;
82 CoMutex lock;
83 Error *migration_blocker;
84 } BDRVQcowState;
86 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
88 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
90 const QCowHeader *cow_header = (const void *)buf;
92 if (buf_size >= sizeof(QCowHeader) &&
93 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
94 be32_to_cpu(cow_header->version) == QCOW_VERSION)
95 return 100;
96 else
97 return 0;
100 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
101 Error **errp)
103 BDRVQcowState *s = bs->opaque;
104 unsigned int len, i, shift;
105 int ret;
106 QCowHeader header;
107 Error *local_err = NULL;
109 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
110 false, errp);
111 if (!bs->file) {
112 return -EINVAL;
115 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
116 if (ret < 0) {
117 goto fail;
119 be32_to_cpus(&header.magic);
120 be32_to_cpus(&header.version);
121 be64_to_cpus(&header.backing_file_offset);
122 be32_to_cpus(&header.backing_file_size);
123 be32_to_cpus(&header.mtime);
124 be64_to_cpus(&header.size);
125 be32_to_cpus(&header.crypt_method);
126 be64_to_cpus(&header.l1_table_offset);
128 if (header.magic != QCOW_MAGIC) {
129 error_setg(errp, "Image not in qcow format");
130 ret = -EINVAL;
131 goto fail;
133 if (header.version != QCOW_VERSION) {
134 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
135 ret = -ENOTSUP;
136 goto fail;
139 if (header.size <= 1) {
140 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
141 ret = -EINVAL;
142 goto fail;
144 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
145 error_setg(errp, "Cluster size must be between 512 and 64k");
146 ret = -EINVAL;
147 goto fail;
150 /* l2_bits specifies number of entries; storing a uint64_t in each entry,
151 * so bytes = num_entries << 3. */
152 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
153 error_setg(errp, "L2 table size must be between 512 and 64k");
154 ret = -EINVAL;
155 goto fail;
158 if (header.crypt_method > QCOW_CRYPT_AES) {
159 error_setg(errp, "invalid encryption method in qcow header");
160 ret = -EINVAL;
161 goto fail;
163 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128,
164 QCRYPTO_CIPHER_MODE_CBC)) {
165 error_setg(errp, "AES cipher not available");
166 ret = -EINVAL;
167 goto fail;
169 s->crypt_method_header = header.crypt_method;
170 if (s->crypt_method_header) {
171 if (bdrv_uses_whitelist() &&
172 s->crypt_method_header == QCOW_CRYPT_AES) {
173 error_setg(errp,
174 "Use of AES-CBC encrypted qcow images is no longer "
175 "supported in system emulators");
176 error_append_hint(errp,
177 "You can use 'qemu-img convert' to convert your "
178 "image to an alternative supported format, such "
179 "as unencrypted qcow, or raw with the LUKS "
180 "format instead.\n");
181 ret = -ENOSYS;
182 goto fail;
185 bs->encrypted = true;
187 s->cluster_bits = header.cluster_bits;
188 s->cluster_size = 1 << s->cluster_bits;
189 s->cluster_sectors = 1 << (s->cluster_bits - 9);
190 s->l2_bits = header.l2_bits;
191 s->l2_size = 1 << s->l2_bits;
192 bs->total_sectors = header.size / 512;
193 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
195 /* read the level 1 table */
196 shift = s->cluster_bits + s->l2_bits;
197 if (header.size > UINT64_MAX - (1LL << shift)) {
198 error_setg(errp, "Image too large");
199 ret = -EINVAL;
200 goto fail;
201 } else {
202 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
203 if (l1_size > INT_MAX / sizeof(uint64_t)) {
204 error_setg(errp, "Image too large");
205 ret = -EINVAL;
206 goto fail;
208 s->l1_size = l1_size;
211 s->l1_table_offset = header.l1_table_offset;
212 s->l1_table = g_try_new(uint64_t, s->l1_size);
213 if (s->l1_table == NULL) {
214 error_setg(errp, "Could not allocate memory for L1 table");
215 ret = -ENOMEM;
216 goto fail;
219 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
220 s->l1_size * sizeof(uint64_t));
221 if (ret < 0) {
222 goto fail;
225 for(i = 0;i < s->l1_size; i++) {
226 be64_to_cpus(&s->l1_table[i]);
229 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
230 s->l2_cache =
231 qemu_try_blockalign(bs->file->bs,
232 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
233 if (s->l2_cache == NULL) {
234 error_setg(errp, "Could not allocate L2 table cache");
235 ret = -ENOMEM;
236 goto fail;
238 s->cluster_cache = g_malloc(s->cluster_size);
239 s->cluster_data = g_malloc(s->cluster_size);
240 s->cluster_cache_offset = -1;
242 /* read the backing file name */
243 if (header.backing_file_offset != 0) {
244 len = header.backing_file_size;
245 if (len > 1023 || len >= sizeof(bs->backing_file)) {
246 error_setg(errp, "Backing file name too long");
247 ret = -EINVAL;
248 goto fail;
250 ret = bdrv_pread(bs->file, header.backing_file_offset,
251 bs->backing_file, len);
252 if (ret < 0) {
253 goto fail;
255 bs->backing_file[len] = '\0';
258 /* Disable migration when qcow images are used */
259 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
260 "does not support live migration",
261 bdrv_get_device_or_node_name(bs));
262 ret = migrate_add_blocker(s->migration_blocker, &local_err);
263 if (local_err) {
264 error_propagate(errp, local_err);
265 error_free(s->migration_blocker);
266 goto fail;
269 qemu_co_mutex_init(&s->lock);
270 return 0;
272 fail:
273 g_free(s->l1_table);
274 qemu_vfree(s->l2_cache);
275 g_free(s->cluster_cache);
276 g_free(s->cluster_data);
277 return ret;
281 /* We have nothing to do for QCOW reopen, stubs just return
282 * success */
283 static int qcow_reopen_prepare(BDRVReopenState *state,
284 BlockReopenQueue *queue, Error **errp)
286 return 0;
289 static int qcow_set_key(BlockDriverState *bs, const char *key)
291 BDRVQcowState *s = bs->opaque;
292 uint8_t keybuf[16];
293 int len, i;
294 Error *err;
296 memset(keybuf, 0, 16);
297 len = strlen(key);
298 if (len > 16)
299 len = 16;
300 /* XXX: we could compress the chars to 7 bits to increase
301 entropy */
302 for(i = 0;i < len;i++) {
303 keybuf[i] = key[i];
305 assert(bs->encrypted);
307 qcrypto_cipher_free(s->cipher);
308 s->cipher = qcrypto_cipher_new(
309 QCRYPTO_CIPHER_ALG_AES_128,
310 QCRYPTO_CIPHER_MODE_CBC,
311 keybuf, G_N_ELEMENTS(keybuf),
312 &err);
314 if (!s->cipher) {
315 /* XXX would be nice if errors in this method could
316 * be properly propagate to the caller. Would need
317 * the bdrv_set_key() API signature to be fixed. */
318 error_free(err);
319 return -1;
321 return 0;
324 /* The crypt function is compatible with the linux cryptoloop
325 algorithm for < 4 GB images. */
326 static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
327 uint8_t *buf, int nb_sectors, bool enc,
328 Error **errp)
330 union {
331 uint64_t ll[2];
332 uint8_t b[16];
333 } ivec;
334 int i;
335 int ret;
337 for(i = 0; i < nb_sectors; i++) {
338 ivec.ll[0] = cpu_to_le64(sector_num);
339 ivec.ll[1] = 0;
340 if (qcrypto_cipher_setiv(s->cipher,
341 ivec.b, G_N_ELEMENTS(ivec.b),
342 errp) < 0) {
343 return -1;
345 if (enc) {
346 ret = qcrypto_cipher_encrypt(s->cipher,
347 buf, buf,
348 512,
349 errp);
350 } else {
351 ret = qcrypto_cipher_decrypt(s->cipher,
352 buf, buf,
353 512,
354 errp);
356 if (ret < 0) {
357 return -1;
359 sector_num++;
360 buf += 512;
362 return 0;
365 /* 'allocate' is:
367 * 0 to not allocate.
369 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
370 * 'n_end')
372 * 2 to allocate a compressed cluster of size
373 * 'compressed_size'. 'compressed_size' must be > 0 and <
374 * cluster_size
376 * return 0 if not allocated.
378 static uint64_t get_cluster_offset(BlockDriverState *bs,
379 uint64_t offset, int allocate,
380 int compressed_size,
381 int n_start, int n_end)
383 BDRVQcowState *s = bs->opaque;
384 int min_index, i, j, l1_index, l2_index;
385 uint64_t l2_offset, *l2_table, cluster_offset, tmp;
386 uint32_t min_count;
387 int new_l2_table;
389 l1_index = offset >> (s->l2_bits + s->cluster_bits);
390 l2_offset = s->l1_table[l1_index];
391 new_l2_table = 0;
392 if (!l2_offset) {
393 if (!allocate)
394 return 0;
395 /* allocate a new l2 entry */
396 l2_offset = bdrv_getlength(bs->file->bs);
397 /* round to cluster size */
398 l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
399 /* update the L1 entry */
400 s->l1_table[l1_index] = l2_offset;
401 tmp = cpu_to_be64(l2_offset);
402 if (bdrv_pwrite_sync(bs->file,
403 s->l1_table_offset + l1_index * sizeof(tmp),
404 &tmp, sizeof(tmp)) < 0)
405 return 0;
406 new_l2_table = 1;
408 for(i = 0; i < L2_CACHE_SIZE; i++) {
409 if (l2_offset == s->l2_cache_offsets[i]) {
410 /* increment the hit count */
411 if (++s->l2_cache_counts[i] == 0xffffffff) {
412 for(j = 0; j < L2_CACHE_SIZE; j++) {
413 s->l2_cache_counts[j] >>= 1;
416 l2_table = s->l2_cache + (i << s->l2_bits);
417 goto found;
420 /* not found: load a new entry in the least used one */
421 min_index = 0;
422 min_count = 0xffffffff;
423 for(i = 0; i < L2_CACHE_SIZE; i++) {
424 if (s->l2_cache_counts[i] < min_count) {
425 min_count = s->l2_cache_counts[i];
426 min_index = i;
429 l2_table = s->l2_cache + (min_index << s->l2_bits);
430 if (new_l2_table) {
431 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
432 if (bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
433 s->l2_size * sizeof(uint64_t)) < 0)
434 return 0;
435 } else {
436 if (bdrv_pread(bs->file, l2_offset, l2_table,
437 s->l2_size * sizeof(uint64_t)) !=
438 s->l2_size * sizeof(uint64_t))
439 return 0;
441 s->l2_cache_offsets[min_index] = l2_offset;
442 s->l2_cache_counts[min_index] = 1;
443 found:
444 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
445 cluster_offset = be64_to_cpu(l2_table[l2_index]);
446 if (!cluster_offset ||
447 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
448 if (!allocate)
449 return 0;
450 /* allocate a new cluster */
451 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
452 (n_end - n_start) < s->cluster_sectors) {
453 /* if the cluster is already compressed, we must
454 decompress it in the case it is not completely
455 overwritten */
456 if (decompress_cluster(bs, cluster_offset) < 0)
457 return 0;
458 cluster_offset = bdrv_getlength(bs->file->bs);
459 cluster_offset = (cluster_offset + s->cluster_size - 1) &
460 ~(s->cluster_size - 1);
461 /* write the cluster content */
462 if (bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
463 s->cluster_size) !=
464 s->cluster_size)
465 return -1;
466 } else {
467 cluster_offset = bdrv_getlength(bs->file->bs);
468 if (allocate == 1) {
469 /* round to cluster size */
470 cluster_offset = (cluster_offset + s->cluster_size - 1) &
471 ~(s->cluster_size - 1);
472 bdrv_truncate(bs->file, cluster_offset + s->cluster_size, NULL);
473 /* if encrypted, we must initialize the cluster
474 content which won't be written */
475 if (bs->encrypted &&
476 (n_end - n_start) < s->cluster_sectors) {
477 uint64_t start_sect;
478 assert(s->cipher);
479 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
480 for(i = 0; i < s->cluster_sectors; i++) {
481 if (i < n_start || i >= n_end) {
482 Error *err = NULL;
483 memset(s->cluster_data, 0x00, 512);
484 if (encrypt_sectors(s, start_sect + i,
485 s->cluster_data, 1,
486 true, &err) < 0) {
487 error_free(err);
488 errno = EIO;
489 return -1;
491 if (bdrv_pwrite(bs->file,
492 cluster_offset + i * 512,
493 s->cluster_data, 512) != 512)
494 return -1;
498 } else if (allocate == 2) {
499 cluster_offset |= QCOW_OFLAG_COMPRESSED |
500 (uint64_t)compressed_size << (63 - s->cluster_bits);
503 /* update L2 table */
504 tmp = cpu_to_be64(cluster_offset);
505 l2_table[l2_index] = tmp;
506 if (bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
507 &tmp, sizeof(tmp)) < 0)
508 return 0;
510 return cluster_offset;
513 static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
514 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
516 BDRVQcowState *s = bs->opaque;
517 int index_in_cluster, n;
518 uint64_t cluster_offset;
520 qemu_co_mutex_lock(&s->lock);
521 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
522 qemu_co_mutex_unlock(&s->lock);
523 index_in_cluster = sector_num & (s->cluster_sectors - 1);
524 n = s->cluster_sectors - index_in_cluster;
525 if (n > nb_sectors)
526 n = nb_sectors;
527 *pnum = n;
528 if (!cluster_offset) {
529 return 0;
531 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
532 return BDRV_BLOCK_DATA;
534 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
535 *file = bs->file->bs;
536 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
539 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
540 const uint8_t *buf, int buf_size)
542 z_stream strm1, *strm = &strm1;
543 int ret, out_len;
545 memset(strm, 0, sizeof(*strm));
547 strm->next_in = (uint8_t *)buf;
548 strm->avail_in = buf_size;
549 strm->next_out = out_buf;
550 strm->avail_out = out_buf_size;
552 ret = inflateInit2(strm, -12);
553 if (ret != Z_OK)
554 return -1;
555 ret = inflate(strm, Z_FINISH);
556 out_len = strm->next_out - out_buf;
557 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
558 out_len != out_buf_size) {
559 inflateEnd(strm);
560 return -1;
562 inflateEnd(strm);
563 return 0;
566 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
568 BDRVQcowState *s = bs->opaque;
569 int ret, csize;
570 uint64_t coffset;
572 coffset = cluster_offset & s->cluster_offset_mask;
573 if (s->cluster_cache_offset != coffset) {
574 csize = cluster_offset >> (63 - s->cluster_bits);
575 csize &= (s->cluster_size - 1);
576 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
577 if (ret != csize)
578 return -1;
579 if (decompress_buffer(s->cluster_cache, s->cluster_size,
580 s->cluster_data, csize) < 0) {
581 return -1;
583 s->cluster_cache_offset = coffset;
585 return 0;
588 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
589 int nb_sectors, QEMUIOVector *qiov)
591 BDRVQcowState *s = bs->opaque;
592 int index_in_cluster;
593 int ret = 0, n;
594 uint64_t cluster_offset;
595 struct iovec hd_iov;
596 QEMUIOVector hd_qiov;
597 uint8_t *buf;
598 void *orig_buf;
599 Error *err = NULL;
601 if (qiov->niov > 1) {
602 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
603 if (buf == NULL) {
604 return -ENOMEM;
606 } else {
607 orig_buf = NULL;
608 buf = (uint8_t *)qiov->iov->iov_base;
611 qemu_co_mutex_lock(&s->lock);
613 while (nb_sectors != 0) {
614 /* prepare next request */
615 cluster_offset = get_cluster_offset(bs, sector_num << 9,
616 0, 0, 0, 0);
617 index_in_cluster = sector_num & (s->cluster_sectors - 1);
618 n = s->cluster_sectors - index_in_cluster;
619 if (n > nb_sectors) {
620 n = nb_sectors;
623 if (!cluster_offset) {
624 if (bs->backing) {
625 /* read from the base image */
626 hd_iov.iov_base = (void *)buf;
627 hd_iov.iov_len = n * 512;
628 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
629 qemu_co_mutex_unlock(&s->lock);
630 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);
631 qemu_co_mutex_lock(&s->lock);
632 if (ret < 0) {
633 goto fail;
635 } else {
636 /* Note: in this case, no need to wait */
637 memset(buf, 0, 512 * n);
639 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
640 /* add AIO support for compressed blocks ? */
641 if (decompress_cluster(bs, cluster_offset) < 0) {
642 goto fail;
644 memcpy(buf,
645 s->cluster_cache + index_in_cluster * 512, 512 * n);
646 } else {
647 if ((cluster_offset & 511) != 0) {
648 goto fail;
650 hd_iov.iov_base = (void *)buf;
651 hd_iov.iov_len = n * 512;
652 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
653 qemu_co_mutex_unlock(&s->lock);
654 ret = bdrv_co_readv(bs->file,
655 (cluster_offset >> 9) + index_in_cluster,
656 n, &hd_qiov);
657 qemu_co_mutex_lock(&s->lock);
658 if (ret < 0) {
659 break;
661 if (bs->encrypted) {
662 assert(s->cipher);
663 if (encrypt_sectors(s, sector_num, buf,
664 n, false, &err) < 0) {
665 goto fail;
669 ret = 0;
671 nb_sectors -= n;
672 sector_num += n;
673 buf += n * 512;
676 done:
677 qemu_co_mutex_unlock(&s->lock);
679 if (qiov->niov > 1) {
680 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
681 qemu_vfree(orig_buf);
684 return ret;
686 fail:
687 error_free(err);
688 ret = -EIO;
689 goto done;
692 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
693 int nb_sectors, QEMUIOVector *qiov)
695 BDRVQcowState *s = bs->opaque;
696 int index_in_cluster;
697 uint64_t cluster_offset;
698 int ret = 0, n;
699 struct iovec hd_iov;
700 QEMUIOVector hd_qiov;
701 uint8_t *buf;
702 void *orig_buf;
704 s->cluster_cache_offset = -1; /* disable compressed cache */
706 /* We must always copy the iov when encrypting, so we
707 * don't modify the original data buffer during encryption */
708 if (bs->encrypted || qiov->niov > 1) {
709 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
710 if (buf == NULL) {
711 return -ENOMEM;
713 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
714 } else {
715 orig_buf = NULL;
716 buf = (uint8_t *)qiov->iov->iov_base;
719 qemu_co_mutex_lock(&s->lock);
721 while (nb_sectors != 0) {
723 index_in_cluster = sector_num & (s->cluster_sectors - 1);
724 n = s->cluster_sectors - index_in_cluster;
725 if (n > nb_sectors) {
726 n = nb_sectors;
728 cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
729 index_in_cluster,
730 index_in_cluster + n);
731 if (!cluster_offset || (cluster_offset & 511) != 0) {
732 ret = -EIO;
733 break;
735 if (bs->encrypted) {
736 Error *err = NULL;
737 assert(s->cipher);
738 if (encrypt_sectors(s, sector_num, buf, n, true, &err) < 0) {
739 error_free(err);
740 ret = -EIO;
741 break;
745 hd_iov.iov_base = (void *)buf;
746 hd_iov.iov_len = n * 512;
747 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
748 qemu_co_mutex_unlock(&s->lock);
749 ret = bdrv_co_writev(bs->file,
750 (cluster_offset >> 9) + index_in_cluster,
751 n, &hd_qiov);
752 qemu_co_mutex_lock(&s->lock);
753 if (ret < 0) {
754 break;
756 ret = 0;
758 nb_sectors -= n;
759 sector_num += n;
760 buf += n * 512;
762 qemu_co_mutex_unlock(&s->lock);
764 qemu_vfree(orig_buf);
766 return ret;
769 static void qcow_close(BlockDriverState *bs)
771 BDRVQcowState *s = bs->opaque;
773 qcrypto_cipher_free(s->cipher);
774 s->cipher = NULL;
775 g_free(s->l1_table);
776 qemu_vfree(s->l2_cache);
777 g_free(s->cluster_cache);
778 g_free(s->cluster_data);
780 migrate_del_blocker(s->migration_blocker);
781 error_free(s->migration_blocker);
784 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
786 int header_size, backing_filename_len, l1_size, shift, i;
787 QCowHeader header;
788 uint8_t *tmp;
789 int64_t total_size = 0;
790 char *backing_file = NULL;
791 Error *local_err = NULL;
792 int ret;
793 BlockBackend *qcow_blk;
794 const char *encryptfmt = NULL;
796 /* Read out options */
797 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
798 BDRV_SECTOR_SIZE);
799 if (total_size == 0) {
800 error_setg(errp, "Image size is too small, cannot be zero length");
801 ret = -EINVAL;
802 goto cleanup;
805 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
806 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
807 if (encryptfmt) {
808 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
809 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
810 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
811 ret = -EINVAL;
812 goto cleanup;
814 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
815 encryptfmt = "aes";
818 ret = bdrv_create_file(filename, opts, &local_err);
819 if (ret < 0) {
820 error_propagate(errp, local_err);
821 goto cleanup;
824 qcow_blk = blk_new_open(filename, NULL, NULL,
825 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
826 &local_err);
827 if (qcow_blk == NULL) {
828 error_propagate(errp, local_err);
829 ret = -EIO;
830 goto cleanup;
833 blk_set_allow_write_beyond_eof(qcow_blk, true);
835 ret = blk_truncate(qcow_blk, 0, errp);
836 if (ret < 0) {
837 goto exit;
840 memset(&header, 0, sizeof(header));
841 header.magic = cpu_to_be32(QCOW_MAGIC);
842 header.version = cpu_to_be32(QCOW_VERSION);
843 header.size = cpu_to_be64(total_size);
844 header_size = sizeof(header);
845 backing_filename_len = 0;
846 if (backing_file) {
847 if (strcmp(backing_file, "fat:")) {
848 header.backing_file_offset = cpu_to_be64(header_size);
849 backing_filename_len = strlen(backing_file);
850 header.backing_file_size = cpu_to_be32(backing_filename_len);
851 header_size += backing_filename_len;
852 } else {
853 /* special backing file for vvfat */
854 g_free(backing_file);
855 backing_file = NULL;
857 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
858 unmodified sectors */
859 header.l2_bits = 12; /* 32 KB L2 tables */
860 } else {
861 header.cluster_bits = 12; /* 4 KB clusters */
862 header.l2_bits = 9; /* 4 KB L2 tables */
864 header_size = (header_size + 7) & ~7;
865 shift = header.cluster_bits + header.l2_bits;
866 l1_size = (total_size + (1LL << shift) - 1) >> shift;
868 header.l1_table_offset = cpu_to_be64(header_size);
869 if (encryptfmt) {
870 if (!g_str_equal(encryptfmt, "aes")) {
871 error_setg(errp, "Unknown encryption format '%s', expected 'aes'",
872 encryptfmt);
873 ret = -EINVAL;
874 goto exit;
876 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
877 } else {
878 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
881 /* write all the data */
882 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
883 if (ret != sizeof(header)) {
884 goto exit;
887 if (backing_file) {
888 ret = blk_pwrite(qcow_blk, sizeof(header),
889 backing_file, backing_filename_len, 0);
890 if (ret != backing_filename_len) {
891 goto exit;
895 tmp = g_malloc0(BDRV_SECTOR_SIZE);
896 for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
897 i++) {
898 ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
899 tmp, BDRV_SECTOR_SIZE, 0);
900 if (ret != BDRV_SECTOR_SIZE) {
901 g_free(tmp);
902 goto exit;
906 g_free(tmp);
907 ret = 0;
908 exit:
909 blk_unref(qcow_blk);
910 cleanup:
911 g_free(backing_file);
912 return ret;
915 static int qcow_make_empty(BlockDriverState *bs)
917 BDRVQcowState *s = bs->opaque;
918 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
919 int ret;
921 memset(s->l1_table, 0, l1_length);
922 if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
923 l1_length) < 0)
924 return -1;
925 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length, NULL);
926 if (ret < 0)
927 return ret;
929 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
930 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
931 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
933 return 0;
936 /* XXX: put compressed sectors first, then all the cluster aligned
937 tables to avoid losing bytes in alignment */
938 static coroutine_fn int
939 qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
940 uint64_t bytes, QEMUIOVector *qiov)
942 BDRVQcowState *s = bs->opaque;
943 QEMUIOVector hd_qiov;
944 struct iovec iov;
945 z_stream strm;
946 int ret, out_len;
947 uint8_t *buf, *out_buf;
948 uint64_t cluster_offset;
950 buf = qemu_blockalign(bs, s->cluster_size);
951 if (bytes != s->cluster_size) {
952 if (bytes > s->cluster_size ||
953 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
955 qemu_vfree(buf);
956 return -EINVAL;
958 /* Zero-pad last write if image size is not cluster aligned */
959 memset(buf + bytes, 0, s->cluster_size - bytes);
961 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
963 out_buf = g_malloc(s->cluster_size);
965 /* best compression, small window, no zlib header */
966 memset(&strm, 0, sizeof(strm));
967 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
968 Z_DEFLATED, -12,
969 9, Z_DEFAULT_STRATEGY);
970 if (ret != 0) {
971 ret = -EINVAL;
972 goto fail;
975 strm.avail_in = s->cluster_size;
976 strm.next_in = (uint8_t *)buf;
977 strm.avail_out = s->cluster_size;
978 strm.next_out = out_buf;
980 ret = deflate(&strm, Z_FINISH);
981 if (ret != Z_STREAM_END && ret != Z_OK) {
982 deflateEnd(&strm);
983 ret = -EINVAL;
984 goto fail;
986 out_len = strm.next_out - out_buf;
988 deflateEnd(&strm);
990 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
991 /* could not compress: write normal cluster */
992 ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,
993 bytes >> BDRV_SECTOR_BITS, qiov);
994 if (ret < 0) {
995 goto fail;
997 goto success;
999 qemu_co_mutex_lock(&s->lock);
1000 cluster_offset = get_cluster_offset(bs, offset, 2, out_len, 0, 0);
1001 qemu_co_mutex_unlock(&s->lock);
1002 if (cluster_offset == 0) {
1003 ret = -EIO;
1004 goto fail;
1006 cluster_offset &= s->cluster_offset_mask;
1008 iov = (struct iovec) {
1009 .iov_base = out_buf,
1010 .iov_len = out_len,
1012 qemu_iovec_init_external(&hd_qiov, &iov, 1);
1013 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
1014 if (ret < 0) {
1015 goto fail;
1017 success:
1018 ret = 0;
1019 fail:
1020 qemu_vfree(buf);
1021 g_free(out_buf);
1022 return ret;
1025 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1027 BDRVQcowState *s = bs->opaque;
1028 bdi->cluster_size = s->cluster_size;
1029 return 0;
1032 static QemuOptsList qcow_create_opts = {
1033 .name = "qcow-create-opts",
1034 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1035 .desc = {
1037 .name = BLOCK_OPT_SIZE,
1038 .type = QEMU_OPT_SIZE,
1039 .help = "Virtual disk size"
1042 .name = BLOCK_OPT_BACKING_FILE,
1043 .type = QEMU_OPT_STRING,
1044 .help = "File name of a base image"
1047 .name = BLOCK_OPT_ENCRYPT,
1048 .type = QEMU_OPT_BOOL,
1049 .help = "Encrypt the image with format 'aes'. (Deprecated "
1050 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
1053 .name = BLOCK_OPT_ENCRYPT_FORMAT,
1054 .type = QEMU_OPT_STRING,
1055 .help = "Encrypt the image, format choices: 'aes'",
1057 { /* end of list */ }
1061 static BlockDriver bdrv_qcow = {
1062 .format_name = "qcow",
1063 .instance_size = sizeof(BDRVQcowState),
1064 .bdrv_probe = qcow_probe,
1065 .bdrv_open = qcow_open,
1066 .bdrv_close = qcow_close,
1067 .bdrv_child_perm = bdrv_format_default_perms,
1068 .bdrv_reopen_prepare = qcow_reopen_prepare,
1069 .bdrv_create = qcow_create,
1070 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1071 .supports_backing = true,
1073 .bdrv_co_readv = qcow_co_readv,
1074 .bdrv_co_writev = qcow_co_writev,
1075 .bdrv_co_get_block_status = qcow_co_get_block_status,
1077 .bdrv_set_key = qcow_set_key,
1078 .bdrv_make_empty = qcow_make_empty,
1079 .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed,
1080 .bdrv_get_info = qcow_get_info,
1082 .create_opts = &qcow_create_opts,
1085 static void bdrv_qcow_init(void)
1087 bdrv_register(&bdrv_qcow);
1090 block_init(bdrv_qcow_init);