qcow2: Trigger blkdebug events
[qemu.git] / block / qcow2.c
blob80c99afcdbe0e7810eff168631cc34800ff81ad7
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
57 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
59 const QCowHeader *cow_header = (const void *)buf;
61 if (buf_size >= sizeof(QCowHeader) &&
62 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
63 be32_to_cpu(cow_header->version) == QCOW_VERSION)
64 return 100;
65 else
66 return 0;
70 /*
71 * read qcow2 extension and fill bs
72 * start reading from start_offset
73 * finish reading upon magic of value 0 or when end_offset reached
74 * unknown magic is skipped (future extension this version knows nothing about)
75 * return 0 upon success, non-0 otherwise
77 static int qcow_read_extensions(BlockDriverState *bs, uint64_t start_offset,
78 uint64_t end_offset)
80 BDRVQcowState *s = bs->opaque;
81 QCowExtension ext;
82 uint64_t offset;
84 #ifdef DEBUG_EXT
85 printf("qcow_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
86 #endif
87 offset = start_offset;
88 while (offset < end_offset) {
90 #ifdef DEBUG_EXT
91 /* Sanity check */
92 if (offset > s->cluster_size)
93 printf("qcow_handle_extension: suspicious offset %lu\n", offset);
95 printf("attemting to read extended header in offset %lu\n", offset);
96 #endif
98 if (bdrv_pread(s->hd, offset, &ext, sizeof(ext)) != sizeof(ext)) {
99 fprintf(stderr, "qcow_handle_extension: ERROR: pread fail from offset %llu\n",
100 (unsigned long long)offset);
101 return 1;
103 be32_to_cpus(&ext.magic);
104 be32_to_cpus(&ext.len);
105 offset += sizeof(ext);
106 #ifdef DEBUG_EXT
107 printf("ext.magic = 0x%x\n", ext.magic);
108 #endif
109 switch (ext.magic) {
110 case QCOW_EXT_MAGIC_END:
111 return 0;
113 case QCOW_EXT_MAGIC_BACKING_FORMAT:
114 if (ext.len >= sizeof(bs->backing_format)) {
115 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
116 " (>=%zu)\n",
117 ext.len, sizeof(bs->backing_format));
118 return 2;
120 if (bdrv_pread(s->hd, offset , bs->backing_format,
121 ext.len) != ext.len)
122 return 3;
123 bs->backing_format[ext.len] = '\0';
124 #ifdef DEBUG_EXT
125 printf("Qcow2: Got format extension %s\n", bs->backing_format);
126 #endif
127 offset = ((offset + ext.len + 7) & ~7);
128 break;
130 default:
131 /* unknown magic -- just skip it */
132 offset = ((offset + ext.len + 7) & ~7);
133 break;
137 return 0;
141 static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
143 BDRVQcowState *s = bs->opaque;
144 int len, i, shift, ret;
145 QCowHeader header;
146 uint64_t ext_end;
148 ret = bdrv_file_open(&s->hd, filename, flags);
149 if (ret < 0)
150 return ret;
151 if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
152 goto fail;
153 be32_to_cpus(&header.magic);
154 be32_to_cpus(&header.version);
155 be64_to_cpus(&header.backing_file_offset);
156 be32_to_cpus(&header.backing_file_size);
157 be64_to_cpus(&header.size);
158 be32_to_cpus(&header.cluster_bits);
159 be32_to_cpus(&header.crypt_method);
160 be64_to_cpus(&header.l1_table_offset);
161 be32_to_cpus(&header.l1_size);
162 be64_to_cpus(&header.refcount_table_offset);
163 be32_to_cpus(&header.refcount_table_clusters);
164 be64_to_cpus(&header.snapshots_offset);
165 be32_to_cpus(&header.nb_snapshots);
167 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
168 goto fail;
169 if (header.cluster_bits < MIN_CLUSTER_BITS ||
170 header.cluster_bits > MAX_CLUSTER_BITS)
171 goto fail;
172 if (header.crypt_method > QCOW_CRYPT_AES)
173 goto fail;
174 s->crypt_method_header = header.crypt_method;
175 if (s->crypt_method_header)
176 bs->encrypted = 1;
177 s->cluster_bits = header.cluster_bits;
178 s->cluster_size = 1 << s->cluster_bits;
179 s->cluster_sectors = 1 << (s->cluster_bits - 9);
180 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
181 s->l2_size = 1 << s->l2_bits;
182 bs->total_sectors = header.size / 512;
183 s->csize_shift = (62 - (s->cluster_bits - 8));
184 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
185 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
186 s->refcount_table_offset = header.refcount_table_offset;
187 s->refcount_table_size =
188 header.refcount_table_clusters << (s->cluster_bits - 3);
190 s->snapshots_offset = header.snapshots_offset;
191 s->nb_snapshots = header.nb_snapshots;
193 /* read the level 1 table */
194 s->l1_size = header.l1_size;
195 shift = s->cluster_bits + s->l2_bits;
196 s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
197 /* the L1 table must contain at least enough entries to put
198 header.size bytes */
199 if (s->l1_size < s->l1_vm_state_index)
200 goto fail;
201 s->l1_table_offset = header.l1_table_offset;
202 if (s->l1_size > 0) {
203 s->l1_table = qemu_mallocz(
204 align_offset(s->l1_size * sizeof(uint64_t), 512));
205 if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
206 s->l1_size * sizeof(uint64_t))
207 goto fail;
208 for(i = 0;i < s->l1_size; i++) {
209 be64_to_cpus(&s->l1_table[i]);
212 /* alloc L2 cache */
213 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
214 s->cluster_cache = qemu_malloc(s->cluster_size);
215 /* one more sector for decompressed data alignment */
216 s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
217 + 512);
218 s->cluster_cache_offset = -1;
220 if (qcow2_refcount_init(bs) < 0)
221 goto fail;
223 QLIST_INIT(&s->cluster_allocs);
225 /* read qcow2 extensions */
226 if (header.backing_file_offset)
227 ext_end = header.backing_file_offset;
228 else
229 ext_end = s->cluster_size;
230 if (qcow_read_extensions(bs, sizeof(header), ext_end))
231 goto fail;
233 /* read the backing file name */
234 if (header.backing_file_offset != 0) {
235 len = header.backing_file_size;
236 if (len > 1023)
237 len = 1023;
238 if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
239 goto fail;
240 bs->backing_file[len] = '\0';
242 if (qcow2_read_snapshots(bs) < 0)
243 goto fail;
245 #ifdef DEBUG_ALLOC
246 qcow2_check_refcounts(bs);
247 #endif
248 return 0;
250 fail:
251 qcow2_free_snapshots(bs);
252 qcow2_refcount_close(bs);
253 qemu_free(s->l1_table);
254 qemu_free(s->l2_cache);
255 qemu_free(s->cluster_cache);
256 qemu_free(s->cluster_data);
257 bdrv_delete(s->hd);
258 return -1;
261 static int qcow_set_key(BlockDriverState *bs, const char *key)
263 BDRVQcowState *s = bs->opaque;
264 uint8_t keybuf[16];
265 int len, i;
267 memset(keybuf, 0, 16);
268 len = strlen(key);
269 if (len > 16)
270 len = 16;
271 /* XXX: we could compress the chars to 7 bits to increase
272 entropy */
273 for(i = 0;i < len;i++) {
274 keybuf[i] = key[i];
276 s->crypt_method = s->crypt_method_header;
278 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
279 return -1;
280 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
281 return -1;
282 #if 0
283 /* test */
285 uint8_t in[16];
286 uint8_t out[16];
287 uint8_t tmp[16];
288 for(i=0;i<16;i++)
289 in[i] = i;
290 AES_encrypt(in, tmp, &s->aes_encrypt_key);
291 AES_decrypt(tmp, out, &s->aes_decrypt_key);
292 for(i = 0; i < 16; i++)
293 printf(" %02x", tmp[i]);
294 printf("\n");
295 for(i = 0; i < 16; i++)
296 printf(" %02x", out[i]);
297 printf("\n");
299 #endif
300 return 0;
303 static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
304 int nb_sectors, int *pnum)
306 uint64_t cluster_offset;
308 *pnum = nb_sectors;
309 cluster_offset = qcow2_get_cluster_offset(bs, sector_num << 9, pnum);
311 return (cluster_offset != 0);
314 /* handle reading after the end of the backing file */
315 int qcow2_backing_read1(BlockDriverState *bs,
316 int64_t sector_num, uint8_t *buf, int nb_sectors)
318 int n1;
319 if ((sector_num + nb_sectors) <= bs->total_sectors)
320 return nb_sectors;
321 if (sector_num >= bs->total_sectors)
322 n1 = 0;
323 else
324 n1 = bs->total_sectors - sector_num;
325 memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
326 return n1;
329 typedef struct QCowAIOCB {
330 BlockDriverAIOCB common;
331 int64_t sector_num;
332 QEMUIOVector *qiov;
333 uint8_t *buf;
334 void *orig_buf;
335 int remaining_sectors;
336 int cur_nr_sectors; /* number of sectors in current iteration */
337 uint64_t cluster_offset;
338 uint8_t *cluster_data;
339 BlockDriverAIOCB *hd_aiocb;
340 struct iovec hd_iov;
341 QEMUIOVector hd_qiov;
342 QEMUBH *bh;
343 QCowL2Meta l2meta;
344 QLIST_ENTRY(QCowAIOCB) next_depend;
345 } QCowAIOCB;
347 static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
349 QCowAIOCB *acb = (QCowAIOCB *)blockacb;
350 if (acb->hd_aiocb)
351 bdrv_aio_cancel(acb->hd_aiocb);
352 qemu_aio_release(acb);
355 static AIOPool qcow_aio_pool = {
356 .aiocb_size = sizeof(QCowAIOCB),
357 .cancel = qcow_aio_cancel,
360 static void qcow_aio_read_cb(void *opaque, int ret);
361 static void qcow_aio_read_bh(void *opaque)
363 QCowAIOCB *acb = opaque;
364 qemu_bh_delete(acb->bh);
365 acb->bh = NULL;
366 qcow_aio_read_cb(opaque, 0);
369 static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
371 if (acb->bh)
372 return -EIO;
374 acb->bh = qemu_bh_new(cb, acb);
375 if (!acb->bh)
376 return -EIO;
378 qemu_bh_schedule(acb->bh);
380 return 0;
383 static void qcow_aio_read_cb(void *opaque, int ret)
385 QCowAIOCB *acb = opaque;
386 BlockDriverState *bs = acb->common.bs;
387 BDRVQcowState *s = bs->opaque;
388 int index_in_cluster, n1;
390 acb->hd_aiocb = NULL;
391 if (ret < 0)
392 goto done;
394 /* post process the read buffer */
395 if (!acb->cluster_offset) {
396 /* nothing to do */
397 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
398 /* nothing to do */
399 } else {
400 if (s->crypt_method) {
401 qcow2_encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
402 acb->cur_nr_sectors, 0,
403 &s->aes_decrypt_key);
407 acb->remaining_sectors -= acb->cur_nr_sectors;
408 acb->sector_num += acb->cur_nr_sectors;
409 acb->buf += acb->cur_nr_sectors * 512;
411 if (acb->remaining_sectors == 0) {
412 /* request completed */
413 ret = 0;
414 goto done;
417 /* prepare next AIO request */
418 acb->cur_nr_sectors = acb->remaining_sectors;
419 acb->cluster_offset = qcow2_get_cluster_offset(bs, acb->sector_num << 9,
420 &acb->cur_nr_sectors);
421 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
423 if (!acb->cluster_offset) {
424 if (bs->backing_hd) {
425 /* read from the base image */
426 n1 = qcow2_backing_read1(bs->backing_hd, acb->sector_num,
427 acb->buf, acb->cur_nr_sectors);
428 if (n1 > 0) {
429 acb->hd_iov.iov_base = (void *)acb->buf;
430 acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
431 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
432 BLKDBG_EVENT(s->hd, BLKDBG_READ_BACKING_AIO);
433 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
434 &acb->hd_qiov, acb->cur_nr_sectors,
435 qcow_aio_read_cb, acb);
436 if (acb->hd_aiocb == NULL)
437 goto done;
438 } else {
439 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
440 if (ret < 0)
441 goto done;
443 } else {
444 /* Note: in this case, no need to wait */
445 memset(acb->buf, 0, 512 * acb->cur_nr_sectors);
446 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
447 if (ret < 0)
448 goto done;
450 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
451 /* add AIO support for compressed blocks ? */
452 if (qcow2_decompress_cluster(s, acb->cluster_offset) < 0)
453 goto done;
454 memcpy(acb->buf, s->cluster_cache + index_in_cluster * 512,
455 512 * acb->cur_nr_sectors);
456 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
457 if (ret < 0)
458 goto done;
459 } else {
460 if ((acb->cluster_offset & 511) != 0) {
461 ret = -EIO;
462 goto done;
465 acb->hd_iov.iov_base = (void *)acb->buf;
466 acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
467 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
468 BLKDBG_EVENT(s->hd, BLKDBG_READ_AIO);
469 acb->hd_aiocb = bdrv_aio_readv(s->hd,
470 (acb->cluster_offset >> 9) + index_in_cluster,
471 &acb->hd_qiov, acb->cur_nr_sectors,
472 qcow_aio_read_cb, acb);
473 if (acb->hd_aiocb == NULL) {
474 ret = -EIO;
475 goto done;
479 return;
480 done:
481 if (acb->qiov->niov > 1) {
482 qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
483 qemu_vfree(acb->orig_buf);
485 acb->common.cb(acb->common.opaque, ret);
486 qemu_aio_release(acb);
489 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
490 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
491 BlockDriverCompletionFunc *cb, void *opaque, int is_write)
493 QCowAIOCB *acb;
495 acb = qemu_aio_get(&qcow_aio_pool, bs, cb, opaque);
496 if (!acb)
497 return NULL;
498 acb->hd_aiocb = NULL;
499 acb->sector_num = sector_num;
500 acb->qiov = qiov;
501 if (qiov->niov > 1) {
502 acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
503 if (is_write)
504 qemu_iovec_to_buffer(qiov, acb->buf);
505 } else {
506 acb->buf = (uint8_t *)qiov->iov->iov_base;
508 acb->remaining_sectors = nb_sectors;
509 acb->cur_nr_sectors = 0;
510 acb->cluster_offset = 0;
511 acb->l2meta.nb_clusters = 0;
512 QLIST_INIT(&acb->l2meta.dependent_requests);
513 return acb;
516 static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
517 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
518 BlockDriverCompletionFunc *cb, void *opaque)
520 QCowAIOCB *acb;
522 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
523 if (!acb)
524 return NULL;
526 qcow_aio_read_cb(acb, 0);
527 return &acb->common;
530 static void qcow_aio_write_cb(void *opaque, int ret);
532 static void run_dependent_requests(QCowL2Meta *m)
534 QCowAIOCB *req;
535 QCowAIOCB *next;
537 /* Take the request off the list of running requests */
538 if (m->nb_clusters != 0) {
539 QLIST_REMOVE(m, next_in_flight);
543 * Restart all dependent requests.
544 * Can't use QLIST_FOREACH here - the next link might not be the same
545 * any more after the callback (request could depend on a different
546 * request now)
548 for (req = m->dependent_requests.lh_first; req != NULL; req = next) {
549 next = req->next_depend.le_next;
550 qcow_aio_write_cb(req, 0);
553 /* Empty the list for the next part of the request */
554 QLIST_INIT(&m->dependent_requests);
557 static void qcow_aio_write_cb(void *opaque, int ret)
559 QCowAIOCB *acb = opaque;
560 BlockDriverState *bs = acb->common.bs;
561 BDRVQcowState *s = bs->opaque;
562 int index_in_cluster;
563 const uint8_t *src_buf;
564 int n_end;
566 acb->hd_aiocb = NULL;
568 if (ret >= 0) {
569 ret = qcow2_alloc_cluster_link_l2(bs, &acb->l2meta);
572 run_dependent_requests(&acb->l2meta);
574 if (ret < 0)
575 goto done;
577 acb->remaining_sectors -= acb->cur_nr_sectors;
578 acb->sector_num += acb->cur_nr_sectors;
579 acb->buf += acb->cur_nr_sectors * 512;
581 if (acb->remaining_sectors == 0) {
582 /* request completed */
583 ret = 0;
584 goto done;
587 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
588 n_end = index_in_cluster + acb->remaining_sectors;
589 if (s->crypt_method &&
590 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
591 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
593 ret = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
594 index_in_cluster, n_end, &acb->cur_nr_sectors, &acb->l2meta);
595 if (ret < 0) {
596 goto done;
599 acb->cluster_offset = acb->l2meta.cluster_offset;
601 /* Need to wait for another request? If so, we are done for now. */
602 if (acb->l2meta.nb_clusters == 0 && acb->l2meta.depends_on != NULL) {
603 QLIST_INSERT_HEAD(&acb->l2meta.depends_on->dependent_requests,
604 acb, next_depend);
605 return;
608 assert((acb->cluster_offset & 511) == 0);
610 if (s->crypt_method) {
611 if (!acb->cluster_data) {
612 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
613 s->cluster_size);
615 qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
616 acb->cur_nr_sectors, 1, &s->aes_encrypt_key);
617 src_buf = acb->cluster_data;
618 } else {
619 src_buf = acb->buf;
621 acb->hd_iov.iov_base = (void *)src_buf;
622 acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
623 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
624 BLKDBG_EVENT(s->hd, BLKDBG_WRITE_AIO);
625 acb->hd_aiocb = bdrv_aio_writev(s->hd,
626 (acb->cluster_offset >> 9) + index_in_cluster,
627 &acb->hd_qiov, acb->cur_nr_sectors,
628 qcow_aio_write_cb, acb);
629 if (acb->hd_aiocb == NULL) {
630 ret = -EIO;
631 goto fail;
634 return;
636 fail:
637 if (acb->l2meta.nb_clusters != 0) {
638 QLIST_REMOVE(&acb->l2meta, next_in_flight);
640 done:
641 if (acb->qiov->niov > 1)
642 qemu_vfree(acb->orig_buf);
643 acb->common.cb(acb->common.opaque, ret);
644 qemu_aio_release(acb);
647 static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
648 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
649 BlockDriverCompletionFunc *cb, void *opaque)
651 BDRVQcowState *s = bs->opaque;
652 QCowAIOCB *acb;
654 s->cluster_cache_offset = -1; /* disable compressed cache */
656 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
657 if (!acb)
658 return NULL;
660 qcow_aio_write_cb(acb, 0);
661 return &acb->common;
664 static void qcow_close(BlockDriverState *bs)
666 BDRVQcowState *s = bs->opaque;
667 qemu_free(s->l1_table);
668 qemu_free(s->l2_cache);
669 qemu_free(s->cluster_cache);
670 qemu_free(s->cluster_data);
671 qcow2_refcount_close(bs);
672 bdrv_delete(s->hd);
676 * Updates the variable length parts of the qcow2 header, i.e. the backing file
677 * name and all extensions. qcow2 was not designed to allow such changes, so if
678 * we run out of space (we can only use the first cluster) this function may
679 * fail.
681 * Returns 0 on success, -errno in error cases.
683 static int qcow2_update_ext_header(BlockDriverState *bs,
684 const char *backing_file, const char *backing_fmt)
686 size_t backing_file_len = 0;
687 size_t backing_fmt_len = 0;
688 BDRVQcowState *s = bs->opaque;
689 QCowExtension ext_backing_fmt = {0, 0};
690 int ret;
692 /* Backing file format doesn't make sense without a backing file */
693 if (backing_fmt && !backing_file) {
694 return -EINVAL;
697 /* Prepare the backing file format extension if needed */
698 if (backing_fmt) {
699 ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
700 ext_backing_fmt.magic = cpu_to_be32(QCOW_EXT_MAGIC_BACKING_FORMAT);
701 backing_fmt_len = ((sizeof(ext_backing_fmt)
702 + strlen(backing_fmt) + 7) & ~7);
705 /* Check if we can fit the new header into the first cluster */
706 if (backing_file) {
707 backing_file_len = strlen(backing_file);
710 size_t header_size = sizeof(QCowHeader) + backing_file_len
711 + backing_fmt_len;
713 if (header_size > s->cluster_size) {
714 return -ENOSPC;
717 /* Rewrite backing file name and qcow2 extensions */
718 size_t ext_size = header_size - sizeof(QCowHeader);
719 uint8_t buf[ext_size];
720 size_t offset = 0;
721 size_t backing_file_offset = 0;
723 if (backing_file) {
724 if (backing_fmt) {
725 int padding = backing_fmt_len -
726 (sizeof(ext_backing_fmt) + strlen(backing_fmt));
728 memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
729 offset += sizeof(ext_backing_fmt);
731 memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
732 offset += strlen(backing_fmt);
734 memset(buf + offset, 0, padding);
735 offset += padding;
738 memcpy(buf + offset, backing_file, backing_file_len);
739 backing_file_offset = sizeof(QCowHeader) + offset;
742 ret = bdrv_pwrite(s->hd, sizeof(QCowHeader), buf, ext_size);
743 if (ret < 0) {
744 goto fail;
747 /* Update header fields */
748 uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
749 uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
751 ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_offset),
752 &be_backing_file_offset, sizeof(uint64_t));
753 if (ret < 0) {
754 goto fail;
757 ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_size),
758 &be_backing_file_size, sizeof(uint32_t));
759 if (ret < 0) {
760 goto fail;
763 ret = 0;
764 fail:
765 return ret;
768 static int qcow2_change_backing_file(BlockDriverState *bs,
769 const char *backing_file, const char *backing_fmt)
771 return qcow2_update_ext_header(bs, backing_file, backing_fmt);
774 static int get_bits_from_size(size_t size)
776 int res = 0;
778 if (size == 0) {
779 return -1;
782 while (size != 1) {
783 /* Not a power of two */
784 if (size & 1) {
785 return -1;
788 size >>= 1;
789 res++;
792 return res;
796 static int preallocate(BlockDriverState *bs)
798 BDRVQcowState *s = bs->opaque;
799 uint64_t nb_sectors;
800 uint64_t offset;
801 int num;
802 int ret;
803 QCowL2Meta meta;
805 nb_sectors = bdrv_getlength(bs) >> 9;
806 offset = 0;
807 QLIST_INIT(&meta.dependent_requests);
808 meta.cluster_offset = 0;
810 while (nb_sectors) {
811 num = MIN(nb_sectors, INT_MAX >> 9);
812 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
814 if (ret < 0) {
815 return -1;
818 if (qcow2_alloc_cluster_link_l2(bs, &meta) < 0) {
819 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
820 return -1;
823 /* There are no dependent requests, but we need to remove our request
824 * from the list of in-flight requests */
825 run_dependent_requests(&meta);
827 /* TODO Preallocate data if requested */
829 nb_sectors -= num;
830 offset += num << 9;
834 * It is expected that the image file is large enough to actually contain
835 * all of the allocated clusters (otherwise we get failing reads after
836 * EOF). Extend the image to the last allocated sector.
838 if (meta.cluster_offset != 0) {
839 uint8_t buf[512];
840 memset(buf, 0, 512);
841 bdrv_write(s->hd, (meta.cluster_offset >> 9) + num - 1, buf, 1);
844 return 0;
847 static int qcow_create2(const char *filename, int64_t total_size,
848 const char *backing_file, const char *backing_format,
849 int flags, size_t cluster_size, int prealloc)
852 int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
853 int ref_clusters, backing_format_len = 0;
854 int rounded_ext_bf_len = 0;
855 QCowHeader header;
856 uint64_t tmp, offset;
857 QCowCreateState s1, *s = &s1;
858 QCowExtension ext_bf = {0, 0};
859 int ret;
861 memset(s, 0, sizeof(*s));
863 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
864 if (fd < 0)
865 return -errno;
866 memset(&header, 0, sizeof(header));
867 header.magic = cpu_to_be32(QCOW_MAGIC);
868 header.version = cpu_to_be32(QCOW_VERSION);
869 header.size = cpu_to_be64(total_size * 512);
870 header_size = sizeof(header);
871 backing_filename_len = 0;
872 if (backing_file) {
873 if (backing_format) {
874 ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
875 backing_format_len = strlen(backing_format);
876 ext_bf.len = backing_format_len;
877 rounded_ext_bf_len = (sizeof(ext_bf) + ext_bf.len + 7) & ~7;
878 header_size += rounded_ext_bf_len;
880 header.backing_file_offset = cpu_to_be64(header_size);
881 backing_filename_len = strlen(backing_file);
882 header.backing_file_size = cpu_to_be32(backing_filename_len);
883 header_size += backing_filename_len;
886 /* Cluster size */
887 s->cluster_bits = get_bits_from_size(cluster_size);
888 if (s->cluster_bits < MIN_CLUSTER_BITS ||
889 s->cluster_bits > MAX_CLUSTER_BITS)
891 fprintf(stderr, "Cluster size must be a power of two between "
892 "%d and %dk\n",
893 1 << MIN_CLUSTER_BITS,
894 1 << (MAX_CLUSTER_BITS - 10));
895 return -EINVAL;
897 s->cluster_size = 1 << s->cluster_bits;
899 header.cluster_bits = cpu_to_be32(s->cluster_bits);
900 header_size = (header_size + 7) & ~7;
901 if (flags & BLOCK_FLAG_ENCRYPT) {
902 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
903 } else {
904 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
906 l2_bits = s->cluster_bits - 3;
907 shift = s->cluster_bits + l2_bits;
908 l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
909 offset = align_offset(header_size, s->cluster_size);
910 s->l1_table_offset = offset;
911 header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
912 header.l1_size = cpu_to_be32(l1_size);
913 offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
915 s->refcount_table = qemu_mallocz(s->cluster_size);
917 s->refcount_table_offset = offset;
918 header.refcount_table_offset = cpu_to_be64(offset);
919 header.refcount_table_clusters = cpu_to_be32(1);
920 offset += s->cluster_size;
921 s->refcount_block_offset = offset;
923 /* count how many refcount blocks needed */
924 tmp = offset >> s->cluster_bits;
925 ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
926 for (i=0; i < ref_clusters; i++) {
927 s->refcount_table[i] = cpu_to_be64(offset);
928 offset += s->cluster_size;
931 s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
933 /* update refcounts */
934 qcow2_create_refcount_update(s, 0, header_size);
935 qcow2_create_refcount_update(s, s->l1_table_offset,
936 l1_size * sizeof(uint64_t));
937 qcow2_create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
938 qcow2_create_refcount_update(s, s->refcount_block_offset,
939 ref_clusters * s->cluster_size);
941 /* write all the data */
942 ret = qemu_write_full(fd, &header, sizeof(header));
943 if (ret != sizeof(header)) {
944 ret = -errno;
945 goto exit;
947 if (backing_file) {
948 if (backing_format_len) {
949 char zero[16];
950 int padding = rounded_ext_bf_len - (ext_bf.len + sizeof(ext_bf));
952 memset(zero, 0, sizeof(zero));
953 cpu_to_be32s(&ext_bf.magic);
954 cpu_to_be32s(&ext_bf.len);
955 ret = qemu_write_full(fd, &ext_bf, sizeof(ext_bf));
956 if (ret != sizeof(ext_bf)) {
957 ret = -errno;
958 goto exit;
960 ret = qemu_write_full(fd, backing_format, backing_format_len);
961 if (ret != backing_format_len) {
962 ret = -errno;
963 goto exit;
965 if (padding > 0) {
966 ret = qemu_write_full(fd, zero, padding);
967 if (ret != padding) {
968 ret = -errno;
969 goto exit;
973 ret = qemu_write_full(fd, backing_file, backing_filename_len);
974 if (ret != backing_filename_len) {
975 ret = -errno;
976 goto exit;
979 lseek(fd, s->l1_table_offset, SEEK_SET);
980 tmp = 0;
981 for(i = 0;i < l1_size; i++) {
982 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
983 if (ret != sizeof(tmp)) {
984 ret = -errno;
985 goto exit;
988 lseek(fd, s->refcount_table_offset, SEEK_SET);
989 ret = qemu_write_full(fd, s->refcount_table, s->cluster_size);
990 if (ret != s->cluster_size) {
991 ret = -errno;
992 goto exit;
995 lseek(fd, s->refcount_block_offset, SEEK_SET);
996 ret = qemu_write_full(fd, s->refcount_block,
997 ref_clusters * s->cluster_size);
998 if (ret != ref_clusters * s->cluster_size) {
999 ret = -errno;
1000 goto exit;
1003 ret = 0;
1004 exit:
1005 qemu_free(s->refcount_table);
1006 qemu_free(s->refcount_block);
1007 close(fd);
1009 /* Preallocate metadata */
1010 if (ret == 0 && prealloc) {
1011 BlockDriverState *bs;
1012 bs = bdrv_new("");
1013 bdrv_open(bs, filename, BDRV_O_CACHE_WB | BDRV_O_RDWR);
1014 preallocate(bs);
1015 bdrv_close(bs);
1018 return ret;
1021 static int qcow_create(const char *filename, QEMUOptionParameter *options)
1023 const char *backing_file = NULL;
1024 const char *backing_fmt = NULL;
1025 uint64_t sectors = 0;
1026 int flags = 0;
1027 size_t cluster_size = 65536;
1028 int prealloc = 0;
1030 /* Read out options */
1031 while (options && options->name) {
1032 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1033 sectors = options->value.n / 512;
1034 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1035 backing_file = options->value.s;
1036 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1037 backing_fmt = options->value.s;
1038 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1039 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1040 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1041 if (options->value.n) {
1042 cluster_size = options->value.n;
1044 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1045 if (!options->value.s || !strcmp(options->value.s, "off")) {
1046 prealloc = 0;
1047 } else if (!strcmp(options->value.s, "metadata")) {
1048 prealloc = 1;
1049 } else {
1050 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1051 options->value.s);
1052 return -EINVAL;
1055 options++;
1058 if (backing_file && prealloc) {
1059 fprintf(stderr, "Backing file and preallocation cannot be used at "
1060 "the same time\n");
1061 return -EINVAL;
1064 return qcow_create2(filename, sectors, backing_file, backing_fmt, flags,
1065 cluster_size, prealloc);
1068 static int qcow_make_empty(BlockDriverState *bs)
1070 #if 0
1071 /* XXX: not correct */
1072 BDRVQcowState *s = bs->opaque;
1073 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1074 int ret;
1076 memset(s->l1_table, 0, l1_length);
1077 if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1078 return -1;
1079 ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1080 if (ret < 0)
1081 return ret;
1083 l2_cache_reset(bs);
1084 #endif
1085 return 0;
1088 /* XXX: put compressed sectors first, then all the cluster aligned
1089 tables to avoid losing bytes in alignment */
1090 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1091 const uint8_t *buf, int nb_sectors)
1093 BDRVQcowState *s = bs->opaque;
1094 z_stream strm;
1095 int ret, out_len;
1096 uint8_t *out_buf;
1097 uint64_t cluster_offset;
1099 if (nb_sectors == 0) {
1100 /* align end of file to a sector boundary to ease reading with
1101 sector based I/Os */
1102 cluster_offset = bdrv_getlength(s->hd);
1103 cluster_offset = (cluster_offset + 511) & ~511;
1104 bdrv_truncate(s->hd, cluster_offset);
1105 return 0;
1108 if (nb_sectors != s->cluster_sectors)
1109 return -EINVAL;
1111 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1113 /* best compression, small window, no zlib header */
1114 memset(&strm, 0, sizeof(strm));
1115 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1116 Z_DEFLATED, -12,
1117 9, Z_DEFAULT_STRATEGY);
1118 if (ret != 0) {
1119 qemu_free(out_buf);
1120 return -1;
1123 strm.avail_in = s->cluster_size;
1124 strm.next_in = (uint8_t *)buf;
1125 strm.avail_out = s->cluster_size;
1126 strm.next_out = out_buf;
1128 ret = deflate(&strm, Z_FINISH);
1129 if (ret != Z_STREAM_END && ret != Z_OK) {
1130 qemu_free(out_buf);
1131 deflateEnd(&strm);
1132 return -1;
1134 out_len = strm.next_out - out_buf;
1136 deflateEnd(&strm);
1138 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1139 /* could not compress: write normal cluster */
1140 bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1141 } else {
1142 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1143 sector_num << 9, out_len);
1144 if (!cluster_offset)
1145 return -1;
1146 cluster_offset &= s->cluster_offset_mask;
1147 BLKDBG_EVENT(s->hd, BLKDBG_WRITE_COMPRESSED);
1148 if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1149 qemu_free(out_buf);
1150 return -1;
1154 qemu_free(out_buf);
1155 return 0;
1158 static void qcow_flush(BlockDriverState *bs)
1160 BDRVQcowState *s = bs->opaque;
1161 bdrv_flush(s->hd);
1164 static BlockDriverAIOCB *qcow_aio_flush(BlockDriverState *bs,
1165 BlockDriverCompletionFunc *cb, void *opaque)
1167 BDRVQcowState *s = bs->opaque;
1169 return bdrv_aio_flush(s->hd, cb, opaque);
1172 static int64_t qcow_vm_state_offset(BDRVQcowState *s)
1174 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1177 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1179 BDRVQcowState *s = bs->opaque;
1180 bdi->cluster_size = s->cluster_size;
1181 bdi->vm_state_offset = qcow_vm_state_offset(s);
1182 return 0;
1186 static int qcow_check(BlockDriverState *bs)
1188 return qcow2_check_refcounts(bs);
1191 #if 0
1192 static void dump_refcounts(BlockDriverState *bs)
1194 BDRVQcowState *s = bs->opaque;
1195 int64_t nb_clusters, k, k1, size;
1196 int refcount;
1198 size = bdrv_getlength(s->hd);
1199 nb_clusters = size_to_clusters(s, size);
1200 for(k = 0; k < nb_clusters;) {
1201 k1 = k;
1202 refcount = get_refcount(bs, k);
1203 k++;
1204 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1205 k++;
1206 printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
1209 #endif
1211 static int qcow_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1212 int64_t pos, int size)
1214 BDRVQcowState *s = bs->opaque;
1215 int growable = bs->growable;
1216 int ret;
1218 BLKDBG_EVENT(s->hd, BLKDBG_VMSTATE_SAVE);
1219 bs->growable = 1;
1220 ret = bdrv_pwrite(bs, qcow_vm_state_offset(s) + pos, buf, size);
1221 bs->growable = growable;
1223 return ret;
1226 static int qcow_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1227 int64_t pos, int size)
1229 BDRVQcowState *s = bs->opaque;
1230 int growable = bs->growable;
1231 int ret;
1233 BLKDBG_EVENT(s->hd, BLKDBG_VMSTATE_LOAD);
1234 bs->growable = 1;
1235 ret = bdrv_pread(bs, qcow_vm_state_offset(s) + pos, buf, size);
1236 bs->growable = growable;
1238 return ret;
1241 static QEMUOptionParameter qcow_create_options[] = {
1243 .name = BLOCK_OPT_SIZE,
1244 .type = OPT_SIZE,
1245 .help = "Virtual disk size"
1248 .name = BLOCK_OPT_BACKING_FILE,
1249 .type = OPT_STRING,
1250 .help = "File name of a base image"
1253 .name = BLOCK_OPT_BACKING_FMT,
1254 .type = OPT_STRING,
1255 .help = "Image format of the base image"
1258 .name = BLOCK_OPT_ENCRYPT,
1259 .type = OPT_FLAG,
1260 .help = "Encrypt the image"
1263 .name = BLOCK_OPT_CLUSTER_SIZE,
1264 .type = OPT_SIZE,
1265 .help = "qcow2 cluster size"
1268 .name = BLOCK_OPT_PREALLOC,
1269 .type = OPT_STRING,
1270 .help = "Preallocation mode (allowed values: off, metadata)"
1272 { NULL }
1275 static BlockDriver bdrv_qcow2 = {
1276 .format_name = "qcow2",
1277 .instance_size = sizeof(BDRVQcowState),
1278 .bdrv_probe = qcow_probe,
1279 .bdrv_open = qcow_open,
1280 .bdrv_close = qcow_close,
1281 .bdrv_create = qcow_create,
1282 .bdrv_flush = qcow_flush,
1283 .bdrv_is_allocated = qcow_is_allocated,
1284 .bdrv_set_key = qcow_set_key,
1285 .bdrv_make_empty = qcow_make_empty,
1287 .bdrv_aio_readv = qcow_aio_readv,
1288 .bdrv_aio_writev = qcow_aio_writev,
1289 .bdrv_aio_flush = qcow_aio_flush,
1290 .bdrv_write_compressed = qcow_write_compressed,
1292 .bdrv_snapshot_create = qcow2_snapshot_create,
1293 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1294 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1295 .bdrv_snapshot_list = qcow2_snapshot_list,
1296 .bdrv_get_info = qcow_get_info,
1298 .bdrv_save_vmstate = qcow_save_vmstate,
1299 .bdrv_load_vmstate = qcow_load_vmstate,
1301 .bdrv_change_backing_file = qcow2_change_backing_file,
1303 .create_options = qcow_create_options,
1304 .bdrv_check = qcow_check,
1307 static void bdrv_qcow2_init(void)
1309 bdrv_register(&bdrv_qcow2);
1312 block_init(bdrv_qcow2_init);