virtio-serial-bus: bump up control vq size to 32
[qemu.git] / block / qcow2.c
blobb6b094c7976edf2db05a62f06b02ebbf78c4a726
1 /*
2 * Block driver for the QCOW version 2 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-common.h"
25 #include "block_int.h"
26 #include "module.h"
27 #include <zlib.h>
28 #include "aes.h"
29 #include "block/qcow2.h"
30 #include "qemu-error.h"
33 Differences with QCOW:
35 - Support for multiple incremental snapshots.
36 - Memory management by reference counts.
37 - Clusters which have a reference count of one have the bit
38 QCOW_OFLAG_COPIED to optimize write performance.
39 - Size of compressed clusters is stored in sectors to reduce bit usage
40 in the cluster offsets.
41 - Support for storing additional data (such as the VM state) in the
42 snapshots.
43 - If a backing store is used, the cluster size is not constrained
44 (could be backported to QCOW).
45 - L2 tables have always a size of one cluster.
49 typedef struct {
50 uint32_t magic;
51 uint32_t len;
52 } QCowExtension;
53 #define QCOW2_EXT_MAGIC_END 0
54 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
56 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
58 const QCowHeader *cow_header = (const void *)buf;
60 if (buf_size >= sizeof(QCowHeader) &&
61 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
62 be32_to_cpu(cow_header->version) == QCOW_VERSION)
63 return 100;
64 else
65 return 0;
69 /*
70 * read qcow2 extension and fill bs
71 * start reading from start_offset
72 * finish reading upon magic of value 0 or when end_offset reached
73 * unknown magic is skipped (future extension this version knows nothing about)
74 * return 0 upon success, non-0 otherwise
76 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
77 uint64_t end_offset)
79 QCowExtension ext;
80 uint64_t offset;
82 #ifdef DEBUG_EXT
83 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
84 #endif
85 offset = start_offset;
86 while (offset < end_offset) {
88 #ifdef DEBUG_EXT
89 /* Sanity check */
90 if (offset > s->cluster_size)
91 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
93 printf("attemting to read extended header in offset %lu\n", offset);
94 #endif
96 if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
97 fprintf(stderr, "qcow2_read_extension: ERROR: "
98 "pread fail from offset %" PRIu64 "\n",
99 offset);
100 return 1;
102 be32_to_cpus(&ext.magic);
103 be32_to_cpus(&ext.len);
104 offset += sizeof(ext);
105 #ifdef DEBUG_EXT
106 printf("ext.magic = 0x%x\n", ext.magic);
107 #endif
108 switch (ext.magic) {
109 case QCOW2_EXT_MAGIC_END:
110 return 0;
112 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
113 if (ext.len >= sizeof(bs->backing_format)) {
114 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
115 " (>=%zu)\n",
116 ext.len, sizeof(bs->backing_format));
117 return 2;
119 if (bdrv_pread(bs->file, offset , bs->backing_format,
120 ext.len) != ext.len)
121 return 3;
122 bs->backing_format[ext.len] = '\0';
123 #ifdef DEBUG_EXT
124 printf("Qcow2: Got format extension %s\n", bs->backing_format);
125 #endif
126 offset = ((offset + ext.len + 7) & ~7);
127 break;
129 default:
130 /* unknown magic -- just skip it */
131 offset = ((offset + ext.len + 7) & ~7);
132 break;
136 return 0;
140 static int qcow2_open(BlockDriverState *bs, int flags)
142 BDRVQcowState *s = bs->opaque;
143 int len, i, ret = 0;
144 QCowHeader header;
145 uint64_t ext_end;
147 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
148 if (ret < 0) {
149 goto fail;
151 be32_to_cpus(&header.magic);
152 be32_to_cpus(&header.version);
153 be64_to_cpus(&header.backing_file_offset);
154 be32_to_cpus(&header.backing_file_size);
155 be64_to_cpus(&header.size);
156 be32_to_cpus(&header.cluster_bits);
157 be32_to_cpus(&header.crypt_method);
158 be64_to_cpus(&header.l1_table_offset);
159 be32_to_cpus(&header.l1_size);
160 be64_to_cpus(&header.refcount_table_offset);
161 be32_to_cpus(&header.refcount_table_clusters);
162 be64_to_cpus(&header.snapshots_offset);
163 be32_to_cpus(&header.nb_snapshots);
165 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION) {
166 ret = -EINVAL;
167 goto fail;
169 if (header.cluster_bits < MIN_CLUSTER_BITS ||
170 header.cluster_bits > MAX_CLUSTER_BITS) {
171 ret = -EINVAL;
172 goto fail;
174 if (header.crypt_method > QCOW_CRYPT_AES) {
175 ret = -EINVAL;
176 goto fail;
178 s->crypt_method_header = header.crypt_method;
179 if (s->crypt_method_header) {
180 bs->encrypted = 1;
182 s->cluster_bits = header.cluster_bits;
183 s->cluster_size = 1 << s->cluster_bits;
184 s->cluster_sectors = 1 << (s->cluster_bits - 9);
185 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
186 s->l2_size = 1 << s->l2_bits;
187 bs->total_sectors = header.size / 512;
188 s->csize_shift = (62 - (s->cluster_bits - 8));
189 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
190 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
191 s->refcount_table_offset = header.refcount_table_offset;
192 s->refcount_table_size =
193 header.refcount_table_clusters << (s->cluster_bits - 3);
195 s->snapshots_offset = header.snapshots_offset;
196 s->nb_snapshots = header.nb_snapshots;
198 /* read the level 1 table */
199 s->l1_size = header.l1_size;
200 s->l1_vm_state_index = size_to_l1(s, header.size);
201 /* the L1 table must contain at least enough entries to put
202 header.size bytes */
203 if (s->l1_size < s->l1_vm_state_index) {
204 ret = -EINVAL;
205 goto fail;
207 s->l1_table_offset = header.l1_table_offset;
208 if (s->l1_size > 0) {
209 s->l1_table = qemu_mallocz(
210 align_offset(s->l1_size * sizeof(uint64_t), 512));
211 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
212 s->l1_size * sizeof(uint64_t));
213 if (ret < 0) {
214 goto fail;
216 for(i = 0;i < s->l1_size; i++) {
217 be64_to_cpus(&s->l1_table[i]);
220 /* alloc L2 cache */
221 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
222 s->cluster_cache = qemu_malloc(s->cluster_size);
223 /* one more sector for decompressed data alignment */
224 s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
225 + 512);
226 s->cluster_cache_offset = -1;
228 ret = qcow2_refcount_init(bs);
229 if (ret != 0) {
230 goto fail;
233 QLIST_INIT(&s->cluster_allocs);
235 /* read qcow2 extensions */
236 if (header.backing_file_offset) {
237 ext_end = header.backing_file_offset;
238 } else {
239 ext_end = s->cluster_size;
241 if (qcow2_read_extensions(bs, sizeof(header), ext_end)) {
242 ret = -EINVAL;
243 goto fail;
246 /* read the backing file name */
247 if (header.backing_file_offset != 0) {
248 len = header.backing_file_size;
249 if (len > 1023) {
250 len = 1023;
252 ret = bdrv_pread(bs->file, header.backing_file_offset,
253 bs->backing_file, len);
254 if (ret < 0) {
255 goto fail;
257 bs->backing_file[len] = '\0';
259 if (qcow2_read_snapshots(bs) < 0) {
260 ret = -EINVAL;
261 goto fail;
264 #ifdef DEBUG_ALLOC
265 qcow2_check_refcounts(bs);
266 #endif
267 return ret;
269 fail:
270 qcow2_free_snapshots(bs);
271 qcow2_refcount_close(bs);
272 qemu_free(s->l1_table);
273 qemu_free(s->l2_cache);
274 qemu_free(s->cluster_cache);
275 qemu_free(s->cluster_data);
276 return ret;
279 static int qcow2_set_key(BlockDriverState *bs, const char *key)
281 BDRVQcowState *s = bs->opaque;
282 uint8_t keybuf[16];
283 int len, i;
285 memset(keybuf, 0, 16);
286 len = strlen(key);
287 if (len > 16)
288 len = 16;
289 /* XXX: we could compress the chars to 7 bits to increase
290 entropy */
291 for(i = 0;i < len;i++) {
292 keybuf[i] = key[i];
294 s->crypt_method = s->crypt_method_header;
296 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
297 return -1;
298 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
299 return -1;
300 #if 0
301 /* test */
303 uint8_t in[16];
304 uint8_t out[16];
305 uint8_t tmp[16];
306 for(i=0;i<16;i++)
307 in[i] = i;
308 AES_encrypt(in, tmp, &s->aes_encrypt_key);
309 AES_decrypt(tmp, out, &s->aes_decrypt_key);
310 for(i = 0; i < 16; i++)
311 printf(" %02x", tmp[i]);
312 printf("\n");
313 for(i = 0; i < 16; i++)
314 printf(" %02x", out[i]);
315 printf("\n");
317 #endif
318 return 0;
321 static int qcow2_is_allocated(BlockDriverState *bs, int64_t sector_num,
322 int nb_sectors, int *pnum)
324 uint64_t cluster_offset;
325 int ret;
327 *pnum = nb_sectors;
328 /* FIXME We can get errors here, but the bdrv_is_allocated interface can't
329 * pass them on today */
330 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
331 if (ret < 0) {
332 *pnum = 0;
335 return (cluster_offset != 0);
338 /* handle reading after the end of the backing file */
339 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
340 int64_t sector_num, int nb_sectors)
342 int n1;
343 if ((sector_num + nb_sectors) <= bs->total_sectors)
344 return nb_sectors;
345 if (sector_num >= bs->total_sectors)
346 n1 = 0;
347 else
348 n1 = bs->total_sectors - sector_num;
350 qemu_iovec_memset(qiov, 0, 512 * (nb_sectors - n1));
352 return n1;
355 typedef struct QCowAIOCB {
356 BlockDriverAIOCB common;
357 int64_t sector_num;
358 QEMUIOVector *qiov;
359 int remaining_sectors;
360 int cur_nr_sectors; /* number of sectors in current iteration */
361 uint64_t bytes_done;
362 uint64_t cluster_offset;
363 uint8_t *cluster_data;
364 BlockDriverAIOCB *hd_aiocb;
365 QEMUIOVector hd_qiov;
366 QEMUBH *bh;
367 QCowL2Meta l2meta;
368 QLIST_ENTRY(QCowAIOCB) next_depend;
369 } QCowAIOCB;
371 static void qcow2_aio_cancel(BlockDriverAIOCB *blockacb)
373 QCowAIOCB *acb = container_of(blockacb, QCowAIOCB, common);
374 if (acb->hd_aiocb)
375 bdrv_aio_cancel(acb->hd_aiocb);
376 qemu_aio_release(acb);
379 static AIOPool qcow2_aio_pool = {
380 .aiocb_size = sizeof(QCowAIOCB),
381 .cancel = qcow2_aio_cancel,
384 static void qcow2_aio_read_cb(void *opaque, int ret);
385 static void qcow2_aio_read_bh(void *opaque)
387 QCowAIOCB *acb = opaque;
388 qemu_bh_delete(acb->bh);
389 acb->bh = NULL;
390 qcow2_aio_read_cb(opaque, 0);
393 static int qcow2_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
395 if (acb->bh)
396 return -EIO;
398 acb->bh = qemu_bh_new(cb, acb);
399 if (!acb->bh)
400 return -EIO;
402 qemu_bh_schedule(acb->bh);
404 return 0;
407 static void qcow2_aio_read_cb(void *opaque, int ret)
409 QCowAIOCB *acb = opaque;
410 BlockDriverState *bs = acb->common.bs;
411 BDRVQcowState *s = bs->opaque;
412 int index_in_cluster, n1;
414 acb->hd_aiocb = NULL;
415 if (ret < 0)
416 goto done;
418 /* post process the read buffer */
419 if (!acb->cluster_offset) {
420 /* nothing to do */
421 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
422 /* nothing to do */
423 } else {
424 if (s->crypt_method) {
425 qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data,
426 acb->cluster_data, acb->cur_nr_sectors, 0, &s->aes_decrypt_key);
427 qemu_iovec_reset(&acb->hd_qiov);
428 qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,
429 acb->cur_nr_sectors * 512);
430 qemu_iovec_from_buffer(&acb->hd_qiov, acb->cluster_data,
431 512 * acb->cur_nr_sectors);
435 acb->remaining_sectors -= acb->cur_nr_sectors;
436 acb->sector_num += acb->cur_nr_sectors;
437 acb->bytes_done += acb->cur_nr_sectors * 512;
439 if (acb->remaining_sectors == 0) {
440 /* request completed */
441 ret = 0;
442 goto done;
445 /* prepare next AIO request */
446 acb->cur_nr_sectors = acb->remaining_sectors;
447 if (s->crypt_method) {
448 acb->cur_nr_sectors = MIN(acb->cur_nr_sectors,
449 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
452 ret = qcow2_get_cluster_offset(bs, acb->sector_num << 9,
453 &acb->cur_nr_sectors, &acb->cluster_offset);
454 if (ret < 0) {
455 goto done;
458 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
460 qemu_iovec_reset(&acb->hd_qiov);
461 qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,
462 acb->cur_nr_sectors * 512);
464 if (!acb->cluster_offset) {
466 if (bs->backing_hd) {
467 /* read from the base image */
468 n1 = qcow2_backing_read1(bs->backing_hd, &acb->hd_qiov,
469 acb->sector_num, acb->cur_nr_sectors);
470 if (n1 > 0) {
471 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
472 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
473 &acb->hd_qiov, acb->cur_nr_sectors,
474 qcow2_aio_read_cb, acb);
475 if (acb->hd_aiocb == NULL)
476 goto done;
477 } else {
478 ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);
479 if (ret < 0)
480 goto done;
482 } else {
483 /* Note: in this case, no need to wait */
484 qemu_iovec_memset(&acb->hd_qiov, 0, 512 * acb->cur_nr_sectors);
485 ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);
486 if (ret < 0)
487 goto done;
489 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
490 /* add AIO support for compressed blocks ? */
491 if (qcow2_decompress_cluster(bs, acb->cluster_offset) < 0)
492 goto done;
494 qemu_iovec_from_buffer(&acb->hd_qiov,
495 s->cluster_cache + index_in_cluster * 512,
496 512 * acb->cur_nr_sectors);
498 ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);
499 if (ret < 0)
500 goto done;
501 } else {
502 if ((acb->cluster_offset & 511) != 0) {
503 ret = -EIO;
504 goto done;
507 if (s->crypt_method) {
509 * For encrypted images, read everything into a temporary
510 * contiguous buffer on which the AES functions can work.
512 if (!acb->cluster_data) {
513 acb->cluster_data =
514 qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
517 assert(acb->cur_nr_sectors <=
518 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
519 qemu_iovec_reset(&acb->hd_qiov);
520 qemu_iovec_add(&acb->hd_qiov, acb->cluster_data,
521 512 * acb->cur_nr_sectors);
524 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
525 acb->hd_aiocb = bdrv_aio_readv(bs->file,
526 (acb->cluster_offset >> 9) + index_in_cluster,
527 &acb->hd_qiov, acb->cur_nr_sectors,
528 qcow2_aio_read_cb, acb);
529 if (acb->hd_aiocb == NULL) {
530 ret = -EIO;
531 goto done;
535 return;
536 done:
537 acb->common.cb(acb->common.opaque, ret);
538 qemu_iovec_destroy(&acb->hd_qiov);
539 qemu_aio_release(acb);
542 static QCowAIOCB *qcow2_aio_setup(BlockDriverState *bs, int64_t sector_num,
543 QEMUIOVector *qiov, int nb_sectors,
544 BlockDriverCompletionFunc *cb,
545 void *opaque, int is_write)
547 QCowAIOCB *acb;
549 acb = qemu_aio_get(&qcow2_aio_pool, bs, cb, opaque);
550 if (!acb)
551 return NULL;
552 acb->hd_aiocb = NULL;
553 acb->sector_num = sector_num;
554 acb->qiov = qiov;
556 qemu_iovec_init(&acb->hd_qiov, qiov->niov);
558 acb->bytes_done = 0;
559 acb->remaining_sectors = nb_sectors;
560 acb->cur_nr_sectors = 0;
561 acb->cluster_offset = 0;
562 acb->l2meta.nb_clusters = 0;
563 QLIST_INIT(&acb->l2meta.dependent_requests);
564 return acb;
567 static BlockDriverAIOCB *qcow2_aio_readv(BlockDriverState *bs,
568 int64_t sector_num,
569 QEMUIOVector *qiov, int nb_sectors,
570 BlockDriverCompletionFunc *cb,
571 void *opaque)
573 QCowAIOCB *acb;
575 acb = qcow2_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
576 if (!acb)
577 return NULL;
579 qcow2_aio_read_cb(acb, 0);
580 return &acb->common;
583 static void qcow2_aio_write_cb(void *opaque, int ret);
585 static void run_dependent_requests(QCowL2Meta *m)
587 QCowAIOCB *req;
588 QCowAIOCB *next;
590 /* Take the request off the list of running requests */
591 if (m->nb_clusters != 0) {
592 QLIST_REMOVE(m, next_in_flight);
595 /* Restart all dependent requests */
596 QLIST_FOREACH_SAFE(req, &m->dependent_requests, next_depend, next) {
597 qcow2_aio_write_cb(req, 0);
600 /* Empty the list for the next part of the request */
601 QLIST_INIT(&m->dependent_requests);
604 static void qcow2_aio_write_cb(void *opaque, int ret)
606 QCowAIOCB *acb = opaque;
607 BlockDriverState *bs = acb->common.bs;
608 BDRVQcowState *s = bs->opaque;
609 int index_in_cluster;
610 int n_end;
612 acb->hd_aiocb = NULL;
614 if (ret >= 0) {
615 ret = qcow2_alloc_cluster_link_l2(bs, &acb->l2meta);
618 run_dependent_requests(&acb->l2meta);
620 if (ret < 0)
621 goto done;
623 acb->remaining_sectors -= acb->cur_nr_sectors;
624 acb->sector_num += acb->cur_nr_sectors;
625 acb->bytes_done += acb->cur_nr_sectors * 512;
627 if (acb->remaining_sectors == 0) {
628 /* request completed */
629 ret = 0;
630 goto done;
633 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
634 n_end = index_in_cluster + acb->remaining_sectors;
635 if (s->crypt_method &&
636 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
637 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
639 ret = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
640 index_in_cluster, n_end, &acb->cur_nr_sectors, &acb->l2meta);
641 if (ret < 0) {
642 goto done;
645 acb->cluster_offset = acb->l2meta.cluster_offset;
647 /* Need to wait for another request? If so, we are done for now. */
648 if (acb->l2meta.nb_clusters == 0 && acb->l2meta.depends_on != NULL) {
649 QLIST_INSERT_HEAD(&acb->l2meta.depends_on->dependent_requests,
650 acb, next_depend);
651 return;
654 assert((acb->cluster_offset & 511) == 0);
656 qemu_iovec_reset(&acb->hd_qiov);
657 qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,
658 acb->cur_nr_sectors * 512);
660 if (s->crypt_method) {
661 if (!acb->cluster_data) {
662 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
663 s->cluster_size);
666 assert(acb->hd_qiov.size <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
667 qemu_iovec_to_buffer(&acb->hd_qiov, acb->cluster_data);
669 qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data,
670 acb->cluster_data, acb->cur_nr_sectors, 1, &s->aes_encrypt_key);
672 qemu_iovec_reset(&acb->hd_qiov);
673 qemu_iovec_add(&acb->hd_qiov, acb->cluster_data,
674 acb->cur_nr_sectors * 512);
677 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
678 acb->hd_aiocb = bdrv_aio_writev(bs->file,
679 (acb->cluster_offset >> 9) + index_in_cluster,
680 &acb->hd_qiov, acb->cur_nr_sectors,
681 qcow2_aio_write_cb, acb);
682 if (acb->hd_aiocb == NULL) {
683 ret = -EIO;
684 goto fail;
687 return;
689 fail:
690 if (acb->l2meta.nb_clusters != 0) {
691 QLIST_REMOVE(&acb->l2meta, next_in_flight);
693 done:
694 acb->common.cb(acb->common.opaque, ret);
695 qemu_iovec_destroy(&acb->hd_qiov);
696 qemu_aio_release(acb);
699 static BlockDriverAIOCB *qcow2_aio_writev(BlockDriverState *bs,
700 int64_t sector_num,
701 QEMUIOVector *qiov, int nb_sectors,
702 BlockDriverCompletionFunc *cb,
703 void *opaque)
705 BDRVQcowState *s = bs->opaque;
706 QCowAIOCB *acb;
708 s->cluster_cache_offset = -1; /* disable compressed cache */
710 acb = qcow2_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
711 if (!acb)
712 return NULL;
714 qcow2_aio_write_cb(acb, 0);
715 return &acb->common;
718 static void qcow2_close(BlockDriverState *bs)
720 BDRVQcowState *s = bs->opaque;
721 qemu_free(s->l1_table);
722 qemu_free(s->l2_cache);
723 qemu_free(s->cluster_cache);
724 qemu_free(s->cluster_data);
725 qcow2_refcount_close(bs);
729 * Updates the variable length parts of the qcow2 header, i.e. the backing file
730 * name and all extensions. qcow2 was not designed to allow such changes, so if
731 * we run out of space (we can only use the first cluster) this function may
732 * fail.
734 * Returns 0 on success, -errno in error cases.
736 static int qcow2_update_ext_header(BlockDriverState *bs,
737 const char *backing_file, const char *backing_fmt)
739 size_t backing_file_len = 0;
740 size_t backing_fmt_len = 0;
741 BDRVQcowState *s = bs->opaque;
742 QCowExtension ext_backing_fmt = {0, 0};
743 int ret;
745 /* Backing file format doesn't make sense without a backing file */
746 if (backing_fmt && !backing_file) {
747 return -EINVAL;
750 /* Prepare the backing file format extension if needed */
751 if (backing_fmt) {
752 ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
753 ext_backing_fmt.magic = cpu_to_be32(QCOW2_EXT_MAGIC_BACKING_FORMAT);
754 backing_fmt_len = ((sizeof(ext_backing_fmt)
755 + strlen(backing_fmt) + 7) & ~7);
758 /* Check if we can fit the new header into the first cluster */
759 if (backing_file) {
760 backing_file_len = strlen(backing_file);
763 size_t header_size = sizeof(QCowHeader) + backing_file_len
764 + backing_fmt_len;
766 if (header_size > s->cluster_size) {
767 return -ENOSPC;
770 /* Rewrite backing file name and qcow2 extensions */
771 size_t ext_size = header_size - sizeof(QCowHeader);
772 uint8_t buf[ext_size];
773 size_t offset = 0;
774 size_t backing_file_offset = 0;
776 if (backing_file) {
777 if (backing_fmt) {
778 int padding = backing_fmt_len -
779 (sizeof(ext_backing_fmt) + strlen(backing_fmt));
781 memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
782 offset += sizeof(ext_backing_fmt);
784 memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
785 offset += strlen(backing_fmt);
787 memset(buf + offset, 0, padding);
788 offset += padding;
791 memcpy(buf + offset, backing_file, backing_file_len);
792 backing_file_offset = sizeof(QCowHeader) + offset;
795 ret = bdrv_pwrite_sync(bs->file, sizeof(QCowHeader), buf, ext_size);
796 if (ret < 0) {
797 goto fail;
800 /* Update header fields */
801 uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
802 uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
804 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, backing_file_offset),
805 &be_backing_file_offset, sizeof(uint64_t));
806 if (ret < 0) {
807 goto fail;
810 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, backing_file_size),
811 &be_backing_file_size, sizeof(uint32_t));
812 if (ret < 0) {
813 goto fail;
816 ret = 0;
817 fail:
818 return ret;
821 static int qcow2_change_backing_file(BlockDriverState *bs,
822 const char *backing_file, const char *backing_fmt)
824 return qcow2_update_ext_header(bs, backing_file, backing_fmt);
827 static int preallocate(BlockDriverState *bs)
829 uint64_t nb_sectors;
830 uint64_t offset;
831 int num;
832 int ret;
833 QCowL2Meta meta;
835 nb_sectors = bdrv_getlength(bs) >> 9;
836 offset = 0;
837 QLIST_INIT(&meta.dependent_requests);
838 meta.cluster_offset = 0;
840 while (nb_sectors) {
841 num = MIN(nb_sectors, INT_MAX >> 9);
842 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
843 if (ret < 0) {
844 return ret;
847 ret = qcow2_alloc_cluster_link_l2(bs, &meta);
848 if (ret < 0) {
849 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
850 return ret;
853 /* There are no dependent requests, but we need to remove our request
854 * from the list of in-flight requests */
855 run_dependent_requests(&meta);
857 /* TODO Preallocate data if requested */
859 nb_sectors -= num;
860 offset += num << 9;
864 * It is expected that the image file is large enough to actually contain
865 * all of the allocated clusters (otherwise we get failing reads after
866 * EOF). Extend the image to the last allocated sector.
868 if (meta.cluster_offset != 0) {
869 uint8_t buf[512];
870 memset(buf, 0, 512);
871 ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
872 if (ret < 0) {
873 return ret;
877 return 0;
880 static int qcow2_create2(const char *filename, int64_t total_size,
881 const char *backing_file, const char *backing_format,
882 int flags, size_t cluster_size, int prealloc,
883 QEMUOptionParameter *options)
885 /* Calulate cluster_bits */
886 int cluster_bits;
887 cluster_bits = ffs(cluster_size) - 1;
888 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
889 (1 << cluster_bits) != cluster_size)
891 error_report(
892 "Cluster size must be a power of two between %d and %dk\n",
893 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
894 return -EINVAL;
898 * Open the image file and write a minimal qcow2 header.
900 * We keep things simple and start with a zero-sized image. We also
901 * do without refcount blocks or a L1 table for now. We'll fix the
902 * inconsistency later.
904 * We do need a refcount table because growing the refcount table means
905 * allocating two new refcount blocks - the seconds of which would be at
906 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
907 * size for any qcow2 image.
909 BlockDriverState* bs;
910 QCowHeader header;
911 uint8_t* refcount_table;
912 int ret;
914 ret = bdrv_create_file(filename, options);
915 if (ret < 0) {
916 return ret;
919 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
920 if (ret < 0) {
921 return ret;
924 /* Write the header */
925 memset(&header, 0, sizeof(header));
926 header.magic = cpu_to_be32(QCOW_MAGIC);
927 header.version = cpu_to_be32(QCOW_VERSION);
928 header.cluster_bits = cpu_to_be32(cluster_bits);
929 header.size = cpu_to_be64(0);
930 header.l1_table_offset = cpu_to_be64(0);
931 header.l1_size = cpu_to_be32(0);
932 header.refcount_table_offset = cpu_to_be64(cluster_size);
933 header.refcount_table_clusters = cpu_to_be32(1);
935 if (flags & BLOCK_FLAG_ENCRYPT) {
936 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
937 } else {
938 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
941 ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
942 if (ret < 0) {
943 goto out;
946 /* Write an empty refcount table */
947 refcount_table = qemu_mallocz(cluster_size);
948 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
949 qemu_free(refcount_table);
951 if (ret < 0) {
952 goto out;
955 bdrv_close(bs);
958 * And now open the image and make it consistent first (i.e. increase the
959 * refcount of the cluster that is occupied by the header and the refcount
960 * table)
962 BlockDriver* drv = bdrv_find_format("qcow2");
963 assert(drv != NULL);
964 ret = bdrv_open(bs, filename, BDRV_O_RDWR | BDRV_O_NO_FLUSH, drv);
965 if (ret < 0) {
966 goto out;
969 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
970 if (ret < 0) {
971 goto out;
973 } else if (ret != 0) {
974 error_report("Huh, first cluster in empty image is already in use?");
975 abort();
978 /* Okay, now that we have a valid image, let's give it the right size */
979 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
980 if (ret < 0) {
981 goto out;
984 /* Want a backing file? There you go.*/
985 if (backing_file) {
986 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
987 if (ret < 0) {
988 goto out;
992 /* And if we're supposed to preallocate metadata, do that now */
993 if (prealloc) {
994 ret = preallocate(bs);
995 if (ret < 0) {
996 goto out;
1000 ret = 0;
1001 out:
1002 bdrv_delete(bs);
1003 return ret;
1006 static int qcow2_create(const char *filename, QEMUOptionParameter *options)
1008 const char *backing_file = NULL;
1009 const char *backing_fmt = NULL;
1010 uint64_t sectors = 0;
1011 int flags = 0;
1012 size_t cluster_size = 65536;
1013 int prealloc = 0;
1015 /* Read out options */
1016 while (options && options->name) {
1017 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1018 sectors = options->value.n / 512;
1019 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1020 backing_file = options->value.s;
1021 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1022 backing_fmt = options->value.s;
1023 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1024 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1025 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1026 if (options->value.n) {
1027 cluster_size = options->value.n;
1029 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1030 if (!options->value.s || !strcmp(options->value.s, "off")) {
1031 prealloc = 0;
1032 } else if (!strcmp(options->value.s, "metadata")) {
1033 prealloc = 1;
1034 } else {
1035 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1036 options->value.s);
1037 return -EINVAL;
1040 options++;
1043 if (backing_file && prealloc) {
1044 fprintf(stderr, "Backing file and preallocation cannot be used at "
1045 "the same time\n");
1046 return -EINVAL;
1049 return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1050 cluster_size, prealloc, options);
1053 static int qcow2_make_empty(BlockDriverState *bs)
1055 #if 0
1056 /* XXX: not correct */
1057 BDRVQcowState *s = bs->opaque;
1058 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1059 int ret;
1061 memset(s->l1_table, 0, l1_length);
1062 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1063 return -1;
1064 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1065 if (ret < 0)
1066 return ret;
1068 l2_cache_reset(bs);
1069 #endif
1070 return 0;
1073 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1075 BDRVQcowState *s = bs->opaque;
1076 int ret, new_l1_size;
1078 if (offset & 511) {
1079 return -EINVAL;
1082 /* cannot proceed if image has snapshots */
1083 if (s->nb_snapshots) {
1084 return -ENOTSUP;
1087 /* shrinking is currently not supported */
1088 if (offset < bs->total_sectors * 512) {
1089 return -ENOTSUP;
1092 new_l1_size = size_to_l1(s, offset);
1093 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1094 if (ret < 0) {
1095 return ret;
1098 /* write updated header.size */
1099 offset = cpu_to_be64(offset);
1100 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1101 &offset, sizeof(uint64_t));
1102 if (ret < 0) {
1103 return ret;
1106 s->l1_vm_state_index = new_l1_size;
1107 return 0;
1110 /* XXX: put compressed sectors first, then all the cluster aligned
1111 tables to avoid losing bytes in alignment */
1112 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1113 const uint8_t *buf, int nb_sectors)
1115 BDRVQcowState *s = bs->opaque;
1116 z_stream strm;
1117 int ret, out_len;
1118 uint8_t *out_buf;
1119 uint64_t cluster_offset;
1121 if (nb_sectors == 0) {
1122 /* align end of file to a sector boundary to ease reading with
1123 sector based I/Os */
1124 cluster_offset = bdrv_getlength(bs->file);
1125 cluster_offset = (cluster_offset + 511) & ~511;
1126 bdrv_truncate(bs->file, cluster_offset);
1127 return 0;
1130 if (nb_sectors != s->cluster_sectors)
1131 return -EINVAL;
1133 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1135 /* best compression, small window, no zlib header */
1136 memset(&strm, 0, sizeof(strm));
1137 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1138 Z_DEFLATED, -12,
1139 9, Z_DEFAULT_STRATEGY);
1140 if (ret != 0) {
1141 qemu_free(out_buf);
1142 return -1;
1145 strm.avail_in = s->cluster_size;
1146 strm.next_in = (uint8_t *)buf;
1147 strm.avail_out = s->cluster_size;
1148 strm.next_out = out_buf;
1150 ret = deflate(&strm, Z_FINISH);
1151 if (ret != Z_STREAM_END && ret != Z_OK) {
1152 qemu_free(out_buf);
1153 deflateEnd(&strm);
1154 return -1;
1156 out_len = strm.next_out - out_buf;
1158 deflateEnd(&strm);
1160 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1161 /* could not compress: write normal cluster */
1162 bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1163 } else {
1164 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1165 sector_num << 9, out_len);
1166 if (!cluster_offset)
1167 return -1;
1168 cluster_offset &= s->cluster_offset_mask;
1169 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1170 if (bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len) != out_len) {
1171 qemu_free(out_buf);
1172 return -1;
1176 qemu_free(out_buf);
1177 return 0;
1180 static int qcow2_flush(BlockDriverState *bs)
1182 return bdrv_flush(bs->file);
1185 static BlockDriverAIOCB *qcow2_aio_flush(BlockDriverState *bs,
1186 BlockDriverCompletionFunc *cb,
1187 void *opaque)
1189 return bdrv_aio_flush(bs->file, cb, opaque);
1192 static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
1194 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1197 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1199 BDRVQcowState *s = bs->opaque;
1200 bdi->cluster_size = s->cluster_size;
1201 bdi->vm_state_offset = qcow2_vm_state_offset(s);
1202 return 0;
1206 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result)
1208 return qcow2_check_refcounts(bs, result);
1211 #if 0
1212 static void dump_refcounts(BlockDriverState *bs)
1214 BDRVQcowState *s = bs->opaque;
1215 int64_t nb_clusters, k, k1, size;
1216 int refcount;
1218 size = bdrv_getlength(bs->file);
1219 nb_clusters = size_to_clusters(s, size);
1220 for(k = 0; k < nb_clusters;) {
1221 k1 = k;
1222 refcount = get_refcount(bs, k);
1223 k++;
1224 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1225 k++;
1226 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1227 k - k1);
1230 #endif
1232 static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1233 int64_t pos, int size)
1235 BDRVQcowState *s = bs->opaque;
1236 int growable = bs->growable;
1237 int ret;
1239 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1240 bs->growable = 1;
1241 ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1242 bs->growable = growable;
1244 return ret;
1247 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1248 int64_t pos, int size)
1250 BDRVQcowState *s = bs->opaque;
1251 int growable = bs->growable;
1252 int ret;
1254 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1255 bs->growable = 1;
1256 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1257 bs->growable = growable;
1259 return ret;
1262 static QEMUOptionParameter qcow2_create_options[] = {
1264 .name = BLOCK_OPT_SIZE,
1265 .type = OPT_SIZE,
1266 .help = "Virtual disk size"
1269 .name = BLOCK_OPT_BACKING_FILE,
1270 .type = OPT_STRING,
1271 .help = "File name of a base image"
1274 .name = BLOCK_OPT_BACKING_FMT,
1275 .type = OPT_STRING,
1276 .help = "Image format of the base image"
1279 .name = BLOCK_OPT_ENCRYPT,
1280 .type = OPT_FLAG,
1281 .help = "Encrypt the image"
1284 .name = BLOCK_OPT_CLUSTER_SIZE,
1285 .type = OPT_SIZE,
1286 .help = "qcow2 cluster size"
1289 .name = BLOCK_OPT_PREALLOC,
1290 .type = OPT_STRING,
1291 .help = "Preallocation mode (allowed values: off, metadata)"
1293 { NULL }
1296 static BlockDriver bdrv_qcow2 = {
1297 .format_name = "qcow2",
1298 .instance_size = sizeof(BDRVQcowState),
1299 .bdrv_probe = qcow2_probe,
1300 .bdrv_open = qcow2_open,
1301 .bdrv_close = qcow2_close,
1302 .bdrv_create = qcow2_create,
1303 .bdrv_flush = qcow2_flush,
1304 .bdrv_is_allocated = qcow2_is_allocated,
1305 .bdrv_set_key = qcow2_set_key,
1306 .bdrv_make_empty = qcow2_make_empty,
1308 .bdrv_aio_readv = qcow2_aio_readv,
1309 .bdrv_aio_writev = qcow2_aio_writev,
1310 .bdrv_aio_flush = qcow2_aio_flush,
1312 .bdrv_truncate = qcow2_truncate,
1313 .bdrv_write_compressed = qcow2_write_compressed,
1315 .bdrv_snapshot_create = qcow2_snapshot_create,
1316 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1317 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1318 .bdrv_snapshot_list = qcow2_snapshot_list,
1319 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
1320 .bdrv_get_info = qcow2_get_info,
1322 .bdrv_save_vmstate = qcow2_save_vmstate,
1323 .bdrv_load_vmstate = qcow2_load_vmstate,
1325 .bdrv_change_backing_file = qcow2_change_backing_file,
1327 .create_options = qcow2_create_options,
1328 .bdrv_check = qcow2_check,
1331 static void bdrv_qcow2_init(void)
1333 bdrv_register(&bdrv_qcow2);
1336 block_init(bdrv_qcow2_init);