Fix docs for block stats monitor command
[qemu/mdroth.git] / block / qcow2.c
blob0ce71507e921ee50e09f0f4048dad31fcacbef42
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"
32 Differences with QCOW:
34 - Support for multiple incremental snapshots.
35 - Memory management by reference counts.
36 - Clusters which have a reference count of one have the bit
37 QCOW_OFLAG_COPIED to optimize write performance.
38 - Size of compressed clusters is stored in sectors to reduce bit usage
39 in the cluster offsets.
40 - Support for storing additional data (such as the VM state) in the
41 snapshots.
42 - If a backing store is used, the cluster size is not constrained
43 (could be backported to QCOW).
44 - L2 tables have always a size of one cluster.
48 typedef struct {
49 uint32_t magic;
50 uint32_t len;
51 } QCowExtension;
52 #define QCOW_EXT_MAGIC_END 0
53 #define QCOW_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
55 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
57 const QCowHeader *cow_header = (const void *)buf;
59 if (buf_size >= sizeof(QCowHeader) &&
60 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
61 be32_to_cpu(cow_header->version) == QCOW_VERSION)
62 return 100;
63 else
64 return 0;
68 /*
69 * read qcow2 extension and fill bs
70 * start reading from start_offset
71 * finish reading upon magic of value 0 or when end_offset reached
72 * unknown magic is skipped (future extension this version knows nothing about)
73 * return 0 upon success, non-0 otherwise
75 static int qcow_read_extensions(BlockDriverState *bs, uint64_t start_offset,
76 uint64_t end_offset)
78 QCowExtension ext;
79 uint64_t offset;
81 #ifdef DEBUG_EXT
82 printf("qcow_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
83 #endif
84 offset = start_offset;
85 while (offset < end_offset) {
87 #ifdef DEBUG_EXT
88 /* Sanity check */
89 if (offset > s->cluster_size)
90 printf("qcow_handle_extension: suspicious offset %lu\n", offset);
92 printf("attemting to read extended header in offset %lu\n", offset);
93 #endif
95 if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
96 fprintf(stderr, "qcow_handle_extension: ERROR: pread fail from offset %llu\n",
97 (unsigned long long)offset);
98 return 1;
100 be32_to_cpus(&ext.magic);
101 be32_to_cpus(&ext.len);
102 offset += sizeof(ext);
103 #ifdef DEBUG_EXT
104 printf("ext.magic = 0x%x\n", ext.magic);
105 #endif
106 switch (ext.magic) {
107 case QCOW_EXT_MAGIC_END:
108 return 0;
110 case QCOW_EXT_MAGIC_BACKING_FORMAT:
111 if (ext.len >= sizeof(bs->backing_format)) {
112 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
113 " (>=%zu)\n",
114 ext.len, sizeof(bs->backing_format));
115 return 2;
117 if (bdrv_pread(bs->file, offset , bs->backing_format,
118 ext.len) != ext.len)
119 return 3;
120 bs->backing_format[ext.len] = '\0';
121 #ifdef DEBUG_EXT
122 printf("Qcow2: Got format extension %s\n", bs->backing_format);
123 #endif
124 offset = ((offset + ext.len + 7) & ~7);
125 break;
127 default:
128 /* unknown magic -- just skip it */
129 offset = ((offset + ext.len + 7) & ~7);
130 break;
134 return 0;
138 static int qcow_open(BlockDriverState *bs, int flags)
140 BDRVQcowState *s = bs->opaque;
141 int len, i;
142 QCowHeader header;
143 uint64_t ext_end;
145 if (bdrv_pread(bs->file, 0, &header, sizeof(header)) != sizeof(header))
146 goto fail;
147 be32_to_cpus(&header.magic);
148 be32_to_cpus(&header.version);
149 be64_to_cpus(&header.backing_file_offset);
150 be32_to_cpus(&header.backing_file_size);
151 be64_to_cpus(&header.size);
152 be32_to_cpus(&header.cluster_bits);
153 be32_to_cpus(&header.crypt_method);
154 be64_to_cpus(&header.l1_table_offset);
155 be32_to_cpus(&header.l1_size);
156 be64_to_cpus(&header.refcount_table_offset);
157 be32_to_cpus(&header.refcount_table_clusters);
158 be64_to_cpus(&header.snapshots_offset);
159 be32_to_cpus(&header.nb_snapshots);
161 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
162 goto fail;
163 if (header.cluster_bits < MIN_CLUSTER_BITS ||
164 header.cluster_bits > MAX_CLUSTER_BITS)
165 goto fail;
166 if (header.crypt_method > QCOW_CRYPT_AES)
167 goto fail;
168 s->crypt_method_header = header.crypt_method;
169 if (s->crypt_method_header)
170 bs->encrypted = 1;
171 s->cluster_bits = header.cluster_bits;
172 s->cluster_size = 1 << s->cluster_bits;
173 s->cluster_sectors = 1 << (s->cluster_bits - 9);
174 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
175 s->l2_size = 1 << s->l2_bits;
176 bs->total_sectors = header.size / 512;
177 s->csize_shift = (62 - (s->cluster_bits - 8));
178 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
179 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
180 s->refcount_table_offset = header.refcount_table_offset;
181 s->refcount_table_size =
182 header.refcount_table_clusters << (s->cluster_bits - 3);
184 s->snapshots_offset = header.snapshots_offset;
185 s->nb_snapshots = header.nb_snapshots;
187 /* read the level 1 table */
188 s->l1_size = header.l1_size;
189 s->l1_vm_state_index = size_to_l1(s, header.size);
190 /* the L1 table must contain at least enough entries to put
191 header.size bytes */
192 if (s->l1_size < s->l1_vm_state_index)
193 goto fail;
194 s->l1_table_offset = header.l1_table_offset;
195 if (s->l1_size > 0) {
196 s->l1_table = qemu_mallocz(
197 align_offset(s->l1_size * sizeof(uint64_t), 512));
198 if (bdrv_pread(bs->file, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
199 s->l1_size * sizeof(uint64_t))
200 goto fail;
201 for(i = 0;i < s->l1_size; i++) {
202 be64_to_cpus(&s->l1_table[i]);
205 /* alloc L2 cache */
206 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
207 s->cluster_cache = qemu_malloc(s->cluster_size);
208 /* one more sector for decompressed data alignment */
209 s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
210 + 512);
211 s->cluster_cache_offset = -1;
213 if (qcow2_refcount_init(bs) < 0)
214 goto fail;
216 QLIST_INIT(&s->cluster_allocs);
218 /* read qcow2 extensions */
219 if (header.backing_file_offset)
220 ext_end = header.backing_file_offset;
221 else
222 ext_end = s->cluster_size;
223 if (qcow_read_extensions(bs, sizeof(header), ext_end))
224 goto fail;
226 /* read the backing file name */
227 if (header.backing_file_offset != 0) {
228 len = header.backing_file_size;
229 if (len > 1023)
230 len = 1023;
231 if (bdrv_pread(bs->file, header.backing_file_offset, bs->backing_file, len) != len)
232 goto fail;
233 bs->backing_file[len] = '\0';
235 if (qcow2_read_snapshots(bs) < 0)
236 goto fail;
238 #ifdef DEBUG_ALLOC
239 qcow2_check_refcounts(bs);
240 #endif
241 return 0;
243 fail:
244 qcow2_free_snapshots(bs);
245 qcow2_refcount_close(bs);
246 qemu_free(s->l1_table);
247 qemu_free(s->l2_cache);
248 qemu_free(s->cluster_cache);
249 qemu_free(s->cluster_data);
250 return -1;
253 static int qcow_set_key(BlockDriverState *bs, const char *key)
255 BDRVQcowState *s = bs->opaque;
256 uint8_t keybuf[16];
257 int len, i;
259 memset(keybuf, 0, 16);
260 len = strlen(key);
261 if (len > 16)
262 len = 16;
263 /* XXX: we could compress the chars to 7 bits to increase
264 entropy */
265 for(i = 0;i < len;i++) {
266 keybuf[i] = key[i];
268 s->crypt_method = s->crypt_method_header;
270 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
271 return -1;
272 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
273 return -1;
274 #if 0
275 /* test */
277 uint8_t in[16];
278 uint8_t out[16];
279 uint8_t tmp[16];
280 for(i=0;i<16;i++)
281 in[i] = i;
282 AES_encrypt(in, tmp, &s->aes_encrypt_key);
283 AES_decrypt(tmp, out, &s->aes_decrypt_key);
284 for(i = 0; i < 16; i++)
285 printf(" %02x", tmp[i]);
286 printf("\n");
287 for(i = 0; i < 16; i++)
288 printf(" %02x", out[i]);
289 printf("\n");
291 #endif
292 return 0;
295 static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
296 int nb_sectors, int *pnum)
298 uint64_t cluster_offset;
300 *pnum = nb_sectors;
301 cluster_offset = qcow2_get_cluster_offset(bs, sector_num << 9, pnum);
303 return (cluster_offset != 0);
306 /* handle reading after the end of the backing file */
307 int qcow2_backing_read1(BlockDriverState *bs,
308 int64_t sector_num, uint8_t *buf, int nb_sectors)
310 int n1;
311 if ((sector_num + nb_sectors) <= bs->total_sectors)
312 return nb_sectors;
313 if (sector_num >= bs->total_sectors)
314 n1 = 0;
315 else
316 n1 = bs->total_sectors - sector_num;
317 memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
318 return n1;
321 typedef struct QCowAIOCB {
322 BlockDriverAIOCB common;
323 int64_t sector_num;
324 QEMUIOVector *qiov;
325 uint8_t *buf;
326 void *orig_buf;
327 int remaining_sectors;
328 int cur_nr_sectors; /* number of sectors in current iteration */
329 uint64_t cluster_offset;
330 uint8_t *cluster_data;
331 BlockDriverAIOCB *hd_aiocb;
332 struct iovec hd_iov;
333 QEMUIOVector hd_qiov;
334 QEMUBH *bh;
335 QCowL2Meta l2meta;
336 QLIST_ENTRY(QCowAIOCB) next_depend;
337 } QCowAIOCB;
339 static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
341 QCowAIOCB *acb = container_of(blockacb, QCowAIOCB, common);
342 if (acb->hd_aiocb)
343 bdrv_aio_cancel(acb->hd_aiocb);
344 qemu_aio_release(acb);
347 static AIOPool qcow_aio_pool = {
348 .aiocb_size = sizeof(QCowAIOCB),
349 .cancel = qcow_aio_cancel,
352 static void qcow_aio_read_cb(void *opaque, int ret);
353 static void qcow_aio_read_bh(void *opaque)
355 QCowAIOCB *acb = opaque;
356 qemu_bh_delete(acb->bh);
357 acb->bh = NULL;
358 qcow_aio_read_cb(opaque, 0);
361 static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
363 if (acb->bh)
364 return -EIO;
366 acb->bh = qemu_bh_new(cb, acb);
367 if (!acb->bh)
368 return -EIO;
370 qemu_bh_schedule(acb->bh);
372 return 0;
375 static void qcow_aio_read_cb(void *opaque, int ret)
377 QCowAIOCB *acb = opaque;
378 BlockDriverState *bs = acb->common.bs;
379 BDRVQcowState *s = bs->opaque;
380 int index_in_cluster, n1;
382 acb->hd_aiocb = NULL;
383 if (ret < 0)
384 goto done;
386 /* post process the read buffer */
387 if (!acb->cluster_offset) {
388 /* nothing to do */
389 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
390 /* nothing to do */
391 } else {
392 if (s->crypt_method) {
393 qcow2_encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
394 acb->cur_nr_sectors, 0,
395 &s->aes_decrypt_key);
399 acb->remaining_sectors -= acb->cur_nr_sectors;
400 acb->sector_num += acb->cur_nr_sectors;
401 acb->buf += acb->cur_nr_sectors * 512;
403 if (acb->remaining_sectors == 0) {
404 /* request completed */
405 ret = 0;
406 goto done;
409 /* prepare next AIO request */
410 acb->cur_nr_sectors = acb->remaining_sectors;
411 acb->cluster_offset = qcow2_get_cluster_offset(bs, acb->sector_num << 9,
412 &acb->cur_nr_sectors);
413 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
415 if (!acb->cluster_offset) {
416 if (bs->backing_hd) {
417 /* read from the base image */
418 n1 = qcow2_backing_read1(bs->backing_hd, acb->sector_num,
419 acb->buf, acb->cur_nr_sectors);
420 if (n1 > 0) {
421 acb->hd_iov.iov_base = (void *)acb->buf;
422 acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
423 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
424 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
425 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
426 &acb->hd_qiov, acb->cur_nr_sectors,
427 qcow_aio_read_cb, acb);
428 if (acb->hd_aiocb == NULL)
429 goto done;
430 } else {
431 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
432 if (ret < 0)
433 goto done;
435 } else {
436 /* Note: in this case, no need to wait */
437 memset(acb->buf, 0, 512 * acb->cur_nr_sectors);
438 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
439 if (ret < 0)
440 goto done;
442 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
443 /* add AIO support for compressed blocks ? */
444 if (qcow2_decompress_cluster(bs, acb->cluster_offset) < 0)
445 goto done;
446 memcpy(acb->buf, s->cluster_cache + index_in_cluster * 512,
447 512 * acb->cur_nr_sectors);
448 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
449 if (ret < 0)
450 goto done;
451 } else {
452 if ((acb->cluster_offset & 511) != 0) {
453 ret = -EIO;
454 goto done;
457 acb->hd_iov.iov_base = (void *)acb->buf;
458 acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
459 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
460 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
461 acb->hd_aiocb = bdrv_aio_readv(bs->file,
462 (acb->cluster_offset >> 9) + index_in_cluster,
463 &acb->hd_qiov, acb->cur_nr_sectors,
464 qcow_aio_read_cb, acb);
465 if (acb->hd_aiocb == NULL) {
466 ret = -EIO;
467 goto done;
471 return;
472 done:
473 if (acb->qiov->niov > 1) {
474 qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
475 qemu_vfree(acb->orig_buf);
477 acb->common.cb(acb->common.opaque, ret);
478 qemu_aio_release(acb);
481 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
482 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
483 BlockDriverCompletionFunc *cb, void *opaque, int is_write)
485 QCowAIOCB *acb;
487 acb = qemu_aio_get(&qcow_aio_pool, bs, cb, opaque);
488 if (!acb)
489 return NULL;
490 acb->hd_aiocb = NULL;
491 acb->sector_num = sector_num;
492 acb->qiov = qiov;
493 if (qiov->niov > 1) {
494 acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
495 if (is_write)
496 qemu_iovec_to_buffer(qiov, acb->buf);
497 } else {
498 acb->buf = (uint8_t *)qiov->iov->iov_base;
500 acb->remaining_sectors = nb_sectors;
501 acb->cur_nr_sectors = 0;
502 acb->cluster_offset = 0;
503 acb->l2meta.nb_clusters = 0;
504 QLIST_INIT(&acb->l2meta.dependent_requests);
505 return acb;
508 static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
509 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
510 BlockDriverCompletionFunc *cb, void *opaque)
512 QCowAIOCB *acb;
514 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
515 if (!acb)
516 return NULL;
518 qcow_aio_read_cb(acb, 0);
519 return &acb->common;
522 static void qcow_aio_write_cb(void *opaque, int ret);
524 static void run_dependent_requests(QCowL2Meta *m)
526 QCowAIOCB *req;
527 QCowAIOCB *next;
529 /* Take the request off the list of running requests */
530 if (m->nb_clusters != 0) {
531 QLIST_REMOVE(m, next_in_flight);
534 /* Restart all dependent requests */
535 QLIST_FOREACH_SAFE(req, &m->dependent_requests, next_depend, next) {
536 qcow_aio_write_cb(req, 0);
539 /* Empty the list for the next part of the request */
540 QLIST_INIT(&m->dependent_requests);
543 static void qcow_aio_write_cb(void *opaque, int ret)
545 QCowAIOCB *acb = opaque;
546 BlockDriverState *bs = acb->common.bs;
547 BDRVQcowState *s = bs->opaque;
548 int index_in_cluster;
549 const uint8_t *src_buf;
550 int n_end;
552 acb->hd_aiocb = NULL;
554 if (ret >= 0) {
555 ret = qcow2_alloc_cluster_link_l2(bs, &acb->l2meta);
558 run_dependent_requests(&acb->l2meta);
560 if (ret < 0)
561 goto done;
563 acb->remaining_sectors -= acb->cur_nr_sectors;
564 acb->sector_num += acb->cur_nr_sectors;
565 acb->buf += acb->cur_nr_sectors * 512;
567 if (acb->remaining_sectors == 0) {
568 /* request completed */
569 ret = 0;
570 goto done;
573 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
574 n_end = index_in_cluster + acb->remaining_sectors;
575 if (s->crypt_method &&
576 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
577 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
579 ret = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
580 index_in_cluster, n_end, &acb->cur_nr_sectors, &acb->l2meta);
581 if (ret < 0) {
582 goto done;
585 acb->cluster_offset = acb->l2meta.cluster_offset;
587 /* Need to wait for another request? If so, we are done for now. */
588 if (acb->l2meta.nb_clusters == 0 && acb->l2meta.depends_on != NULL) {
589 QLIST_INSERT_HEAD(&acb->l2meta.depends_on->dependent_requests,
590 acb, next_depend);
591 return;
594 assert((acb->cluster_offset & 511) == 0);
596 if (s->crypt_method) {
597 if (!acb->cluster_data) {
598 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
599 s->cluster_size);
601 qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
602 acb->cur_nr_sectors, 1, &s->aes_encrypt_key);
603 src_buf = acb->cluster_data;
604 } else {
605 src_buf = acb->buf;
607 acb->hd_iov.iov_base = (void *)src_buf;
608 acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
609 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
610 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
611 acb->hd_aiocb = bdrv_aio_writev(bs->file,
612 (acb->cluster_offset >> 9) + index_in_cluster,
613 &acb->hd_qiov, acb->cur_nr_sectors,
614 qcow_aio_write_cb, acb);
615 if (acb->hd_aiocb == NULL) {
616 ret = -EIO;
617 goto fail;
620 return;
622 fail:
623 if (acb->l2meta.nb_clusters != 0) {
624 QLIST_REMOVE(&acb->l2meta, next_in_flight);
626 done:
627 if (acb->qiov->niov > 1)
628 qemu_vfree(acb->orig_buf);
629 acb->common.cb(acb->common.opaque, ret);
630 qemu_aio_release(acb);
633 static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
634 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
635 BlockDriverCompletionFunc *cb, void *opaque)
637 BDRVQcowState *s = bs->opaque;
638 QCowAIOCB *acb;
640 s->cluster_cache_offset = -1; /* disable compressed cache */
642 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
643 if (!acb)
644 return NULL;
646 qcow_aio_write_cb(acb, 0);
647 return &acb->common;
650 static void qcow_close(BlockDriverState *bs)
652 BDRVQcowState *s = bs->opaque;
653 qemu_free(s->l1_table);
654 qemu_free(s->l2_cache);
655 qemu_free(s->cluster_cache);
656 qemu_free(s->cluster_data);
657 qcow2_refcount_close(bs);
661 * Updates the variable length parts of the qcow2 header, i.e. the backing file
662 * name and all extensions. qcow2 was not designed to allow such changes, so if
663 * we run out of space (we can only use the first cluster) this function may
664 * fail.
666 * Returns 0 on success, -errno in error cases.
668 static int qcow2_update_ext_header(BlockDriverState *bs,
669 const char *backing_file, const char *backing_fmt)
671 size_t backing_file_len = 0;
672 size_t backing_fmt_len = 0;
673 BDRVQcowState *s = bs->opaque;
674 QCowExtension ext_backing_fmt = {0, 0};
675 int ret;
677 /* Backing file format doesn't make sense without a backing file */
678 if (backing_fmt && !backing_file) {
679 return -EINVAL;
682 /* Prepare the backing file format extension if needed */
683 if (backing_fmt) {
684 ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
685 ext_backing_fmt.magic = cpu_to_be32(QCOW_EXT_MAGIC_BACKING_FORMAT);
686 backing_fmt_len = ((sizeof(ext_backing_fmt)
687 + strlen(backing_fmt) + 7) & ~7);
690 /* Check if we can fit the new header into the first cluster */
691 if (backing_file) {
692 backing_file_len = strlen(backing_file);
695 size_t header_size = sizeof(QCowHeader) + backing_file_len
696 + backing_fmt_len;
698 if (header_size > s->cluster_size) {
699 return -ENOSPC;
702 /* Rewrite backing file name and qcow2 extensions */
703 size_t ext_size = header_size - sizeof(QCowHeader);
704 uint8_t buf[ext_size];
705 size_t offset = 0;
706 size_t backing_file_offset = 0;
708 if (backing_file) {
709 if (backing_fmt) {
710 int padding = backing_fmt_len -
711 (sizeof(ext_backing_fmt) + strlen(backing_fmt));
713 memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
714 offset += sizeof(ext_backing_fmt);
716 memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
717 offset += strlen(backing_fmt);
719 memset(buf + offset, 0, padding);
720 offset += padding;
723 memcpy(buf + offset, backing_file, backing_file_len);
724 backing_file_offset = sizeof(QCowHeader) + offset;
727 ret = bdrv_pwrite(bs->file, sizeof(QCowHeader), buf, ext_size);
728 if (ret < 0) {
729 goto fail;
732 /* Update header fields */
733 uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
734 uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
736 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, backing_file_offset),
737 &be_backing_file_offset, sizeof(uint64_t));
738 if (ret < 0) {
739 goto fail;
742 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, backing_file_size),
743 &be_backing_file_size, sizeof(uint32_t));
744 if (ret < 0) {
745 goto fail;
748 ret = 0;
749 fail:
750 return ret;
753 static int qcow2_change_backing_file(BlockDriverState *bs,
754 const char *backing_file, const char *backing_fmt)
756 return qcow2_update_ext_header(bs, backing_file, backing_fmt);
759 static int get_bits_from_size(size_t size)
761 int res = 0;
763 if (size == 0) {
764 return -1;
767 while (size != 1) {
768 /* Not a power of two */
769 if (size & 1) {
770 return -1;
773 size >>= 1;
774 res++;
777 return res;
781 static int preallocate(BlockDriverState *bs)
783 uint64_t nb_sectors;
784 uint64_t offset;
785 int num;
786 int ret;
787 QCowL2Meta meta;
789 nb_sectors = bdrv_getlength(bs) >> 9;
790 offset = 0;
791 QLIST_INIT(&meta.dependent_requests);
792 meta.cluster_offset = 0;
794 while (nb_sectors) {
795 num = MIN(nb_sectors, INT_MAX >> 9);
796 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
798 if (ret < 0) {
799 return -1;
802 if (qcow2_alloc_cluster_link_l2(bs, &meta) < 0) {
803 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
804 return -1;
807 /* There are no dependent requests, but we need to remove our request
808 * from the list of in-flight requests */
809 run_dependent_requests(&meta);
811 /* TODO Preallocate data if requested */
813 nb_sectors -= num;
814 offset += num << 9;
818 * It is expected that the image file is large enough to actually contain
819 * all of the allocated clusters (otherwise we get failing reads after
820 * EOF). Extend the image to the last allocated sector.
822 if (meta.cluster_offset != 0) {
823 uint8_t buf[512];
824 memset(buf, 0, 512);
825 bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
828 return 0;
831 static int qcow_create2(const char *filename, int64_t total_size,
832 const char *backing_file, const char *backing_format,
833 int flags, size_t cluster_size, int prealloc)
836 int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
837 int ref_clusters, reftable_clusters, backing_format_len = 0;
838 int rounded_ext_bf_len = 0;
839 QCowHeader header;
840 uint64_t tmp, offset;
841 uint64_t old_ref_clusters;
842 QCowCreateState s1, *s = &s1;
843 QCowExtension ext_bf = {0, 0};
844 int ret;
846 memset(s, 0, sizeof(*s));
848 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
849 if (fd < 0)
850 return -errno;
851 memset(&header, 0, sizeof(header));
852 header.magic = cpu_to_be32(QCOW_MAGIC);
853 header.version = cpu_to_be32(QCOW_VERSION);
854 header.size = cpu_to_be64(total_size * 512);
855 header_size = sizeof(header);
856 backing_filename_len = 0;
857 if (backing_file) {
858 if (backing_format) {
859 ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
860 backing_format_len = strlen(backing_format);
861 ext_bf.len = backing_format_len;
862 rounded_ext_bf_len = (sizeof(ext_bf) + ext_bf.len + 7) & ~7;
863 header_size += rounded_ext_bf_len;
865 header.backing_file_offset = cpu_to_be64(header_size);
866 backing_filename_len = strlen(backing_file);
867 header.backing_file_size = cpu_to_be32(backing_filename_len);
868 header_size += backing_filename_len;
871 /* Cluster size */
872 s->cluster_bits = get_bits_from_size(cluster_size);
873 if (s->cluster_bits < MIN_CLUSTER_BITS ||
874 s->cluster_bits > MAX_CLUSTER_BITS)
876 fprintf(stderr, "Cluster size must be a power of two between "
877 "%d and %dk\n",
878 1 << MIN_CLUSTER_BITS,
879 1 << (MAX_CLUSTER_BITS - 10));
880 return -EINVAL;
882 s->cluster_size = 1 << s->cluster_bits;
884 header.cluster_bits = cpu_to_be32(s->cluster_bits);
885 header_size = (header_size + 7) & ~7;
886 if (flags & BLOCK_FLAG_ENCRYPT) {
887 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
888 } else {
889 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
891 l2_bits = s->cluster_bits - 3;
892 shift = s->cluster_bits + l2_bits;
893 l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
894 offset = align_offset(header_size, s->cluster_size);
895 s->l1_table_offset = offset;
896 header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
897 header.l1_size = cpu_to_be32(l1_size);
898 offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
900 /* count how many refcount blocks needed */
902 #define NUM_CLUSTERS(bytes) \
903 (((bytes) + (s->cluster_size) - 1) / (s->cluster_size))
905 ref_clusters = NUM_CLUSTERS(NUM_CLUSTERS(offset) * sizeof(uint16_t));
907 do {
908 uint64_t image_clusters;
909 old_ref_clusters = ref_clusters;
911 /* Number of clusters used for the refcount table */
912 reftable_clusters = NUM_CLUSTERS(ref_clusters * sizeof(uint64_t));
914 /* Number of clusters that the whole image will have */
915 image_clusters = NUM_CLUSTERS(offset) + ref_clusters
916 + reftable_clusters;
918 /* Number of refcount blocks needed for the image */
919 ref_clusters = NUM_CLUSTERS(image_clusters * sizeof(uint16_t));
921 } while (ref_clusters != old_ref_clusters);
923 s->refcount_table = qemu_mallocz(reftable_clusters * s->cluster_size);
925 s->refcount_table_offset = offset;
926 header.refcount_table_offset = cpu_to_be64(offset);
927 header.refcount_table_clusters = cpu_to_be32(reftable_clusters);
928 offset += (reftable_clusters * s->cluster_size);
929 s->refcount_block_offset = offset;
931 for (i=0; i < ref_clusters; i++) {
932 s->refcount_table[i] = cpu_to_be64(offset);
933 offset += s->cluster_size;
936 s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
938 /* update refcounts */
939 qcow2_create_refcount_update(s, 0, header_size);
940 qcow2_create_refcount_update(s, s->l1_table_offset,
941 l1_size * sizeof(uint64_t));
942 qcow2_create_refcount_update(s, s->refcount_table_offset,
943 reftable_clusters * s->cluster_size);
944 qcow2_create_refcount_update(s, s->refcount_block_offset,
945 ref_clusters * s->cluster_size);
947 /* write all the data */
948 ret = qemu_write_full(fd, &header, sizeof(header));
949 if (ret != sizeof(header)) {
950 ret = -errno;
951 goto exit;
953 if (backing_file) {
954 if (backing_format_len) {
955 char zero[16];
956 int padding = rounded_ext_bf_len - (ext_bf.len + sizeof(ext_bf));
958 memset(zero, 0, sizeof(zero));
959 cpu_to_be32s(&ext_bf.magic);
960 cpu_to_be32s(&ext_bf.len);
961 ret = qemu_write_full(fd, &ext_bf, sizeof(ext_bf));
962 if (ret != sizeof(ext_bf)) {
963 ret = -errno;
964 goto exit;
966 ret = qemu_write_full(fd, backing_format, backing_format_len);
967 if (ret != backing_format_len) {
968 ret = -errno;
969 goto exit;
971 if (padding > 0) {
972 ret = qemu_write_full(fd, zero, padding);
973 if (ret != padding) {
974 ret = -errno;
975 goto exit;
979 ret = qemu_write_full(fd, backing_file, backing_filename_len);
980 if (ret != backing_filename_len) {
981 ret = -errno;
982 goto exit;
985 lseek(fd, s->l1_table_offset, SEEK_SET);
986 tmp = 0;
987 for(i = 0;i < l1_size; i++) {
988 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
989 if (ret != sizeof(tmp)) {
990 ret = -errno;
991 goto exit;
994 lseek(fd, s->refcount_table_offset, SEEK_SET);
995 ret = qemu_write_full(fd, s->refcount_table,
996 reftable_clusters * s->cluster_size);
997 if (ret != reftable_clusters * s->cluster_size) {
998 ret = -errno;
999 goto exit;
1002 lseek(fd, s->refcount_block_offset, SEEK_SET);
1003 ret = qemu_write_full(fd, s->refcount_block,
1004 ref_clusters * s->cluster_size);
1005 if (ret != ref_clusters * s->cluster_size) {
1006 ret = -errno;
1007 goto exit;
1010 ret = 0;
1011 exit:
1012 qemu_free(s->refcount_table);
1013 qemu_free(s->refcount_block);
1014 close(fd);
1016 /* Preallocate metadata */
1017 if (ret == 0 && prealloc) {
1018 BlockDriverState *bs;
1019 BlockDriver *drv = bdrv_find_format("qcow2");
1020 bs = bdrv_new("");
1021 bdrv_open(bs, filename, BDRV_O_CACHE_WB | BDRV_O_RDWR, drv);
1022 preallocate(bs);
1023 bdrv_close(bs);
1026 return ret;
1029 static int qcow_create(const char *filename, QEMUOptionParameter *options)
1031 const char *backing_file = NULL;
1032 const char *backing_fmt = NULL;
1033 uint64_t sectors = 0;
1034 int flags = 0;
1035 size_t cluster_size = 65536;
1036 int prealloc = 0;
1038 /* Read out options */
1039 while (options && options->name) {
1040 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1041 sectors = options->value.n / 512;
1042 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1043 backing_file = options->value.s;
1044 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1045 backing_fmt = options->value.s;
1046 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1047 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1048 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1049 if (options->value.n) {
1050 cluster_size = options->value.n;
1052 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1053 if (!options->value.s || !strcmp(options->value.s, "off")) {
1054 prealloc = 0;
1055 } else if (!strcmp(options->value.s, "metadata")) {
1056 prealloc = 1;
1057 } else {
1058 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1059 options->value.s);
1060 return -EINVAL;
1063 options++;
1066 if (backing_file && prealloc) {
1067 fprintf(stderr, "Backing file and preallocation cannot be used at "
1068 "the same time\n");
1069 return -EINVAL;
1072 return qcow_create2(filename, sectors, backing_file, backing_fmt, flags,
1073 cluster_size, prealloc);
1076 static int qcow_make_empty(BlockDriverState *bs)
1078 #if 0
1079 /* XXX: not correct */
1080 BDRVQcowState *s = bs->opaque;
1081 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1082 int ret;
1084 memset(s->l1_table, 0, l1_length);
1085 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1086 return -1;
1087 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1088 if (ret < 0)
1089 return ret;
1091 l2_cache_reset(bs);
1092 #endif
1093 return 0;
1096 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1098 BDRVQcowState *s = bs->opaque;
1099 int ret, new_l1_size;
1101 if (offset & 511) {
1102 return -EINVAL;
1105 /* cannot proceed if image has snapshots */
1106 if (s->nb_snapshots) {
1107 return -ENOTSUP;
1110 /* shrinking is currently not supported */
1111 if (offset < bs->total_sectors * 512) {
1112 return -ENOTSUP;
1115 new_l1_size = size_to_l1(s, offset);
1116 ret = qcow2_grow_l1_table(bs, new_l1_size);
1117 if (ret < 0) {
1118 return ret;
1121 /* write updated header.size */
1122 offset = cpu_to_be64(offset);
1123 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, size),
1124 &offset, sizeof(uint64_t));
1125 if (ret < 0) {
1126 return ret;
1129 s->l1_vm_state_index = new_l1_size;
1130 return 0;
1133 /* XXX: put compressed sectors first, then all the cluster aligned
1134 tables to avoid losing bytes in alignment */
1135 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1136 const uint8_t *buf, int nb_sectors)
1138 BDRVQcowState *s = bs->opaque;
1139 z_stream strm;
1140 int ret, out_len;
1141 uint8_t *out_buf;
1142 uint64_t cluster_offset;
1144 if (nb_sectors == 0) {
1145 /* align end of file to a sector boundary to ease reading with
1146 sector based I/Os */
1147 cluster_offset = bdrv_getlength(bs->file);
1148 cluster_offset = (cluster_offset + 511) & ~511;
1149 bdrv_truncate(bs->file, cluster_offset);
1150 return 0;
1153 if (nb_sectors != s->cluster_sectors)
1154 return -EINVAL;
1156 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1158 /* best compression, small window, no zlib header */
1159 memset(&strm, 0, sizeof(strm));
1160 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1161 Z_DEFLATED, -12,
1162 9, Z_DEFAULT_STRATEGY);
1163 if (ret != 0) {
1164 qemu_free(out_buf);
1165 return -1;
1168 strm.avail_in = s->cluster_size;
1169 strm.next_in = (uint8_t *)buf;
1170 strm.avail_out = s->cluster_size;
1171 strm.next_out = out_buf;
1173 ret = deflate(&strm, Z_FINISH);
1174 if (ret != Z_STREAM_END && ret != Z_OK) {
1175 qemu_free(out_buf);
1176 deflateEnd(&strm);
1177 return -1;
1179 out_len = strm.next_out - out_buf;
1181 deflateEnd(&strm);
1183 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1184 /* could not compress: write normal cluster */
1185 bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1186 } else {
1187 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1188 sector_num << 9, out_len);
1189 if (!cluster_offset)
1190 return -1;
1191 cluster_offset &= s->cluster_offset_mask;
1192 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1193 if (bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len) != out_len) {
1194 qemu_free(out_buf);
1195 return -1;
1199 qemu_free(out_buf);
1200 return 0;
1203 static void qcow_flush(BlockDriverState *bs)
1205 bdrv_flush(bs->file);
1208 static BlockDriverAIOCB *qcow_aio_flush(BlockDriverState *bs,
1209 BlockDriverCompletionFunc *cb, void *opaque)
1211 return bdrv_aio_flush(bs->file, cb, opaque);
1214 static int64_t qcow_vm_state_offset(BDRVQcowState *s)
1216 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1219 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1221 BDRVQcowState *s = bs->opaque;
1222 bdi->cluster_size = s->cluster_size;
1223 bdi->vm_state_offset = qcow_vm_state_offset(s);
1224 return 0;
1228 static int qcow_check(BlockDriverState *bs)
1230 return qcow2_check_refcounts(bs);
1233 #if 0
1234 static void dump_refcounts(BlockDriverState *bs)
1236 BDRVQcowState *s = bs->opaque;
1237 int64_t nb_clusters, k, k1, size;
1238 int refcount;
1240 size = bdrv_getlength(bs->file);
1241 nb_clusters = size_to_clusters(s, size);
1242 for(k = 0; k < nb_clusters;) {
1243 k1 = k;
1244 refcount = get_refcount(bs, k);
1245 k++;
1246 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1247 k++;
1248 printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
1251 #endif
1253 static int qcow_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1254 int64_t pos, int size)
1256 BDRVQcowState *s = bs->opaque;
1257 int growable = bs->growable;
1258 int ret;
1260 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1261 bs->growable = 1;
1262 ret = bdrv_pwrite(bs, qcow_vm_state_offset(s) + pos, buf, size);
1263 bs->growable = growable;
1265 return ret;
1268 static int qcow_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1269 int64_t pos, int size)
1271 BDRVQcowState *s = bs->opaque;
1272 int growable = bs->growable;
1273 int ret;
1275 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1276 bs->growable = 1;
1277 ret = bdrv_pread(bs, qcow_vm_state_offset(s) + pos, buf, size);
1278 bs->growable = growable;
1280 return ret;
1283 static QEMUOptionParameter qcow_create_options[] = {
1285 .name = BLOCK_OPT_SIZE,
1286 .type = OPT_SIZE,
1287 .help = "Virtual disk size"
1290 .name = BLOCK_OPT_BACKING_FILE,
1291 .type = OPT_STRING,
1292 .help = "File name of a base image"
1295 .name = BLOCK_OPT_BACKING_FMT,
1296 .type = OPT_STRING,
1297 .help = "Image format of the base image"
1300 .name = BLOCK_OPT_ENCRYPT,
1301 .type = OPT_FLAG,
1302 .help = "Encrypt the image"
1305 .name = BLOCK_OPT_CLUSTER_SIZE,
1306 .type = OPT_SIZE,
1307 .help = "qcow2 cluster size"
1310 .name = BLOCK_OPT_PREALLOC,
1311 .type = OPT_STRING,
1312 .help = "Preallocation mode (allowed values: off, metadata)"
1314 { NULL }
1317 static BlockDriver bdrv_qcow2 = {
1318 .format_name = "qcow2",
1319 .instance_size = sizeof(BDRVQcowState),
1320 .bdrv_probe = qcow_probe,
1321 .bdrv_open = qcow_open,
1322 .bdrv_close = qcow_close,
1323 .bdrv_create = qcow_create,
1324 .bdrv_flush = qcow_flush,
1325 .bdrv_is_allocated = qcow_is_allocated,
1326 .bdrv_set_key = qcow_set_key,
1327 .bdrv_make_empty = qcow_make_empty,
1329 .bdrv_aio_readv = qcow_aio_readv,
1330 .bdrv_aio_writev = qcow_aio_writev,
1331 .bdrv_aio_flush = qcow_aio_flush,
1333 .bdrv_truncate = qcow2_truncate,
1334 .bdrv_write_compressed = qcow_write_compressed,
1336 .bdrv_snapshot_create = qcow2_snapshot_create,
1337 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1338 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1339 .bdrv_snapshot_list = qcow2_snapshot_list,
1340 .bdrv_get_info = qcow_get_info,
1342 .bdrv_save_vmstate = qcow_save_vmstate,
1343 .bdrv_load_vmstate = qcow_load_vmstate,
1345 .bdrv_change_backing_file = qcow2_change_backing_file,
1347 .create_options = qcow_create_options,
1348 .bdrv_check = qcow_check,
1351 static void bdrv_qcow2_init(void)
1353 bdrv_register(&bdrv_qcow2);
1356 block_init(bdrv_qcow2_init);