target-tricore: add add.f/sub.f instructions
[qemu/ar7.git] / block / qcow.c
blob73cf8a708178bacd10b515563d227b27df44ef58
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 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
125 ret = -ENOTSUP;
126 goto fail;
129 if (header.size <= 1) {
130 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
131 ret = -EINVAL;
132 goto fail;
134 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
135 error_setg(errp, "Cluster size must be between 512 and 64k");
136 ret = -EINVAL;
137 goto fail;
140 /* l2_bits specifies number of entries; storing a uint64_t in each entry,
141 * so bytes = num_entries << 3. */
142 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
143 error_setg(errp, "L2 table size must be between 512 and 64k");
144 ret = -EINVAL;
145 goto fail;
148 if (header.crypt_method > QCOW_CRYPT_AES) {
149 error_setg(errp, "invalid encryption method in qcow header");
150 ret = -EINVAL;
151 goto fail;
153 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
154 error_setg(errp, "AES cipher not available");
155 ret = -EINVAL;
156 goto fail;
158 s->crypt_method_header = header.crypt_method;
159 if (s->crypt_method_header) {
160 bs->encrypted = 1;
162 s->cluster_bits = header.cluster_bits;
163 s->cluster_size = 1 << s->cluster_bits;
164 s->cluster_sectors = 1 << (s->cluster_bits - 9);
165 s->l2_bits = header.l2_bits;
166 s->l2_size = 1 << s->l2_bits;
167 bs->total_sectors = header.size / 512;
168 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
170 /* read the level 1 table */
171 shift = s->cluster_bits + s->l2_bits;
172 if (header.size > UINT64_MAX - (1LL << shift)) {
173 error_setg(errp, "Image too large");
174 ret = -EINVAL;
175 goto fail;
176 } else {
177 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
178 if (l1_size > INT_MAX / sizeof(uint64_t)) {
179 error_setg(errp, "Image too large");
180 ret = -EINVAL;
181 goto fail;
183 s->l1_size = l1_size;
186 s->l1_table_offset = header.l1_table_offset;
187 s->l1_table = g_try_new(uint64_t, s->l1_size);
188 if (s->l1_table == NULL) {
189 error_setg(errp, "Could not allocate memory for L1 table");
190 ret = -ENOMEM;
191 goto fail;
194 ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
195 s->l1_size * sizeof(uint64_t));
196 if (ret < 0) {
197 goto fail;
200 for(i = 0;i < s->l1_size; i++) {
201 be64_to_cpus(&s->l1_table[i]);
204 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
205 s->l2_cache =
206 qemu_try_blockalign(bs->file->bs,
207 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
208 if (s->l2_cache == NULL) {
209 error_setg(errp, "Could not allocate L2 table cache");
210 ret = -ENOMEM;
211 goto fail;
213 s->cluster_cache = g_malloc(s->cluster_size);
214 s->cluster_data = g_malloc(s->cluster_size);
215 s->cluster_cache_offset = -1;
217 /* read the backing file name */
218 if (header.backing_file_offset != 0) {
219 len = header.backing_file_size;
220 if (len > 1023 || len >= sizeof(bs->backing_file)) {
221 error_setg(errp, "Backing file name too long");
222 ret = -EINVAL;
223 goto fail;
225 ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
226 bs->backing_file, len);
227 if (ret < 0) {
228 goto fail;
230 bs->backing_file[len] = '\0';
233 /* Disable migration when qcow images are used */
234 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
235 "does not support live migration",
236 bdrv_get_device_or_node_name(bs));
237 migrate_add_blocker(s->migration_blocker);
239 qemu_co_mutex_init(&s->lock);
240 return 0;
242 fail:
243 g_free(s->l1_table);
244 qemu_vfree(s->l2_cache);
245 g_free(s->cluster_cache);
246 g_free(s->cluster_data);
247 return ret;
251 /* We have nothing to do for QCOW reopen, stubs just return
252 * success */
253 static int qcow_reopen_prepare(BDRVReopenState *state,
254 BlockReopenQueue *queue, Error **errp)
256 return 0;
259 static int qcow_set_key(BlockDriverState *bs, const char *key)
261 BDRVQcowState *s = bs->opaque;
262 uint8_t keybuf[16];
263 int len, i;
264 Error *err;
266 memset(keybuf, 0, 16);
267 len = strlen(key);
268 if (len > 16)
269 len = 16;
270 /* XXX: we could compress the chars to 7 bits to increase
271 entropy */
272 for(i = 0;i < len;i++) {
273 keybuf[i] = key[i];
275 assert(bs->encrypted);
277 qcrypto_cipher_free(s->cipher);
278 s->cipher = qcrypto_cipher_new(
279 QCRYPTO_CIPHER_ALG_AES_128,
280 QCRYPTO_CIPHER_MODE_CBC,
281 keybuf, G_N_ELEMENTS(keybuf),
282 &err);
284 if (!s->cipher) {
285 /* XXX would be nice if errors in this method could
286 * be properly propagate to the caller. Would need
287 * the bdrv_set_key() API signature to be fixed. */
288 error_free(err);
289 return -1;
291 return 0;
294 /* The crypt function is compatible with the linux cryptoloop
295 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
296 supported */
297 static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
298 uint8_t *out_buf, const uint8_t *in_buf,
299 int nb_sectors, bool enc, Error **errp)
301 union {
302 uint64_t ll[2];
303 uint8_t b[16];
304 } ivec;
305 int i;
306 int ret;
308 for(i = 0; i < nb_sectors; i++) {
309 ivec.ll[0] = cpu_to_le64(sector_num);
310 ivec.ll[1] = 0;
311 if (qcrypto_cipher_setiv(s->cipher,
312 ivec.b, G_N_ELEMENTS(ivec.b),
313 errp) < 0) {
314 return -1;
316 if (enc) {
317 ret = qcrypto_cipher_encrypt(s->cipher,
318 in_buf,
319 out_buf,
320 512,
321 errp);
322 } else {
323 ret = qcrypto_cipher_decrypt(s->cipher,
324 in_buf,
325 out_buf,
326 512,
327 errp);
329 if (ret < 0) {
330 return -1;
332 sector_num++;
333 in_buf += 512;
334 out_buf += 512;
336 return 0;
339 /* 'allocate' is:
341 * 0 to not allocate.
343 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
344 * 'n_end')
346 * 2 to allocate a compressed cluster of size
347 * 'compressed_size'. 'compressed_size' must be > 0 and <
348 * cluster_size
350 * return 0 if not allocated.
352 static uint64_t get_cluster_offset(BlockDriverState *bs,
353 uint64_t offset, int allocate,
354 int compressed_size,
355 int n_start, int n_end)
357 BDRVQcowState *s = bs->opaque;
358 int min_index, i, j, l1_index, l2_index;
359 uint64_t l2_offset, *l2_table, cluster_offset, tmp;
360 uint32_t min_count;
361 int new_l2_table;
363 l1_index = offset >> (s->l2_bits + s->cluster_bits);
364 l2_offset = s->l1_table[l1_index];
365 new_l2_table = 0;
366 if (!l2_offset) {
367 if (!allocate)
368 return 0;
369 /* allocate a new l2 entry */
370 l2_offset = bdrv_getlength(bs->file->bs);
371 /* round to cluster size */
372 l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
373 /* update the L1 entry */
374 s->l1_table[l1_index] = l2_offset;
375 tmp = cpu_to_be64(l2_offset);
376 if (bdrv_pwrite_sync(bs->file->bs,
377 s->l1_table_offset + l1_index * sizeof(tmp),
378 &tmp, sizeof(tmp)) < 0)
379 return 0;
380 new_l2_table = 1;
382 for(i = 0; i < L2_CACHE_SIZE; i++) {
383 if (l2_offset == s->l2_cache_offsets[i]) {
384 /* increment the hit count */
385 if (++s->l2_cache_counts[i] == 0xffffffff) {
386 for(j = 0; j < L2_CACHE_SIZE; j++) {
387 s->l2_cache_counts[j] >>= 1;
390 l2_table = s->l2_cache + (i << s->l2_bits);
391 goto found;
394 /* not found: load a new entry in the least used one */
395 min_index = 0;
396 min_count = 0xffffffff;
397 for(i = 0; i < L2_CACHE_SIZE; i++) {
398 if (s->l2_cache_counts[i] < min_count) {
399 min_count = s->l2_cache_counts[i];
400 min_index = i;
403 l2_table = s->l2_cache + (min_index << s->l2_bits);
404 if (new_l2_table) {
405 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
406 if (bdrv_pwrite_sync(bs->file->bs, l2_offset, l2_table,
407 s->l2_size * sizeof(uint64_t)) < 0)
408 return 0;
409 } else {
410 if (bdrv_pread(bs->file->bs, l2_offset, l2_table,
411 s->l2_size * sizeof(uint64_t)) !=
412 s->l2_size * sizeof(uint64_t))
413 return 0;
415 s->l2_cache_offsets[min_index] = l2_offset;
416 s->l2_cache_counts[min_index] = 1;
417 found:
418 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
419 cluster_offset = be64_to_cpu(l2_table[l2_index]);
420 if (!cluster_offset ||
421 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
422 if (!allocate)
423 return 0;
424 /* allocate a new cluster */
425 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
426 (n_end - n_start) < s->cluster_sectors) {
427 /* if the cluster is already compressed, we must
428 decompress it in the case it is not completely
429 overwritten */
430 if (decompress_cluster(bs, cluster_offset) < 0)
431 return 0;
432 cluster_offset = bdrv_getlength(bs->file->bs);
433 cluster_offset = (cluster_offset + s->cluster_size - 1) &
434 ~(s->cluster_size - 1);
435 /* write the cluster content */
436 if (bdrv_pwrite(bs->file->bs, cluster_offset, s->cluster_cache,
437 s->cluster_size) !=
438 s->cluster_size)
439 return -1;
440 } else {
441 cluster_offset = bdrv_getlength(bs->file->bs);
442 if (allocate == 1) {
443 /* round to cluster size */
444 cluster_offset = (cluster_offset + s->cluster_size - 1) &
445 ~(s->cluster_size - 1);
446 bdrv_truncate(bs->file->bs, cluster_offset + s->cluster_size);
447 /* if encrypted, we must initialize the cluster
448 content which won't be written */
449 if (bs->encrypted &&
450 (n_end - n_start) < s->cluster_sectors) {
451 uint64_t start_sect;
452 assert(s->cipher);
453 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
454 memset(s->cluster_data + 512, 0x00, 512);
455 for(i = 0; i < s->cluster_sectors; i++) {
456 if (i < n_start || i >= n_end) {
457 Error *err = NULL;
458 if (encrypt_sectors(s, start_sect + i,
459 s->cluster_data,
460 s->cluster_data + 512, 1,
461 true, &err) < 0) {
462 error_free(err);
463 errno = EIO;
464 return -1;
466 if (bdrv_pwrite(bs->file->bs,
467 cluster_offset + i * 512,
468 s->cluster_data, 512) != 512)
469 return -1;
473 } else if (allocate == 2) {
474 cluster_offset |= QCOW_OFLAG_COMPRESSED |
475 (uint64_t)compressed_size << (63 - s->cluster_bits);
478 /* update L2 table */
479 tmp = cpu_to_be64(cluster_offset);
480 l2_table[l2_index] = tmp;
481 if (bdrv_pwrite_sync(bs->file->bs, l2_offset + l2_index * sizeof(tmp),
482 &tmp, sizeof(tmp)) < 0)
483 return 0;
485 return cluster_offset;
488 static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
489 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
491 BDRVQcowState *s = bs->opaque;
492 int index_in_cluster, n;
493 uint64_t cluster_offset;
495 qemu_co_mutex_lock(&s->lock);
496 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
497 qemu_co_mutex_unlock(&s->lock);
498 index_in_cluster = sector_num & (s->cluster_sectors - 1);
499 n = s->cluster_sectors - index_in_cluster;
500 if (n > nb_sectors)
501 n = nb_sectors;
502 *pnum = n;
503 if (!cluster_offset) {
504 return 0;
506 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
507 return BDRV_BLOCK_DATA;
509 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
510 *file = bs->file->bs;
511 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
514 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
515 const uint8_t *buf, int buf_size)
517 z_stream strm1, *strm = &strm1;
518 int ret, out_len;
520 memset(strm, 0, sizeof(*strm));
522 strm->next_in = (uint8_t *)buf;
523 strm->avail_in = buf_size;
524 strm->next_out = out_buf;
525 strm->avail_out = out_buf_size;
527 ret = inflateInit2(strm, -12);
528 if (ret != Z_OK)
529 return -1;
530 ret = inflate(strm, Z_FINISH);
531 out_len = strm->next_out - out_buf;
532 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
533 out_len != out_buf_size) {
534 inflateEnd(strm);
535 return -1;
537 inflateEnd(strm);
538 return 0;
541 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
543 BDRVQcowState *s = bs->opaque;
544 int ret, csize;
545 uint64_t coffset;
547 coffset = cluster_offset & s->cluster_offset_mask;
548 if (s->cluster_cache_offset != coffset) {
549 csize = cluster_offset >> (63 - s->cluster_bits);
550 csize &= (s->cluster_size - 1);
551 ret = bdrv_pread(bs->file->bs, coffset, s->cluster_data, csize);
552 if (ret != csize)
553 return -1;
554 if (decompress_buffer(s->cluster_cache, s->cluster_size,
555 s->cluster_data, csize) < 0) {
556 return -1;
558 s->cluster_cache_offset = coffset;
560 return 0;
563 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
564 int nb_sectors, QEMUIOVector *qiov)
566 BDRVQcowState *s = bs->opaque;
567 int index_in_cluster;
568 int ret = 0, n;
569 uint64_t cluster_offset;
570 struct iovec hd_iov;
571 QEMUIOVector hd_qiov;
572 uint8_t *buf;
573 void *orig_buf;
574 Error *err = NULL;
576 if (qiov->niov > 1) {
577 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
578 if (buf == NULL) {
579 return -ENOMEM;
581 } else {
582 orig_buf = NULL;
583 buf = (uint8_t *)qiov->iov->iov_base;
586 qemu_co_mutex_lock(&s->lock);
588 while (nb_sectors != 0) {
589 /* prepare next request */
590 cluster_offset = get_cluster_offset(bs, sector_num << 9,
591 0, 0, 0, 0);
592 index_in_cluster = sector_num & (s->cluster_sectors - 1);
593 n = s->cluster_sectors - index_in_cluster;
594 if (n > nb_sectors) {
595 n = nb_sectors;
598 if (!cluster_offset) {
599 if (bs->backing) {
600 /* read from the base image */
601 hd_iov.iov_base = (void *)buf;
602 hd_iov.iov_len = n * 512;
603 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
604 qemu_co_mutex_unlock(&s->lock);
605 ret = bdrv_co_readv(bs->backing->bs, sector_num,
606 n, &hd_qiov);
607 qemu_co_mutex_lock(&s->lock);
608 if (ret < 0) {
609 goto fail;
611 } else {
612 /* Note: in this case, no need to wait */
613 memset(buf, 0, 512 * n);
615 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
616 /* add AIO support for compressed blocks ? */
617 if (decompress_cluster(bs, cluster_offset) < 0) {
618 goto fail;
620 memcpy(buf,
621 s->cluster_cache + index_in_cluster * 512, 512 * n);
622 } else {
623 if ((cluster_offset & 511) != 0) {
624 goto fail;
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->file->bs,
631 (cluster_offset >> 9) + index_in_cluster,
632 n, &hd_qiov);
633 qemu_co_mutex_lock(&s->lock);
634 if (ret < 0) {
635 break;
637 if (bs->encrypted) {
638 assert(s->cipher);
639 if (encrypt_sectors(s, sector_num, buf, buf,
640 n, false, &err) < 0) {
641 goto fail;
645 ret = 0;
647 nb_sectors -= n;
648 sector_num += n;
649 buf += n * 512;
652 done:
653 qemu_co_mutex_unlock(&s->lock);
655 if (qiov->niov > 1) {
656 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
657 qemu_vfree(orig_buf);
660 return ret;
662 fail:
663 error_free(err);
664 ret = -EIO;
665 goto done;
668 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
669 int nb_sectors, QEMUIOVector *qiov)
671 BDRVQcowState *s = bs->opaque;
672 int index_in_cluster;
673 uint64_t cluster_offset;
674 const uint8_t *src_buf;
675 int ret = 0, n;
676 uint8_t *cluster_data = NULL;
677 struct iovec hd_iov;
678 QEMUIOVector hd_qiov;
679 uint8_t *buf;
680 void *orig_buf;
682 s->cluster_cache_offset = -1; /* disable compressed cache */
684 if (qiov->niov > 1) {
685 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
686 if (buf == NULL) {
687 return -ENOMEM;
689 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
690 } else {
691 orig_buf = NULL;
692 buf = (uint8_t *)qiov->iov->iov_base;
695 qemu_co_mutex_lock(&s->lock);
697 while (nb_sectors != 0) {
699 index_in_cluster = sector_num & (s->cluster_sectors - 1);
700 n = s->cluster_sectors - index_in_cluster;
701 if (n > nb_sectors) {
702 n = nb_sectors;
704 cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
705 index_in_cluster,
706 index_in_cluster + n);
707 if (!cluster_offset || (cluster_offset & 511) != 0) {
708 ret = -EIO;
709 break;
711 if (bs->encrypted) {
712 Error *err = NULL;
713 assert(s->cipher);
714 if (!cluster_data) {
715 cluster_data = g_malloc0(s->cluster_size);
717 if (encrypt_sectors(s, sector_num, cluster_data, buf,
718 n, true, &err) < 0) {
719 error_free(err);
720 ret = -EIO;
721 break;
723 src_buf = cluster_data;
724 } else {
725 src_buf = buf;
728 hd_iov.iov_base = (void *)src_buf;
729 hd_iov.iov_len = n * 512;
730 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
731 qemu_co_mutex_unlock(&s->lock);
732 ret = bdrv_co_writev(bs->file->bs,
733 (cluster_offset >> 9) + index_in_cluster,
734 n, &hd_qiov);
735 qemu_co_mutex_lock(&s->lock);
736 if (ret < 0) {
737 break;
739 ret = 0;
741 nb_sectors -= n;
742 sector_num += n;
743 buf += n * 512;
745 qemu_co_mutex_unlock(&s->lock);
747 if (qiov->niov > 1) {
748 qemu_vfree(orig_buf);
750 g_free(cluster_data);
752 return ret;
755 static void qcow_close(BlockDriverState *bs)
757 BDRVQcowState *s = bs->opaque;
759 qcrypto_cipher_free(s->cipher);
760 s->cipher = NULL;
761 g_free(s->l1_table);
762 qemu_vfree(s->l2_cache);
763 g_free(s->cluster_cache);
764 g_free(s->cluster_data);
766 migrate_del_blocker(s->migration_blocker);
767 error_free(s->migration_blocker);
770 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
772 int header_size, backing_filename_len, l1_size, shift, i;
773 QCowHeader header;
774 uint8_t *tmp;
775 int64_t total_size = 0;
776 char *backing_file = NULL;
777 int flags = 0;
778 Error *local_err = NULL;
779 int ret;
780 BlockBackend *qcow_blk;
782 /* Read out options */
783 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
784 BDRV_SECTOR_SIZE);
785 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
786 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
787 flags |= BLOCK_FLAG_ENCRYPT;
790 ret = bdrv_create_file(filename, opts, &local_err);
791 if (ret < 0) {
792 error_propagate(errp, local_err);
793 goto cleanup;
796 qcow_blk = blk_new_open(filename, NULL, NULL,
797 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_PROTOCOL,
798 &local_err);
799 if (qcow_blk == NULL) {
800 error_propagate(errp, local_err);
801 ret = -EIO;
802 goto cleanup;
805 blk_set_allow_write_beyond_eof(qcow_blk, true);
807 ret = blk_truncate(qcow_blk, 0);
808 if (ret < 0) {
809 goto exit;
812 memset(&header, 0, sizeof(header));
813 header.magic = cpu_to_be32(QCOW_MAGIC);
814 header.version = cpu_to_be32(QCOW_VERSION);
815 header.size = cpu_to_be64(total_size);
816 header_size = sizeof(header);
817 backing_filename_len = 0;
818 if (backing_file) {
819 if (strcmp(backing_file, "fat:")) {
820 header.backing_file_offset = cpu_to_be64(header_size);
821 backing_filename_len = strlen(backing_file);
822 header.backing_file_size = cpu_to_be32(backing_filename_len);
823 header_size += backing_filename_len;
824 } else {
825 /* special backing file for vvfat */
826 backing_file = NULL;
828 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
829 unmodified sectors */
830 header.l2_bits = 12; /* 32 KB L2 tables */
831 } else {
832 header.cluster_bits = 12; /* 4 KB clusters */
833 header.l2_bits = 9; /* 4 KB L2 tables */
835 header_size = (header_size + 7) & ~7;
836 shift = header.cluster_bits + header.l2_bits;
837 l1_size = (total_size + (1LL << shift) - 1) >> shift;
839 header.l1_table_offset = cpu_to_be64(header_size);
840 if (flags & BLOCK_FLAG_ENCRYPT) {
841 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
842 } else {
843 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
846 /* write all the data */
847 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header));
848 if (ret != sizeof(header)) {
849 goto exit;
852 if (backing_file) {
853 ret = blk_pwrite(qcow_blk, sizeof(header),
854 backing_file, backing_filename_len);
855 if (ret != backing_filename_len) {
856 goto exit;
860 tmp = g_malloc0(BDRV_SECTOR_SIZE);
861 for (i = 0; i < ((sizeof(uint64_t)*l1_size + BDRV_SECTOR_SIZE - 1)/
862 BDRV_SECTOR_SIZE); i++) {
863 ret = blk_pwrite(qcow_blk, header_size +
864 BDRV_SECTOR_SIZE*i, tmp, BDRV_SECTOR_SIZE);
865 if (ret != BDRV_SECTOR_SIZE) {
866 g_free(tmp);
867 goto exit;
871 g_free(tmp);
872 ret = 0;
873 exit:
874 blk_unref(qcow_blk);
875 cleanup:
876 g_free(backing_file);
877 return ret;
880 static int qcow_make_empty(BlockDriverState *bs)
882 BDRVQcowState *s = bs->opaque;
883 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
884 int ret;
886 memset(s->l1_table, 0, l1_length);
887 if (bdrv_pwrite_sync(bs->file->bs, s->l1_table_offset, s->l1_table,
888 l1_length) < 0)
889 return -1;
890 ret = bdrv_truncate(bs->file->bs, s->l1_table_offset + l1_length);
891 if (ret < 0)
892 return ret;
894 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
895 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
896 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
898 return 0;
901 /* XXX: put compressed sectors first, then all the cluster aligned
902 tables to avoid losing bytes in alignment */
903 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
904 const uint8_t *buf, int nb_sectors)
906 BDRVQcowState *s = bs->opaque;
907 z_stream strm;
908 int ret, out_len;
909 uint8_t *out_buf;
910 uint64_t cluster_offset;
912 if (nb_sectors != s->cluster_sectors) {
913 ret = -EINVAL;
915 /* Zero-pad last write if image size is not cluster aligned */
916 if (sector_num + nb_sectors == bs->total_sectors &&
917 nb_sectors < s->cluster_sectors) {
918 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
919 memset(pad_buf, 0, s->cluster_size);
920 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
921 ret = qcow_write_compressed(bs, sector_num,
922 pad_buf, s->cluster_sectors);
923 qemu_vfree(pad_buf);
925 return ret;
928 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
930 /* best compression, small window, no zlib header */
931 memset(&strm, 0, sizeof(strm));
932 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
933 Z_DEFLATED, -12,
934 9, Z_DEFAULT_STRATEGY);
935 if (ret != 0) {
936 ret = -EINVAL;
937 goto fail;
940 strm.avail_in = s->cluster_size;
941 strm.next_in = (uint8_t *)buf;
942 strm.avail_out = s->cluster_size;
943 strm.next_out = out_buf;
945 ret = deflate(&strm, Z_FINISH);
946 if (ret != Z_STREAM_END && ret != Z_OK) {
947 deflateEnd(&strm);
948 ret = -EINVAL;
949 goto fail;
951 out_len = strm.next_out - out_buf;
953 deflateEnd(&strm);
955 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
956 /* could not compress: write normal cluster */
957 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
958 if (ret < 0) {
959 goto fail;
961 } else {
962 cluster_offset = get_cluster_offset(bs, sector_num << 9, 2,
963 out_len, 0, 0);
964 if (cluster_offset == 0) {
965 ret = -EIO;
966 goto fail;
969 cluster_offset &= s->cluster_offset_mask;
970 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
971 if (ret < 0) {
972 goto fail;
976 ret = 0;
977 fail:
978 g_free(out_buf);
979 return ret;
982 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
984 BDRVQcowState *s = bs->opaque;
985 bdi->cluster_size = s->cluster_size;
986 return 0;
989 static QemuOptsList qcow_create_opts = {
990 .name = "qcow-create-opts",
991 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
992 .desc = {
994 .name = BLOCK_OPT_SIZE,
995 .type = QEMU_OPT_SIZE,
996 .help = "Virtual disk size"
999 .name = BLOCK_OPT_BACKING_FILE,
1000 .type = QEMU_OPT_STRING,
1001 .help = "File name of a base image"
1004 .name = BLOCK_OPT_ENCRYPT,
1005 .type = QEMU_OPT_BOOL,
1006 .help = "Encrypt the image",
1007 .def_value_str = "off"
1009 { /* end of list */ }
1013 static BlockDriver bdrv_qcow = {
1014 .format_name = "qcow",
1015 .instance_size = sizeof(BDRVQcowState),
1016 .bdrv_probe = qcow_probe,
1017 .bdrv_open = qcow_open,
1018 .bdrv_close = qcow_close,
1019 .bdrv_reopen_prepare = qcow_reopen_prepare,
1020 .bdrv_create = qcow_create,
1021 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1022 .supports_backing = true,
1024 .bdrv_co_readv = qcow_co_readv,
1025 .bdrv_co_writev = qcow_co_writev,
1026 .bdrv_co_get_block_status = qcow_co_get_block_status,
1028 .bdrv_set_key = qcow_set_key,
1029 .bdrv_make_empty = qcow_make_empty,
1030 .bdrv_write_compressed = qcow_write_compressed,
1031 .bdrv_get_info = qcow_get_info,
1033 .create_opts = &qcow_create_opts,
1036 static void bdrv_qcow_init(void)
1038 bdrv_register(&bdrv_qcow);
1041 block_init(bdrv_qcow_init);