exec: remove ram_addr argument from qemu_ram_block_from_host
[qemu.git] / block / qcow.c
blobcb4bf0299f7589bf3843816336b28e3ef9a16a19
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/migration.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;
108 ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
109 if (ret < 0) {
110 goto fail;
112 be32_to_cpus(&header.magic);
113 be32_to_cpus(&header.version);
114 be64_to_cpus(&header.backing_file_offset);
115 be32_to_cpus(&header.backing_file_size);
116 be32_to_cpus(&header.mtime);
117 be64_to_cpus(&header.size);
118 be32_to_cpus(&header.crypt_method);
119 be64_to_cpus(&header.l1_table_offset);
121 if (header.magic != QCOW_MAGIC) {
122 error_setg(errp, "Image not in qcow format");
123 ret = -EINVAL;
124 goto fail;
126 if (header.version != QCOW_VERSION) {
127 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
128 ret = -ENOTSUP;
129 goto fail;
132 if (header.size <= 1) {
133 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
134 ret = -EINVAL;
135 goto fail;
137 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
138 error_setg(errp, "Cluster size must be between 512 and 64k");
139 ret = -EINVAL;
140 goto fail;
143 /* l2_bits specifies number of entries; storing a uint64_t in each entry,
144 * so bytes = num_entries << 3. */
145 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
146 error_setg(errp, "L2 table size must be between 512 and 64k");
147 ret = -EINVAL;
148 goto fail;
151 if (header.crypt_method > QCOW_CRYPT_AES) {
152 error_setg(errp, "invalid encryption method in qcow header");
153 ret = -EINVAL;
154 goto fail;
156 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
157 error_setg(errp, "AES cipher not available");
158 ret = -EINVAL;
159 goto fail;
161 s->crypt_method_header = header.crypt_method;
162 if (s->crypt_method_header) {
163 if (bdrv_uses_whitelist() &&
164 s->crypt_method_header == QCOW_CRYPT_AES) {
165 error_report("qcow built-in AES encryption is deprecated");
166 error_printf("Support for it will be removed in a future release.\n"
167 "You can use 'qemu-img convert' to switch to an\n"
168 "unencrypted qcow image, or a LUKS raw image.\n");
171 bs->encrypted = 1;
173 s->cluster_bits = header.cluster_bits;
174 s->cluster_size = 1 << s->cluster_bits;
175 s->cluster_sectors = 1 << (s->cluster_bits - 9);
176 s->l2_bits = header.l2_bits;
177 s->l2_size = 1 << s->l2_bits;
178 bs->total_sectors = header.size / 512;
179 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
181 /* read the level 1 table */
182 shift = s->cluster_bits + s->l2_bits;
183 if (header.size > UINT64_MAX - (1LL << shift)) {
184 error_setg(errp, "Image too large");
185 ret = -EINVAL;
186 goto fail;
187 } else {
188 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
189 if (l1_size > INT_MAX / sizeof(uint64_t)) {
190 error_setg(errp, "Image too large");
191 ret = -EINVAL;
192 goto fail;
194 s->l1_size = l1_size;
197 s->l1_table_offset = header.l1_table_offset;
198 s->l1_table = g_try_new(uint64_t, s->l1_size);
199 if (s->l1_table == NULL) {
200 error_setg(errp, "Could not allocate memory for L1 table");
201 ret = -ENOMEM;
202 goto fail;
205 ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
206 s->l1_size * sizeof(uint64_t));
207 if (ret < 0) {
208 goto fail;
211 for(i = 0;i < s->l1_size; i++) {
212 be64_to_cpus(&s->l1_table[i]);
215 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
216 s->l2_cache =
217 qemu_try_blockalign(bs->file->bs,
218 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
219 if (s->l2_cache == NULL) {
220 error_setg(errp, "Could not allocate L2 table cache");
221 ret = -ENOMEM;
222 goto fail;
224 s->cluster_cache = g_malloc(s->cluster_size);
225 s->cluster_data = g_malloc(s->cluster_size);
226 s->cluster_cache_offset = -1;
228 /* read the backing file name */
229 if (header.backing_file_offset != 0) {
230 len = header.backing_file_size;
231 if (len > 1023 || len >= sizeof(bs->backing_file)) {
232 error_setg(errp, "Backing file name too long");
233 ret = -EINVAL;
234 goto fail;
236 ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
237 bs->backing_file, len);
238 if (ret < 0) {
239 goto fail;
241 bs->backing_file[len] = '\0';
244 /* Disable migration when qcow images are used */
245 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
246 "does not support live migration",
247 bdrv_get_device_or_node_name(bs));
248 migrate_add_blocker(s->migration_blocker);
250 qemu_co_mutex_init(&s->lock);
251 return 0;
253 fail:
254 g_free(s->l1_table);
255 qemu_vfree(s->l2_cache);
256 g_free(s->cluster_cache);
257 g_free(s->cluster_data);
258 return ret;
262 /* We have nothing to do for QCOW reopen, stubs just return
263 * success */
264 static int qcow_reopen_prepare(BDRVReopenState *state,
265 BlockReopenQueue *queue, Error **errp)
267 return 0;
270 static int qcow_set_key(BlockDriverState *bs, const char *key)
272 BDRVQcowState *s = bs->opaque;
273 uint8_t keybuf[16];
274 int len, i;
275 Error *err;
277 memset(keybuf, 0, 16);
278 len = strlen(key);
279 if (len > 16)
280 len = 16;
281 /* XXX: we could compress the chars to 7 bits to increase
282 entropy */
283 for(i = 0;i < len;i++) {
284 keybuf[i] = key[i];
286 assert(bs->encrypted);
288 qcrypto_cipher_free(s->cipher);
289 s->cipher = qcrypto_cipher_new(
290 QCRYPTO_CIPHER_ALG_AES_128,
291 QCRYPTO_CIPHER_MODE_CBC,
292 keybuf, G_N_ELEMENTS(keybuf),
293 &err);
295 if (!s->cipher) {
296 /* XXX would be nice if errors in this method could
297 * be properly propagate to the caller. Would need
298 * the bdrv_set_key() API signature to be fixed. */
299 error_free(err);
300 return -1;
302 return 0;
305 /* The crypt function is compatible with the linux cryptoloop
306 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
307 supported */
308 static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
309 uint8_t *out_buf, const uint8_t *in_buf,
310 int nb_sectors, bool enc, Error **errp)
312 union {
313 uint64_t ll[2];
314 uint8_t b[16];
315 } ivec;
316 int i;
317 int ret;
319 for(i = 0; i < nb_sectors; i++) {
320 ivec.ll[0] = cpu_to_le64(sector_num);
321 ivec.ll[1] = 0;
322 if (qcrypto_cipher_setiv(s->cipher,
323 ivec.b, G_N_ELEMENTS(ivec.b),
324 errp) < 0) {
325 return -1;
327 if (enc) {
328 ret = qcrypto_cipher_encrypt(s->cipher,
329 in_buf,
330 out_buf,
331 512,
332 errp);
333 } else {
334 ret = qcrypto_cipher_decrypt(s->cipher,
335 in_buf,
336 out_buf,
337 512,
338 errp);
340 if (ret < 0) {
341 return -1;
343 sector_num++;
344 in_buf += 512;
345 out_buf += 512;
347 return 0;
350 /* 'allocate' is:
352 * 0 to not allocate.
354 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
355 * 'n_end')
357 * 2 to allocate a compressed cluster of size
358 * 'compressed_size'. 'compressed_size' must be > 0 and <
359 * cluster_size
361 * return 0 if not allocated.
363 static uint64_t get_cluster_offset(BlockDriverState *bs,
364 uint64_t offset, int allocate,
365 int compressed_size,
366 int n_start, int n_end)
368 BDRVQcowState *s = bs->opaque;
369 int min_index, i, j, l1_index, l2_index;
370 uint64_t l2_offset, *l2_table, cluster_offset, tmp;
371 uint32_t min_count;
372 int new_l2_table;
374 l1_index = offset >> (s->l2_bits + s->cluster_bits);
375 l2_offset = s->l1_table[l1_index];
376 new_l2_table = 0;
377 if (!l2_offset) {
378 if (!allocate)
379 return 0;
380 /* allocate a new l2 entry */
381 l2_offset = bdrv_getlength(bs->file->bs);
382 /* round to cluster size */
383 l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
384 /* update the L1 entry */
385 s->l1_table[l1_index] = l2_offset;
386 tmp = cpu_to_be64(l2_offset);
387 if (bdrv_pwrite_sync(bs->file->bs,
388 s->l1_table_offset + l1_index * sizeof(tmp),
389 &tmp, sizeof(tmp)) < 0)
390 return 0;
391 new_l2_table = 1;
393 for(i = 0; i < L2_CACHE_SIZE; i++) {
394 if (l2_offset == s->l2_cache_offsets[i]) {
395 /* increment the hit count */
396 if (++s->l2_cache_counts[i] == 0xffffffff) {
397 for(j = 0; j < L2_CACHE_SIZE; j++) {
398 s->l2_cache_counts[j] >>= 1;
401 l2_table = s->l2_cache + (i << s->l2_bits);
402 goto found;
405 /* not found: load a new entry in the least used one */
406 min_index = 0;
407 min_count = 0xffffffff;
408 for(i = 0; i < L2_CACHE_SIZE; i++) {
409 if (s->l2_cache_counts[i] < min_count) {
410 min_count = s->l2_cache_counts[i];
411 min_index = i;
414 l2_table = s->l2_cache + (min_index << s->l2_bits);
415 if (new_l2_table) {
416 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
417 if (bdrv_pwrite_sync(bs->file->bs, l2_offset, l2_table,
418 s->l2_size * sizeof(uint64_t)) < 0)
419 return 0;
420 } else {
421 if (bdrv_pread(bs->file->bs, l2_offset, l2_table,
422 s->l2_size * sizeof(uint64_t)) !=
423 s->l2_size * sizeof(uint64_t))
424 return 0;
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 0;
443 cluster_offset = bdrv_getlength(bs->file->bs);
444 cluster_offset = (cluster_offset + s->cluster_size - 1) &
445 ~(s->cluster_size - 1);
446 /* write the cluster content */
447 if (bdrv_pwrite(bs->file->bs, cluster_offset, s->cluster_cache,
448 s->cluster_size) !=
449 s->cluster_size)
450 return -1;
451 } else {
452 cluster_offset = bdrv_getlength(bs->file->bs);
453 if (allocate == 1) {
454 /* round to cluster size */
455 cluster_offset = (cluster_offset + s->cluster_size - 1) &
456 ~(s->cluster_size - 1);
457 bdrv_truncate(bs->file->bs, cluster_offset + s->cluster_size);
458 /* if encrypted, we must initialize the cluster
459 content which won't be written */
460 if (bs->encrypted &&
461 (n_end - n_start) < s->cluster_sectors) {
462 uint64_t start_sect;
463 assert(s->cipher);
464 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
465 memset(s->cluster_data + 512, 0x00, 512);
466 for(i = 0; i < s->cluster_sectors; i++) {
467 if (i < n_start || i >= n_end) {
468 Error *err = NULL;
469 if (encrypt_sectors(s, start_sect + i,
470 s->cluster_data,
471 s->cluster_data + 512, 1,
472 true, &err) < 0) {
473 error_free(err);
474 errno = EIO;
475 return -1;
477 if (bdrv_pwrite(bs->file->bs,
478 cluster_offset + i * 512,
479 s->cluster_data, 512) != 512)
480 return -1;
484 } else if (allocate == 2) {
485 cluster_offset |= QCOW_OFLAG_COMPRESSED |
486 (uint64_t)compressed_size << (63 - s->cluster_bits);
489 /* update L2 table */
490 tmp = cpu_to_be64(cluster_offset);
491 l2_table[l2_index] = tmp;
492 if (bdrv_pwrite_sync(bs->file->bs, l2_offset + l2_index * sizeof(tmp),
493 &tmp, sizeof(tmp)) < 0)
494 return 0;
496 return cluster_offset;
499 static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
500 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
502 BDRVQcowState *s = bs->opaque;
503 int index_in_cluster, n;
504 uint64_t cluster_offset;
506 qemu_co_mutex_lock(&s->lock);
507 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
508 qemu_co_mutex_unlock(&s->lock);
509 index_in_cluster = sector_num & (s->cluster_sectors - 1);
510 n = s->cluster_sectors - index_in_cluster;
511 if (n > nb_sectors)
512 n = nb_sectors;
513 *pnum = n;
514 if (!cluster_offset) {
515 return 0;
517 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
518 return BDRV_BLOCK_DATA;
520 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
521 *file = bs->file->bs;
522 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
525 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
526 const uint8_t *buf, int buf_size)
528 z_stream strm1, *strm = &strm1;
529 int ret, out_len;
531 memset(strm, 0, sizeof(*strm));
533 strm->next_in = (uint8_t *)buf;
534 strm->avail_in = buf_size;
535 strm->next_out = out_buf;
536 strm->avail_out = out_buf_size;
538 ret = inflateInit2(strm, -12);
539 if (ret != Z_OK)
540 return -1;
541 ret = inflate(strm, Z_FINISH);
542 out_len = strm->next_out - out_buf;
543 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
544 out_len != out_buf_size) {
545 inflateEnd(strm);
546 return -1;
548 inflateEnd(strm);
549 return 0;
552 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
554 BDRVQcowState *s = bs->opaque;
555 int ret, csize;
556 uint64_t coffset;
558 coffset = cluster_offset & s->cluster_offset_mask;
559 if (s->cluster_cache_offset != coffset) {
560 csize = cluster_offset >> (63 - s->cluster_bits);
561 csize &= (s->cluster_size - 1);
562 ret = bdrv_pread(bs->file->bs, coffset, s->cluster_data, csize);
563 if (ret != csize)
564 return -1;
565 if (decompress_buffer(s->cluster_cache, s->cluster_size,
566 s->cluster_data, csize) < 0) {
567 return -1;
569 s->cluster_cache_offset = coffset;
571 return 0;
574 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
575 int nb_sectors, QEMUIOVector *qiov)
577 BDRVQcowState *s = bs->opaque;
578 int index_in_cluster;
579 int ret = 0, n;
580 uint64_t cluster_offset;
581 struct iovec hd_iov;
582 QEMUIOVector hd_qiov;
583 uint8_t *buf;
584 void *orig_buf;
585 Error *err = NULL;
587 if (qiov->niov > 1) {
588 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
589 if (buf == NULL) {
590 return -ENOMEM;
592 } else {
593 orig_buf = NULL;
594 buf = (uint8_t *)qiov->iov->iov_base;
597 qemu_co_mutex_lock(&s->lock);
599 while (nb_sectors != 0) {
600 /* prepare next request */
601 cluster_offset = get_cluster_offset(bs, sector_num << 9,
602 0, 0, 0, 0);
603 index_in_cluster = sector_num & (s->cluster_sectors - 1);
604 n = s->cluster_sectors - index_in_cluster;
605 if (n > nb_sectors) {
606 n = nb_sectors;
609 if (!cluster_offset) {
610 if (bs->backing) {
611 /* read from the base image */
612 hd_iov.iov_base = (void *)buf;
613 hd_iov.iov_len = n * 512;
614 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
615 qemu_co_mutex_unlock(&s->lock);
616 ret = bdrv_co_readv(bs->backing->bs, sector_num,
617 n, &hd_qiov);
618 qemu_co_mutex_lock(&s->lock);
619 if (ret < 0) {
620 goto fail;
622 } else {
623 /* Note: in this case, no need to wait */
624 memset(buf, 0, 512 * n);
626 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
627 /* add AIO support for compressed blocks ? */
628 if (decompress_cluster(bs, cluster_offset) < 0) {
629 goto fail;
631 memcpy(buf,
632 s->cluster_cache + index_in_cluster * 512, 512 * n);
633 } else {
634 if ((cluster_offset & 511) != 0) {
635 goto fail;
637 hd_iov.iov_base = (void *)buf;
638 hd_iov.iov_len = n * 512;
639 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
640 qemu_co_mutex_unlock(&s->lock);
641 ret = bdrv_co_readv(bs->file->bs,
642 (cluster_offset >> 9) + index_in_cluster,
643 n, &hd_qiov);
644 qemu_co_mutex_lock(&s->lock);
645 if (ret < 0) {
646 break;
648 if (bs->encrypted) {
649 assert(s->cipher);
650 if (encrypt_sectors(s, sector_num, buf, buf,
651 n, false, &err) < 0) {
652 goto fail;
656 ret = 0;
658 nb_sectors -= n;
659 sector_num += n;
660 buf += n * 512;
663 done:
664 qemu_co_mutex_unlock(&s->lock);
666 if (qiov->niov > 1) {
667 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
668 qemu_vfree(orig_buf);
671 return ret;
673 fail:
674 error_free(err);
675 ret = -EIO;
676 goto done;
679 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
680 int nb_sectors, QEMUIOVector *qiov)
682 BDRVQcowState *s = bs->opaque;
683 int index_in_cluster;
684 uint64_t cluster_offset;
685 const uint8_t *src_buf;
686 int ret = 0, n;
687 uint8_t *cluster_data = NULL;
688 struct iovec hd_iov;
689 QEMUIOVector hd_qiov;
690 uint8_t *buf;
691 void *orig_buf;
693 s->cluster_cache_offset = -1; /* disable compressed cache */
695 if (qiov->niov > 1) {
696 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
697 if (buf == NULL) {
698 return -ENOMEM;
700 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
701 } else {
702 orig_buf = NULL;
703 buf = (uint8_t *)qiov->iov->iov_base;
706 qemu_co_mutex_lock(&s->lock);
708 while (nb_sectors != 0) {
710 index_in_cluster = sector_num & (s->cluster_sectors - 1);
711 n = s->cluster_sectors - index_in_cluster;
712 if (n > nb_sectors) {
713 n = nb_sectors;
715 cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
716 index_in_cluster,
717 index_in_cluster + n);
718 if (!cluster_offset || (cluster_offset & 511) != 0) {
719 ret = -EIO;
720 break;
722 if (bs->encrypted) {
723 Error *err = NULL;
724 assert(s->cipher);
725 if (!cluster_data) {
726 cluster_data = g_malloc0(s->cluster_size);
728 if (encrypt_sectors(s, sector_num, cluster_data, buf,
729 n, true, &err) < 0) {
730 error_free(err);
731 ret = -EIO;
732 break;
734 src_buf = cluster_data;
735 } else {
736 src_buf = buf;
739 hd_iov.iov_base = (void *)src_buf;
740 hd_iov.iov_len = n * 512;
741 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
742 qemu_co_mutex_unlock(&s->lock);
743 ret = bdrv_co_writev(bs->file->bs,
744 (cluster_offset >> 9) + index_in_cluster,
745 n, &hd_qiov);
746 qemu_co_mutex_lock(&s->lock);
747 if (ret < 0) {
748 break;
750 ret = 0;
752 nb_sectors -= n;
753 sector_num += n;
754 buf += n * 512;
756 qemu_co_mutex_unlock(&s->lock);
758 if (qiov->niov > 1) {
759 qemu_vfree(orig_buf);
761 g_free(cluster_data);
763 return ret;
766 static void qcow_close(BlockDriverState *bs)
768 BDRVQcowState *s = bs->opaque;
770 qcrypto_cipher_free(s->cipher);
771 s->cipher = NULL;
772 g_free(s->l1_table);
773 qemu_vfree(s->l2_cache);
774 g_free(s->cluster_cache);
775 g_free(s->cluster_data);
777 migrate_del_blocker(s->migration_blocker);
778 error_free(s->migration_blocker);
781 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
783 int header_size, backing_filename_len, l1_size, shift, i;
784 QCowHeader header;
785 uint8_t *tmp;
786 int64_t total_size = 0;
787 char *backing_file = NULL;
788 int flags = 0;
789 Error *local_err = NULL;
790 int ret;
791 BlockBackend *qcow_blk;
793 /* Read out options */
794 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
795 BDRV_SECTOR_SIZE);
796 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
797 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
798 flags |= BLOCK_FLAG_ENCRYPT;
801 ret = bdrv_create_file(filename, opts, &local_err);
802 if (ret < 0) {
803 error_propagate(errp, local_err);
804 goto cleanup;
807 qcow_blk = blk_new_open(filename, NULL, NULL,
808 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
809 if (qcow_blk == NULL) {
810 error_propagate(errp, local_err);
811 ret = -EIO;
812 goto cleanup;
815 blk_set_allow_write_beyond_eof(qcow_blk, true);
817 ret = blk_truncate(qcow_blk, 0);
818 if (ret < 0) {
819 goto exit;
822 memset(&header, 0, sizeof(header));
823 header.magic = cpu_to_be32(QCOW_MAGIC);
824 header.version = cpu_to_be32(QCOW_VERSION);
825 header.size = cpu_to_be64(total_size);
826 header_size = sizeof(header);
827 backing_filename_len = 0;
828 if (backing_file) {
829 if (strcmp(backing_file, "fat:")) {
830 header.backing_file_offset = cpu_to_be64(header_size);
831 backing_filename_len = strlen(backing_file);
832 header.backing_file_size = cpu_to_be32(backing_filename_len);
833 header_size += backing_filename_len;
834 } else {
835 /* special backing file for vvfat */
836 backing_file = NULL;
838 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
839 unmodified sectors */
840 header.l2_bits = 12; /* 32 KB L2 tables */
841 } else {
842 header.cluster_bits = 12; /* 4 KB clusters */
843 header.l2_bits = 9; /* 4 KB L2 tables */
845 header_size = (header_size + 7) & ~7;
846 shift = header.cluster_bits + header.l2_bits;
847 l1_size = (total_size + (1LL << shift) - 1) >> shift;
849 header.l1_table_offset = cpu_to_be64(header_size);
850 if (flags & BLOCK_FLAG_ENCRYPT) {
851 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
852 } else {
853 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
856 /* write all the data */
857 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
858 if (ret != sizeof(header)) {
859 goto exit;
862 if (backing_file) {
863 ret = blk_pwrite(qcow_blk, sizeof(header),
864 backing_file, backing_filename_len, 0);
865 if (ret != backing_filename_len) {
866 goto exit;
870 tmp = g_malloc0(BDRV_SECTOR_SIZE);
871 for (i = 0; i < ((sizeof(uint64_t)*l1_size + BDRV_SECTOR_SIZE - 1)/
872 BDRV_SECTOR_SIZE); i++) {
873 ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
874 tmp, BDRV_SECTOR_SIZE, 0);
875 if (ret != BDRV_SECTOR_SIZE) {
876 g_free(tmp);
877 goto exit;
881 g_free(tmp);
882 ret = 0;
883 exit:
884 blk_unref(qcow_blk);
885 cleanup:
886 g_free(backing_file);
887 return ret;
890 static int qcow_make_empty(BlockDriverState *bs)
892 BDRVQcowState *s = bs->opaque;
893 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
894 int ret;
896 memset(s->l1_table, 0, l1_length);
897 if (bdrv_pwrite_sync(bs->file->bs, s->l1_table_offset, s->l1_table,
898 l1_length) < 0)
899 return -1;
900 ret = bdrv_truncate(bs->file->bs, s->l1_table_offset + l1_length);
901 if (ret < 0)
902 return ret;
904 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
905 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
906 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
908 return 0;
911 /* XXX: put compressed sectors first, then all the cluster aligned
912 tables to avoid losing bytes in alignment */
913 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
914 const uint8_t *buf, int nb_sectors)
916 BDRVQcowState *s = bs->opaque;
917 z_stream strm;
918 int ret, out_len;
919 uint8_t *out_buf;
920 uint64_t cluster_offset;
922 if (nb_sectors != s->cluster_sectors) {
923 ret = -EINVAL;
925 /* Zero-pad last write if image size is not cluster aligned */
926 if (sector_num + nb_sectors == bs->total_sectors &&
927 nb_sectors < s->cluster_sectors) {
928 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
929 memset(pad_buf, 0, s->cluster_size);
930 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
931 ret = qcow_write_compressed(bs, sector_num,
932 pad_buf, s->cluster_sectors);
933 qemu_vfree(pad_buf);
935 return ret;
938 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
940 /* best compression, small window, no zlib header */
941 memset(&strm, 0, sizeof(strm));
942 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
943 Z_DEFLATED, -12,
944 9, Z_DEFAULT_STRATEGY);
945 if (ret != 0) {
946 ret = -EINVAL;
947 goto fail;
950 strm.avail_in = s->cluster_size;
951 strm.next_in = (uint8_t *)buf;
952 strm.avail_out = s->cluster_size;
953 strm.next_out = out_buf;
955 ret = deflate(&strm, Z_FINISH);
956 if (ret != Z_STREAM_END && ret != Z_OK) {
957 deflateEnd(&strm);
958 ret = -EINVAL;
959 goto fail;
961 out_len = strm.next_out - out_buf;
963 deflateEnd(&strm);
965 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
966 /* could not compress: write normal cluster */
967 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
968 if (ret < 0) {
969 goto fail;
971 } else {
972 cluster_offset = get_cluster_offset(bs, sector_num << 9, 2,
973 out_len, 0, 0);
974 if (cluster_offset == 0) {
975 ret = -EIO;
976 goto fail;
979 cluster_offset &= s->cluster_offset_mask;
980 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
981 if (ret < 0) {
982 goto fail;
986 ret = 0;
987 fail:
988 g_free(out_buf);
989 return ret;
992 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
994 BDRVQcowState *s = bs->opaque;
995 bdi->cluster_size = s->cluster_size;
996 return 0;
999 static QemuOptsList qcow_create_opts = {
1000 .name = "qcow-create-opts",
1001 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1002 .desc = {
1004 .name = BLOCK_OPT_SIZE,
1005 .type = QEMU_OPT_SIZE,
1006 .help = "Virtual disk size"
1009 .name = BLOCK_OPT_BACKING_FILE,
1010 .type = QEMU_OPT_STRING,
1011 .help = "File name of a base image"
1014 .name = BLOCK_OPT_ENCRYPT,
1015 .type = QEMU_OPT_BOOL,
1016 .help = "Encrypt the image",
1017 .def_value_str = "off"
1019 { /* end of list */ }
1023 static BlockDriver bdrv_qcow = {
1024 .format_name = "qcow",
1025 .instance_size = sizeof(BDRVQcowState),
1026 .bdrv_probe = qcow_probe,
1027 .bdrv_open = qcow_open,
1028 .bdrv_close = qcow_close,
1029 .bdrv_reopen_prepare = qcow_reopen_prepare,
1030 .bdrv_create = qcow_create,
1031 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1032 .supports_backing = true,
1034 .bdrv_co_readv = qcow_co_readv,
1035 .bdrv_co_writev = qcow_co_writev,
1036 .bdrv_co_get_block_status = qcow_co_get_block_status,
1038 .bdrv_set_key = qcow_set_key,
1039 .bdrv_make_empty = qcow_make_empty,
1040 .bdrv_write_compressed = qcow_write_compressed,
1041 .bdrv_get_info = qcow_get_info,
1043 .create_opts = &qcow_create_opts,
1046 static void bdrv_qcow_init(void)
1048 bdrv_register(&bdrv_qcow);
1051 block_init(bdrv_qcow_init);