target-ppc: Eliminate kvmppc_kern_htab global
[qemu/kevin.git] / block / qcow.c
blob2fd5ee65d4cadba53fb8fdfa44e513253374286f
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 "qemu-common.h"
26 #include "block/block_int.h"
27 #include "sysemu/block-backend.h"
28 #include "qemu/module.h"
29 #include <zlib.h>
30 #include "qapi/qmp/qerror.h"
31 #include "crypto/cipher.h"
32 #include "migration/migration.h"
34 /**************************************************************/
35 /* QEMU COW block driver with compression and encryption support */
37 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
38 #define QCOW_VERSION 1
40 #define QCOW_CRYPT_NONE 0
41 #define QCOW_CRYPT_AES 1
43 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
45 typedef struct QCowHeader {
46 uint32_t magic;
47 uint32_t version;
48 uint64_t backing_file_offset;
49 uint32_t backing_file_size;
50 uint32_t mtime;
51 uint64_t size; /* in bytes */
52 uint8_t cluster_bits;
53 uint8_t l2_bits;
54 uint16_t padding;
55 uint32_t crypt_method;
56 uint64_t l1_table_offset;
57 } QEMU_PACKED QCowHeader;
59 #define L2_CACHE_SIZE 16
61 typedef struct BDRVQcowState {
62 int cluster_bits;
63 int cluster_size;
64 int cluster_sectors;
65 int l2_bits;
66 int l2_size;
67 unsigned int l1_size;
68 uint64_t cluster_offset_mask;
69 uint64_t l1_table_offset;
70 uint64_t *l1_table;
71 uint64_t *l2_cache;
72 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
73 uint32_t l2_cache_counts[L2_CACHE_SIZE];
74 uint8_t *cluster_cache;
75 uint8_t *cluster_data;
76 uint64_t cluster_cache_offset;
77 QCryptoCipher *cipher; /* NULL if no key yet */
78 uint32_t crypt_method_header;
79 CoMutex lock;
80 Error *migration_blocker;
81 } BDRVQcowState;
83 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
85 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
87 const QCowHeader *cow_header = (const void *)buf;
89 if (buf_size >= sizeof(QCowHeader) &&
90 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
91 be32_to_cpu(cow_header->version) == QCOW_VERSION)
92 return 100;
93 else
94 return 0;
97 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
98 Error **errp)
100 BDRVQcowState *s = bs->opaque;
101 unsigned int len, i, shift;
102 int ret;
103 QCowHeader header;
105 ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
106 if (ret < 0) {
107 goto fail;
109 be32_to_cpus(&header.magic);
110 be32_to_cpus(&header.version);
111 be64_to_cpus(&header.backing_file_offset);
112 be32_to_cpus(&header.backing_file_size);
113 be32_to_cpus(&header.mtime);
114 be64_to_cpus(&header.size);
115 be32_to_cpus(&header.crypt_method);
116 be64_to_cpus(&header.l1_table_offset);
118 if (header.magic != QCOW_MAGIC) {
119 error_setg(errp, "Image not in qcow format");
120 ret = -EINVAL;
121 goto fail;
123 if (header.version != QCOW_VERSION) {
124 char version[64];
125 snprintf(version, sizeof(version), "QCOW version %" PRIu32,
126 header.version);
127 error_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
128 bdrv_get_device_or_node_name(bs), "qcow", version);
129 ret = -ENOTSUP;
130 goto fail;
133 if (header.size <= 1) {
134 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
135 ret = -EINVAL;
136 goto fail;
138 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
139 error_setg(errp, "Cluster size must be between 512 and 64k");
140 ret = -EINVAL;
141 goto fail;
144 /* l2_bits specifies number of entries; storing a uint64_t in each entry,
145 * so bytes = num_entries << 3. */
146 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
147 error_setg(errp, "L2 table size must be between 512 and 64k");
148 ret = -EINVAL;
149 goto fail;
152 if (header.crypt_method > QCOW_CRYPT_AES) {
153 error_setg(errp, "invalid encryption method in qcow header");
154 ret = -EINVAL;
155 goto fail;
157 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
158 error_setg(errp, "AES cipher not available");
159 ret = -EINVAL;
160 goto fail;
162 s->crypt_method_header = header.crypt_method;
163 if (s->crypt_method_header) {
164 bs->encrypted = 1;
166 s->cluster_bits = header.cluster_bits;
167 s->cluster_size = 1 << s->cluster_bits;
168 s->cluster_sectors = 1 << (s->cluster_bits - 9);
169 s->l2_bits = header.l2_bits;
170 s->l2_size = 1 << s->l2_bits;
171 bs->total_sectors = header.size / 512;
172 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
174 /* read the level 1 table */
175 shift = s->cluster_bits + s->l2_bits;
176 if (header.size > UINT64_MAX - (1LL << shift)) {
177 error_setg(errp, "Image too large");
178 ret = -EINVAL;
179 goto fail;
180 } else {
181 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
182 if (l1_size > INT_MAX / sizeof(uint64_t)) {
183 error_setg(errp, "Image too large");
184 ret = -EINVAL;
185 goto fail;
187 s->l1_size = l1_size;
190 s->l1_table_offset = header.l1_table_offset;
191 s->l1_table = g_try_new(uint64_t, s->l1_size);
192 if (s->l1_table == NULL) {
193 error_setg(errp, "Could not allocate memory for L1 table");
194 ret = -ENOMEM;
195 goto fail;
198 ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
199 s->l1_size * sizeof(uint64_t));
200 if (ret < 0) {
201 goto fail;
204 for(i = 0;i < s->l1_size; i++) {
205 be64_to_cpus(&s->l1_table[i]);
208 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
209 s->l2_cache =
210 qemu_try_blockalign(bs->file->bs,
211 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
212 if (s->l2_cache == NULL) {
213 error_setg(errp, "Could not allocate L2 table cache");
214 ret = -ENOMEM;
215 goto fail;
217 s->cluster_cache = g_malloc(s->cluster_size);
218 s->cluster_data = g_malloc(s->cluster_size);
219 s->cluster_cache_offset = -1;
221 /* read the backing file name */
222 if (header.backing_file_offset != 0) {
223 len = header.backing_file_size;
224 if (len > 1023 || len >= sizeof(bs->backing_file)) {
225 error_setg(errp, "Backing file name too long");
226 ret = -EINVAL;
227 goto fail;
229 ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
230 bs->backing_file, len);
231 if (ret < 0) {
232 goto fail;
234 bs->backing_file[len] = '\0';
237 /* Disable migration when qcow images are used */
238 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
239 "does not support live migration",
240 bdrv_get_device_or_node_name(bs));
241 migrate_add_blocker(s->migration_blocker);
243 qemu_co_mutex_init(&s->lock);
244 return 0;
246 fail:
247 g_free(s->l1_table);
248 qemu_vfree(s->l2_cache);
249 g_free(s->cluster_cache);
250 g_free(s->cluster_data);
251 return ret;
255 /* We have nothing to do for QCOW reopen, stubs just return
256 * success */
257 static int qcow_reopen_prepare(BDRVReopenState *state,
258 BlockReopenQueue *queue, Error **errp)
260 return 0;
263 static int qcow_set_key(BlockDriverState *bs, const char *key)
265 BDRVQcowState *s = bs->opaque;
266 uint8_t keybuf[16];
267 int len, i;
268 Error *err;
270 memset(keybuf, 0, 16);
271 len = strlen(key);
272 if (len > 16)
273 len = 16;
274 /* XXX: we could compress the chars to 7 bits to increase
275 entropy */
276 for(i = 0;i < len;i++) {
277 keybuf[i] = key[i];
279 assert(bs->encrypted);
281 qcrypto_cipher_free(s->cipher);
282 s->cipher = qcrypto_cipher_new(
283 QCRYPTO_CIPHER_ALG_AES_128,
284 QCRYPTO_CIPHER_MODE_CBC,
285 keybuf, G_N_ELEMENTS(keybuf),
286 &err);
288 if (!s->cipher) {
289 /* XXX would be nice if errors in this method could
290 * be properly propagate to the caller. Would need
291 * the bdrv_set_key() API signature to be fixed. */
292 error_free(err);
293 return -1;
295 return 0;
298 /* The crypt function is compatible with the linux cryptoloop
299 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
300 supported */
301 static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
302 uint8_t *out_buf, const uint8_t *in_buf,
303 int nb_sectors, bool enc, Error **errp)
305 union {
306 uint64_t ll[2];
307 uint8_t b[16];
308 } ivec;
309 int i;
310 int ret;
312 for(i = 0; i < nb_sectors; i++) {
313 ivec.ll[0] = cpu_to_le64(sector_num);
314 ivec.ll[1] = 0;
315 if (qcrypto_cipher_setiv(s->cipher,
316 ivec.b, G_N_ELEMENTS(ivec.b),
317 errp) < 0) {
318 return -1;
320 if (enc) {
321 ret = qcrypto_cipher_encrypt(s->cipher,
322 in_buf,
323 out_buf,
324 512,
325 errp);
326 } else {
327 ret = qcrypto_cipher_decrypt(s->cipher,
328 in_buf,
329 out_buf,
330 512,
331 errp);
333 if (ret < 0) {
334 return -1;
336 sector_num++;
337 in_buf += 512;
338 out_buf += 512;
340 return 0;
343 /* 'allocate' is:
345 * 0 to not allocate.
347 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
348 * 'n_end')
350 * 2 to allocate a compressed cluster of size
351 * 'compressed_size'. 'compressed_size' must be > 0 and <
352 * cluster_size
354 * return 0 if not allocated.
356 static uint64_t get_cluster_offset(BlockDriverState *bs,
357 uint64_t offset, int allocate,
358 int compressed_size,
359 int n_start, int n_end)
361 BDRVQcowState *s = bs->opaque;
362 int min_index, i, j, l1_index, l2_index;
363 uint64_t l2_offset, *l2_table, cluster_offset, tmp;
364 uint32_t min_count;
365 int new_l2_table;
367 l1_index = offset >> (s->l2_bits + s->cluster_bits);
368 l2_offset = s->l1_table[l1_index];
369 new_l2_table = 0;
370 if (!l2_offset) {
371 if (!allocate)
372 return 0;
373 /* allocate a new l2 entry */
374 l2_offset = bdrv_getlength(bs->file->bs);
375 /* round to cluster size */
376 l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
377 /* update the L1 entry */
378 s->l1_table[l1_index] = l2_offset;
379 tmp = cpu_to_be64(l2_offset);
380 if (bdrv_pwrite_sync(bs->file->bs,
381 s->l1_table_offset + l1_index * sizeof(tmp),
382 &tmp, sizeof(tmp)) < 0)
383 return 0;
384 new_l2_table = 1;
386 for(i = 0; i < L2_CACHE_SIZE; i++) {
387 if (l2_offset == s->l2_cache_offsets[i]) {
388 /* increment the hit count */
389 if (++s->l2_cache_counts[i] == 0xffffffff) {
390 for(j = 0; j < L2_CACHE_SIZE; j++) {
391 s->l2_cache_counts[j] >>= 1;
394 l2_table = s->l2_cache + (i << s->l2_bits);
395 goto found;
398 /* not found: load a new entry in the least used one */
399 min_index = 0;
400 min_count = 0xffffffff;
401 for(i = 0; i < L2_CACHE_SIZE; i++) {
402 if (s->l2_cache_counts[i] < min_count) {
403 min_count = s->l2_cache_counts[i];
404 min_index = i;
407 l2_table = s->l2_cache + (min_index << s->l2_bits);
408 if (new_l2_table) {
409 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
410 if (bdrv_pwrite_sync(bs->file->bs, l2_offset, l2_table,
411 s->l2_size * sizeof(uint64_t)) < 0)
412 return 0;
413 } else {
414 if (bdrv_pread(bs->file->bs, l2_offset, l2_table,
415 s->l2_size * sizeof(uint64_t)) !=
416 s->l2_size * sizeof(uint64_t))
417 return 0;
419 s->l2_cache_offsets[min_index] = l2_offset;
420 s->l2_cache_counts[min_index] = 1;
421 found:
422 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
423 cluster_offset = be64_to_cpu(l2_table[l2_index]);
424 if (!cluster_offset ||
425 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
426 if (!allocate)
427 return 0;
428 /* allocate a new cluster */
429 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
430 (n_end - n_start) < s->cluster_sectors) {
431 /* if the cluster is already compressed, we must
432 decompress it in the case it is not completely
433 overwritten */
434 if (decompress_cluster(bs, cluster_offset) < 0)
435 return 0;
436 cluster_offset = bdrv_getlength(bs->file->bs);
437 cluster_offset = (cluster_offset + s->cluster_size - 1) &
438 ~(s->cluster_size - 1);
439 /* write the cluster content */
440 if (bdrv_pwrite(bs->file->bs, cluster_offset, s->cluster_cache,
441 s->cluster_size) !=
442 s->cluster_size)
443 return -1;
444 } else {
445 cluster_offset = bdrv_getlength(bs->file->bs);
446 if (allocate == 1) {
447 /* round to cluster size */
448 cluster_offset = (cluster_offset + s->cluster_size - 1) &
449 ~(s->cluster_size - 1);
450 bdrv_truncate(bs->file->bs, cluster_offset + s->cluster_size);
451 /* if encrypted, we must initialize the cluster
452 content which won't be written */
453 if (bs->encrypted &&
454 (n_end - n_start) < s->cluster_sectors) {
455 uint64_t start_sect;
456 assert(s->cipher);
457 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
458 memset(s->cluster_data + 512, 0x00, 512);
459 for(i = 0; i < s->cluster_sectors; i++) {
460 if (i < n_start || i >= n_end) {
461 Error *err = NULL;
462 if (encrypt_sectors(s, start_sect + i,
463 s->cluster_data,
464 s->cluster_data + 512, 1,
465 true, &err) < 0) {
466 error_free(err);
467 errno = EIO;
468 return -1;
470 if (bdrv_pwrite(bs->file->bs,
471 cluster_offset + i * 512,
472 s->cluster_data, 512) != 512)
473 return -1;
477 } else if (allocate == 2) {
478 cluster_offset |= QCOW_OFLAG_COMPRESSED |
479 (uint64_t)compressed_size << (63 - s->cluster_bits);
482 /* update L2 table */
483 tmp = cpu_to_be64(cluster_offset);
484 l2_table[l2_index] = tmp;
485 if (bdrv_pwrite_sync(bs->file->bs, l2_offset + l2_index * sizeof(tmp),
486 &tmp, sizeof(tmp)) < 0)
487 return 0;
489 return cluster_offset;
492 static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
493 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
495 BDRVQcowState *s = bs->opaque;
496 int index_in_cluster, n;
497 uint64_t cluster_offset;
499 qemu_co_mutex_lock(&s->lock);
500 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
501 qemu_co_mutex_unlock(&s->lock);
502 index_in_cluster = sector_num & (s->cluster_sectors - 1);
503 n = s->cluster_sectors - index_in_cluster;
504 if (n > nb_sectors)
505 n = nb_sectors;
506 *pnum = n;
507 if (!cluster_offset) {
508 return 0;
510 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
511 return BDRV_BLOCK_DATA;
513 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
514 *file = bs->file->bs;
515 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
518 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
519 const uint8_t *buf, int buf_size)
521 z_stream strm1, *strm = &strm1;
522 int ret, out_len;
524 memset(strm, 0, sizeof(*strm));
526 strm->next_in = (uint8_t *)buf;
527 strm->avail_in = buf_size;
528 strm->next_out = out_buf;
529 strm->avail_out = out_buf_size;
531 ret = inflateInit2(strm, -12);
532 if (ret != Z_OK)
533 return -1;
534 ret = inflate(strm, Z_FINISH);
535 out_len = strm->next_out - out_buf;
536 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
537 out_len != out_buf_size) {
538 inflateEnd(strm);
539 return -1;
541 inflateEnd(strm);
542 return 0;
545 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
547 BDRVQcowState *s = bs->opaque;
548 int ret, csize;
549 uint64_t coffset;
551 coffset = cluster_offset & s->cluster_offset_mask;
552 if (s->cluster_cache_offset != coffset) {
553 csize = cluster_offset >> (63 - s->cluster_bits);
554 csize &= (s->cluster_size - 1);
555 ret = bdrv_pread(bs->file->bs, coffset, s->cluster_data, csize);
556 if (ret != csize)
557 return -1;
558 if (decompress_buffer(s->cluster_cache, s->cluster_size,
559 s->cluster_data, csize) < 0) {
560 return -1;
562 s->cluster_cache_offset = coffset;
564 return 0;
567 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
568 int nb_sectors, QEMUIOVector *qiov)
570 BDRVQcowState *s = bs->opaque;
571 int index_in_cluster;
572 int ret = 0, n;
573 uint64_t cluster_offset;
574 struct iovec hd_iov;
575 QEMUIOVector hd_qiov;
576 uint8_t *buf;
577 void *orig_buf;
578 Error *err = NULL;
580 if (qiov->niov > 1) {
581 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
582 if (buf == NULL) {
583 return -ENOMEM;
585 } else {
586 orig_buf = NULL;
587 buf = (uint8_t *)qiov->iov->iov_base;
590 qemu_co_mutex_lock(&s->lock);
592 while (nb_sectors != 0) {
593 /* prepare next request */
594 cluster_offset = get_cluster_offset(bs, sector_num << 9,
595 0, 0, 0, 0);
596 index_in_cluster = sector_num & (s->cluster_sectors - 1);
597 n = s->cluster_sectors - index_in_cluster;
598 if (n > nb_sectors) {
599 n = nb_sectors;
602 if (!cluster_offset) {
603 if (bs->backing) {
604 /* read from the base image */
605 hd_iov.iov_base = (void *)buf;
606 hd_iov.iov_len = n * 512;
607 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
608 qemu_co_mutex_unlock(&s->lock);
609 ret = bdrv_co_readv(bs->backing->bs, sector_num,
610 n, &hd_qiov);
611 qemu_co_mutex_lock(&s->lock);
612 if (ret < 0) {
613 goto fail;
615 } else {
616 /* Note: in this case, no need to wait */
617 memset(buf, 0, 512 * n);
619 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
620 /* add AIO support for compressed blocks ? */
621 if (decompress_cluster(bs, cluster_offset) < 0) {
622 goto fail;
624 memcpy(buf,
625 s->cluster_cache + index_in_cluster * 512, 512 * n);
626 } else {
627 if ((cluster_offset & 511) != 0) {
628 goto fail;
630 hd_iov.iov_base = (void *)buf;
631 hd_iov.iov_len = n * 512;
632 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
633 qemu_co_mutex_unlock(&s->lock);
634 ret = bdrv_co_readv(bs->file->bs,
635 (cluster_offset >> 9) + index_in_cluster,
636 n, &hd_qiov);
637 qemu_co_mutex_lock(&s->lock);
638 if (ret < 0) {
639 break;
641 if (bs->encrypted) {
642 assert(s->cipher);
643 if (encrypt_sectors(s, sector_num, buf, buf,
644 n, false, &err) < 0) {
645 goto fail;
649 ret = 0;
651 nb_sectors -= n;
652 sector_num += n;
653 buf += n * 512;
656 done:
657 qemu_co_mutex_unlock(&s->lock);
659 if (qiov->niov > 1) {
660 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
661 qemu_vfree(orig_buf);
664 return ret;
666 fail:
667 error_free(err);
668 ret = -EIO;
669 goto done;
672 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
673 int nb_sectors, QEMUIOVector *qiov)
675 BDRVQcowState *s = bs->opaque;
676 int index_in_cluster;
677 uint64_t cluster_offset;
678 const uint8_t *src_buf;
679 int ret = 0, n;
680 uint8_t *cluster_data = NULL;
681 struct iovec hd_iov;
682 QEMUIOVector hd_qiov;
683 uint8_t *buf;
684 void *orig_buf;
686 s->cluster_cache_offset = -1; /* disable compressed cache */
688 if (qiov->niov > 1) {
689 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
690 if (buf == NULL) {
691 return -ENOMEM;
693 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
694 } else {
695 orig_buf = NULL;
696 buf = (uint8_t *)qiov->iov->iov_base;
699 qemu_co_mutex_lock(&s->lock);
701 while (nb_sectors != 0) {
703 index_in_cluster = sector_num & (s->cluster_sectors - 1);
704 n = s->cluster_sectors - index_in_cluster;
705 if (n > nb_sectors) {
706 n = nb_sectors;
708 cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
709 index_in_cluster,
710 index_in_cluster + n);
711 if (!cluster_offset || (cluster_offset & 511) != 0) {
712 ret = -EIO;
713 break;
715 if (bs->encrypted) {
716 Error *err = NULL;
717 assert(s->cipher);
718 if (!cluster_data) {
719 cluster_data = g_malloc0(s->cluster_size);
721 if (encrypt_sectors(s, sector_num, cluster_data, buf,
722 n, true, &err) < 0) {
723 error_free(err);
724 ret = -EIO;
725 break;
727 src_buf = cluster_data;
728 } else {
729 src_buf = buf;
732 hd_iov.iov_base = (void *)src_buf;
733 hd_iov.iov_len = n * 512;
734 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
735 qemu_co_mutex_unlock(&s->lock);
736 ret = bdrv_co_writev(bs->file->bs,
737 (cluster_offset >> 9) + index_in_cluster,
738 n, &hd_qiov);
739 qemu_co_mutex_lock(&s->lock);
740 if (ret < 0) {
741 break;
743 ret = 0;
745 nb_sectors -= n;
746 sector_num += n;
747 buf += n * 512;
749 qemu_co_mutex_unlock(&s->lock);
751 if (qiov->niov > 1) {
752 qemu_vfree(orig_buf);
754 g_free(cluster_data);
756 return ret;
759 static void qcow_close(BlockDriverState *bs)
761 BDRVQcowState *s = bs->opaque;
763 qcrypto_cipher_free(s->cipher);
764 s->cipher = NULL;
765 g_free(s->l1_table);
766 qemu_vfree(s->l2_cache);
767 g_free(s->cluster_cache);
768 g_free(s->cluster_data);
770 migrate_del_blocker(s->migration_blocker);
771 error_free(s->migration_blocker);
774 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
776 int header_size, backing_filename_len, l1_size, shift, i;
777 QCowHeader header;
778 uint8_t *tmp;
779 int64_t total_size = 0;
780 char *backing_file = NULL;
781 int flags = 0;
782 Error *local_err = NULL;
783 int ret;
784 BlockBackend *qcow_blk;
786 /* Read out options */
787 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
788 BDRV_SECTOR_SIZE);
789 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
790 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
791 flags |= BLOCK_FLAG_ENCRYPT;
794 ret = bdrv_create_file(filename, opts, &local_err);
795 if (ret < 0) {
796 error_propagate(errp, local_err);
797 goto cleanup;
800 qcow_blk = blk_new_open("image", filename, NULL, NULL,
801 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_PROTOCOL,
802 &local_err);
803 if (qcow_blk == NULL) {
804 error_propagate(errp, local_err);
805 ret = -EIO;
806 goto cleanup;
809 blk_set_allow_write_beyond_eof(qcow_blk, true);
811 ret = blk_truncate(qcow_blk, 0);
812 if (ret < 0) {
813 goto exit;
816 memset(&header, 0, sizeof(header));
817 header.magic = cpu_to_be32(QCOW_MAGIC);
818 header.version = cpu_to_be32(QCOW_VERSION);
819 header.size = cpu_to_be64(total_size);
820 header_size = sizeof(header);
821 backing_filename_len = 0;
822 if (backing_file) {
823 if (strcmp(backing_file, "fat:")) {
824 header.backing_file_offset = cpu_to_be64(header_size);
825 backing_filename_len = strlen(backing_file);
826 header.backing_file_size = cpu_to_be32(backing_filename_len);
827 header_size += backing_filename_len;
828 } else {
829 /* special backing file for vvfat */
830 backing_file = NULL;
832 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
833 unmodified sectors */
834 header.l2_bits = 12; /* 32 KB L2 tables */
835 } else {
836 header.cluster_bits = 12; /* 4 KB clusters */
837 header.l2_bits = 9; /* 4 KB L2 tables */
839 header_size = (header_size + 7) & ~7;
840 shift = header.cluster_bits + header.l2_bits;
841 l1_size = (total_size + (1LL << shift) - 1) >> shift;
843 header.l1_table_offset = cpu_to_be64(header_size);
844 if (flags & BLOCK_FLAG_ENCRYPT) {
845 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
846 } else {
847 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
850 /* write all the data */
851 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header));
852 if (ret != sizeof(header)) {
853 goto exit;
856 if (backing_file) {
857 ret = blk_pwrite(qcow_blk, sizeof(header),
858 backing_file, backing_filename_len);
859 if (ret != backing_filename_len) {
860 goto exit;
864 tmp = g_malloc0(BDRV_SECTOR_SIZE);
865 for (i = 0; i < ((sizeof(uint64_t)*l1_size + BDRV_SECTOR_SIZE - 1)/
866 BDRV_SECTOR_SIZE); i++) {
867 ret = blk_pwrite(qcow_blk, header_size +
868 BDRV_SECTOR_SIZE*i, tmp, BDRV_SECTOR_SIZE);
869 if (ret != BDRV_SECTOR_SIZE) {
870 g_free(tmp);
871 goto exit;
875 g_free(tmp);
876 ret = 0;
877 exit:
878 blk_unref(qcow_blk);
879 cleanup:
880 g_free(backing_file);
881 return ret;
884 static int qcow_make_empty(BlockDriverState *bs)
886 BDRVQcowState *s = bs->opaque;
887 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
888 int ret;
890 memset(s->l1_table, 0, l1_length);
891 if (bdrv_pwrite_sync(bs->file->bs, s->l1_table_offset, s->l1_table,
892 l1_length) < 0)
893 return -1;
894 ret = bdrv_truncate(bs->file->bs, s->l1_table_offset + l1_length);
895 if (ret < 0)
896 return ret;
898 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
899 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
900 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
902 return 0;
905 /* XXX: put compressed sectors first, then all the cluster aligned
906 tables to avoid losing bytes in alignment */
907 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
908 const uint8_t *buf, int nb_sectors)
910 BDRVQcowState *s = bs->opaque;
911 z_stream strm;
912 int ret, out_len;
913 uint8_t *out_buf;
914 uint64_t cluster_offset;
916 if (nb_sectors != s->cluster_sectors) {
917 ret = -EINVAL;
919 /* Zero-pad last write if image size is not cluster aligned */
920 if (sector_num + nb_sectors == bs->total_sectors &&
921 nb_sectors < s->cluster_sectors) {
922 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
923 memset(pad_buf, 0, s->cluster_size);
924 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
925 ret = qcow_write_compressed(bs, sector_num,
926 pad_buf, s->cluster_sectors);
927 qemu_vfree(pad_buf);
929 return ret;
932 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
934 /* best compression, small window, no zlib header */
935 memset(&strm, 0, sizeof(strm));
936 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
937 Z_DEFLATED, -12,
938 9, Z_DEFAULT_STRATEGY);
939 if (ret != 0) {
940 ret = -EINVAL;
941 goto fail;
944 strm.avail_in = s->cluster_size;
945 strm.next_in = (uint8_t *)buf;
946 strm.avail_out = s->cluster_size;
947 strm.next_out = out_buf;
949 ret = deflate(&strm, Z_FINISH);
950 if (ret != Z_STREAM_END && ret != Z_OK) {
951 deflateEnd(&strm);
952 ret = -EINVAL;
953 goto fail;
955 out_len = strm.next_out - out_buf;
957 deflateEnd(&strm);
959 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
960 /* could not compress: write normal cluster */
961 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
962 if (ret < 0) {
963 goto fail;
965 } else {
966 cluster_offset = get_cluster_offset(bs, sector_num << 9, 2,
967 out_len, 0, 0);
968 if (cluster_offset == 0) {
969 ret = -EIO;
970 goto fail;
973 cluster_offset &= s->cluster_offset_mask;
974 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
975 if (ret < 0) {
976 goto fail;
980 ret = 0;
981 fail:
982 g_free(out_buf);
983 return ret;
986 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
988 BDRVQcowState *s = bs->opaque;
989 bdi->cluster_size = s->cluster_size;
990 return 0;
993 static QemuOptsList qcow_create_opts = {
994 .name = "qcow-create-opts",
995 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
996 .desc = {
998 .name = BLOCK_OPT_SIZE,
999 .type = QEMU_OPT_SIZE,
1000 .help = "Virtual disk size"
1003 .name = BLOCK_OPT_BACKING_FILE,
1004 .type = QEMU_OPT_STRING,
1005 .help = "File name of a base image"
1008 .name = BLOCK_OPT_ENCRYPT,
1009 .type = QEMU_OPT_BOOL,
1010 .help = "Encrypt the image",
1011 .def_value_str = "off"
1013 { /* end of list */ }
1017 static BlockDriver bdrv_qcow = {
1018 .format_name = "qcow",
1019 .instance_size = sizeof(BDRVQcowState),
1020 .bdrv_probe = qcow_probe,
1021 .bdrv_open = qcow_open,
1022 .bdrv_close = qcow_close,
1023 .bdrv_reopen_prepare = qcow_reopen_prepare,
1024 .bdrv_create = qcow_create,
1025 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1026 .supports_backing = true,
1028 .bdrv_co_readv = qcow_co_readv,
1029 .bdrv_co_writev = qcow_co_writev,
1030 .bdrv_co_get_block_status = qcow_co_get_block_status,
1032 .bdrv_set_key = qcow_set_key,
1033 .bdrv_make_empty = qcow_make_empty,
1034 .bdrv_write_compressed = qcow_write_compressed,
1035 .bdrv_get_info = qcow_get_info,
1037 .create_opts = &qcow_create_opts,
1040 static void bdrv_qcow_init(void)
1042 bdrv_register(&bdrv_qcow);
1045 block_init(bdrv_qcow_init);