qcow2: Return 0/-errno in qcow2_alloc_cluster_offset
[qemu/ar7.git] / block / qcow2.c
blob773d381870161fc8f046b3c22369b87d9fc03bb5
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 nb_sectors;
336 int n;
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->n, 0,
403 &s->aes_decrypt_key);
407 acb->nb_sectors -= acb->n;
408 acb->sector_num += acb->n;
409 acb->buf += acb->n * 512;
411 if (acb->nb_sectors == 0) {
412 /* request completed */
413 ret = 0;
414 goto done;
417 /* prepare next AIO request */
418 acb->n = acb->nb_sectors;
419 acb->cluster_offset =
420 qcow2_get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
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->n);
428 if (n1 > 0) {
429 acb->hd_iov.iov_base = (void *)acb->buf;
430 acb->hd_iov.iov_len = acb->n * 512;
431 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
432 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
433 &acb->hd_qiov, acb->n,
434 qcow_aio_read_cb, acb);
435 if (acb->hd_aiocb == NULL)
436 goto done;
437 } else {
438 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
439 if (ret < 0)
440 goto done;
442 } else {
443 /* Note: in this case, no need to wait */
444 memset(acb->buf, 0, 512 * acb->n);
445 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
446 if (ret < 0)
447 goto done;
449 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
450 /* add AIO support for compressed blocks ? */
451 if (qcow2_decompress_cluster(s, acb->cluster_offset) < 0)
452 goto done;
453 memcpy(acb->buf,
454 s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
455 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
456 if (ret < 0)
457 goto done;
458 } else {
459 if ((acb->cluster_offset & 511) != 0) {
460 ret = -EIO;
461 goto done;
464 acb->hd_iov.iov_base = (void *)acb->buf;
465 acb->hd_iov.iov_len = acb->n * 512;
466 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
467 acb->hd_aiocb = bdrv_aio_readv(s->hd,
468 (acb->cluster_offset >> 9) + index_in_cluster,
469 &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
470 if (acb->hd_aiocb == NULL)
471 goto done;
474 return;
475 done:
476 if (acb->qiov->niov > 1) {
477 qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
478 qemu_vfree(acb->orig_buf);
480 acb->common.cb(acb->common.opaque, ret);
481 qemu_aio_release(acb);
484 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
485 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
486 BlockDriverCompletionFunc *cb, void *opaque, int is_write)
488 QCowAIOCB *acb;
490 acb = qemu_aio_get(&qcow_aio_pool, bs, cb, opaque);
491 if (!acb)
492 return NULL;
493 acb->hd_aiocb = NULL;
494 acb->sector_num = sector_num;
495 acb->qiov = qiov;
496 if (qiov->niov > 1) {
497 acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
498 if (is_write)
499 qemu_iovec_to_buffer(qiov, acb->buf);
500 } else {
501 acb->buf = (uint8_t *)qiov->iov->iov_base;
503 acb->nb_sectors = nb_sectors;
504 acb->n = 0;
505 acb->cluster_offset = 0;
506 acb->l2meta.nb_clusters = 0;
507 QLIST_INIT(&acb->l2meta.dependent_requests);
508 return acb;
511 static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
512 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
513 BlockDriverCompletionFunc *cb, void *opaque)
515 QCowAIOCB *acb;
517 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
518 if (!acb)
519 return NULL;
521 qcow_aio_read_cb(acb, 0);
522 return &acb->common;
525 static void qcow_aio_write_cb(void *opaque, int ret);
527 static void run_dependent_requests(QCowL2Meta *m)
529 QCowAIOCB *req;
530 QCowAIOCB *next;
532 /* Take the request off the list of running requests */
533 if (m->nb_clusters != 0) {
534 QLIST_REMOVE(m, next_in_flight);
538 * Restart all dependent requests.
539 * Can't use QLIST_FOREACH here - the next link might not be the same
540 * any more after the callback (request could depend on a different
541 * request now)
543 for (req = m->dependent_requests.lh_first; req != NULL; req = next) {
544 next = req->next_depend.le_next;
545 qcow_aio_write_cb(req, 0);
548 /* Empty the list for the next part of the request */
549 QLIST_INIT(&m->dependent_requests);
552 static void qcow_aio_write_cb(void *opaque, int ret)
554 QCowAIOCB *acb = opaque;
555 BlockDriverState *bs = acb->common.bs;
556 BDRVQcowState *s = bs->opaque;
557 int index_in_cluster;
558 const uint8_t *src_buf;
559 int n_end;
561 acb->hd_aiocb = NULL;
563 if (ret >= 0) {
564 ret = qcow2_alloc_cluster_link_l2(bs, &acb->l2meta);
567 run_dependent_requests(&acb->l2meta);
569 if (ret < 0)
570 goto done;
572 acb->nb_sectors -= acb->n;
573 acb->sector_num += acb->n;
574 acb->buf += acb->n * 512;
576 if (acb->nb_sectors == 0) {
577 /* request completed */
578 ret = 0;
579 goto done;
582 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
583 n_end = index_in_cluster + acb->nb_sectors;
584 if (s->crypt_method &&
585 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
586 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
588 ret = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
589 index_in_cluster, n_end, &acb->n, &acb->l2meta);
590 if (ret < 0) {
591 goto done;
594 acb->cluster_offset = acb->l2meta.cluster_offset;
596 /* Need to wait for another request? If so, we are done for now. */
597 if (acb->l2meta.nb_clusters == 0 && acb->l2meta.depends_on != NULL) {
598 QLIST_INSERT_HEAD(&acb->l2meta.depends_on->dependent_requests,
599 acb, next_depend);
600 return;
603 assert((acb->cluster_offset & 511) == 0);
605 if (s->crypt_method) {
606 if (!acb->cluster_data) {
607 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
608 s->cluster_size);
610 qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
611 acb->n, 1, &s->aes_encrypt_key);
612 src_buf = acb->cluster_data;
613 } else {
614 src_buf = acb->buf;
616 acb->hd_iov.iov_base = (void *)src_buf;
617 acb->hd_iov.iov_len = acb->n * 512;
618 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
619 acb->hd_aiocb = bdrv_aio_writev(s->hd,
620 (acb->cluster_offset >> 9) + index_in_cluster,
621 &acb->hd_qiov, acb->n,
622 qcow_aio_write_cb, acb);
623 if (acb->hd_aiocb == NULL)
624 goto done;
626 return;
628 done:
629 if (acb->qiov->niov > 1)
630 qemu_vfree(acb->orig_buf);
631 acb->common.cb(acb->common.opaque, ret);
632 qemu_aio_release(acb);
635 static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
636 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
637 BlockDriverCompletionFunc *cb, void *opaque)
639 BDRVQcowState *s = bs->opaque;
640 QCowAIOCB *acb;
642 s->cluster_cache_offset = -1; /* disable compressed cache */
644 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
645 if (!acb)
646 return NULL;
648 qcow_aio_write_cb(acb, 0);
649 return &acb->common;
652 static void qcow_close(BlockDriverState *bs)
654 BDRVQcowState *s = bs->opaque;
655 qemu_free(s->l1_table);
656 qemu_free(s->l2_cache);
657 qemu_free(s->cluster_cache);
658 qemu_free(s->cluster_data);
659 qcow2_refcount_close(bs);
660 bdrv_delete(s->hd);
664 * Updates the variable length parts of the qcow2 header, i.e. the backing file
665 * name and all extensions. qcow2 was not designed to allow such changes, so if
666 * we run out of space (we can only use the first cluster) this function may
667 * fail.
669 * Returns 0 on success, -errno in error cases.
671 static int qcow2_update_ext_header(BlockDriverState *bs,
672 const char *backing_file, const char *backing_fmt)
674 size_t backing_file_len = 0;
675 size_t backing_fmt_len = 0;
676 BDRVQcowState *s = bs->opaque;
677 QCowExtension ext_backing_fmt = {0, 0};
678 int ret;
680 /* Backing file format doesn't make sense without a backing file */
681 if (backing_fmt && !backing_file) {
682 return -EINVAL;
685 /* Prepare the backing file format extension if needed */
686 if (backing_fmt) {
687 ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
688 ext_backing_fmt.magic = cpu_to_be32(QCOW_EXT_MAGIC_BACKING_FORMAT);
689 backing_fmt_len = ((sizeof(ext_backing_fmt)
690 + strlen(backing_fmt) + 7) & ~7);
693 /* Check if we can fit the new header into the first cluster */
694 if (backing_file) {
695 backing_file_len = strlen(backing_file);
698 size_t header_size = sizeof(QCowHeader) + backing_file_len
699 + backing_fmt_len;
701 if (header_size > s->cluster_size) {
702 return -ENOSPC;
705 /* Rewrite backing file name and qcow2 extensions */
706 size_t ext_size = header_size - sizeof(QCowHeader);
707 uint8_t buf[ext_size];
708 size_t offset = 0;
709 size_t backing_file_offset = 0;
711 if (backing_file) {
712 if (backing_fmt) {
713 int padding = backing_fmt_len -
714 (sizeof(ext_backing_fmt) + strlen(backing_fmt));
716 memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
717 offset += sizeof(ext_backing_fmt);
719 memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
720 offset += strlen(backing_fmt);
722 memset(buf + offset, 0, padding);
723 offset += padding;
726 memcpy(buf + offset, backing_file, backing_file_len);
727 backing_file_offset = sizeof(QCowHeader) + offset;
730 ret = bdrv_pwrite(s->hd, sizeof(QCowHeader), buf, ext_size);
731 if (ret < 0) {
732 goto fail;
735 /* Update header fields */
736 uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
737 uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
739 ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_offset),
740 &be_backing_file_offset, sizeof(uint64_t));
741 if (ret < 0) {
742 goto fail;
745 ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_size),
746 &be_backing_file_size, sizeof(uint32_t));
747 if (ret < 0) {
748 goto fail;
751 ret = 0;
752 fail:
753 return ret;
756 static int qcow2_change_backing_file(BlockDriverState *bs,
757 const char *backing_file, const char *backing_fmt)
759 return qcow2_update_ext_header(bs, backing_file, backing_fmt);
762 static int get_bits_from_size(size_t size)
764 int res = 0;
766 if (size == 0) {
767 return -1;
770 while (size != 1) {
771 /* Not a power of two */
772 if (size & 1) {
773 return -1;
776 size >>= 1;
777 res++;
780 return res;
784 static int preallocate(BlockDriverState *bs)
786 BDRVQcowState *s = bs->opaque;
787 uint64_t nb_sectors;
788 uint64_t offset;
789 int num;
790 int ret;
791 QCowL2Meta meta;
793 nb_sectors = bdrv_getlength(bs) >> 9;
794 offset = 0;
795 QLIST_INIT(&meta.dependent_requests);
796 meta.cluster_offset = 0;
798 while (nb_sectors) {
799 num = MIN(nb_sectors, INT_MAX >> 9);
800 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
802 if (ret < 0) {
803 return -1;
806 if (qcow2_alloc_cluster_link_l2(bs, &meta) < 0) {
807 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
808 return -1;
811 /* There are no dependent requests, but we need to remove our request
812 * from the list of in-flight requests */
813 run_dependent_requests(&meta);
815 /* TODO Preallocate data if requested */
817 nb_sectors -= num;
818 offset += num << 9;
822 * It is expected that the image file is large enough to actually contain
823 * all of the allocated clusters (otherwise we get failing reads after
824 * EOF). Extend the image to the last allocated sector.
826 if (meta.cluster_offset != 0) {
827 uint8_t buf[512];
828 memset(buf, 0, 512);
829 bdrv_write(s->hd, (meta.cluster_offset >> 9) + num - 1, buf, 1);
832 return 0;
835 static int qcow_create2(const char *filename, int64_t total_size,
836 const char *backing_file, const char *backing_format,
837 int flags, size_t cluster_size, int prealloc)
840 int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
841 int ref_clusters, backing_format_len = 0;
842 int rounded_ext_bf_len = 0;
843 QCowHeader header;
844 uint64_t tmp, offset;
845 QCowCreateState s1, *s = &s1;
846 QCowExtension ext_bf = {0, 0};
849 memset(s, 0, sizeof(*s));
851 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
852 if (fd < 0)
853 return -1;
854 memset(&header, 0, sizeof(header));
855 header.magic = cpu_to_be32(QCOW_MAGIC);
856 header.version = cpu_to_be32(QCOW_VERSION);
857 header.size = cpu_to_be64(total_size * 512);
858 header_size = sizeof(header);
859 backing_filename_len = 0;
860 if (backing_file) {
861 if (backing_format) {
862 ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
863 backing_format_len = strlen(backing_format);
864 ext_bf.len = backing_format_len;
865 rounded_ext_bf_len = (sizeof(ext_bf) + ext_bf.len + 7) & ~7;
866 header_size += rounded_ext_bf_len;
868 header.backing_file_offset = cpu_to_be64(header_size);
869 backing_filename_len = strlen(backing_file);
870 header.backing_file_size = cpu_to_be32(backing_filename_len);
871 header_size += backing_filename_len;
874 /* Cluster size */
875 s->cluster_bits = get_bits_from_size(cluster_size);
876 if (s->cluster_bits < MIN_CLUSTER_BITS ||
877 s->cluster_bits > MAX_CLUSTER_BITS)
879 fprintf(stderr, "Cluster size must be a power of two between "
880 "%d and %dk\n",
881 1 << MIN_CLUSTER_BITS,
882 1 << (MAX_CLUSTER_BITS - 10));
883 return -EINVAL;
885 s->cluster_size = 1 << s->cluster_bits;
887 header.cluster_bits = cpu_to_be32(s->cluster_bits);
888 header_size = (header_size + 7) & ~7;
889 if (flags & BLOCK_FLAG_ENCRYPT) {
890 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
891 } else {
892 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
894 l2_bits = s->cluster_bits - 3;
895 shift = s->cluster_bits + l2_bits;
896 l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
897 offset = align_offset(header_size, s->cluster_size);
898 s->l1_table_offset = offset;
899 header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
900 header.l1_size = cpu_to_be32(l1_size);
901 offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
903 s->refcount_table = qemu_mallocz(s->cluster_size);
905 s->refcount_table_offset = offset;
906 header.refcount_table_offset = cpu_to_be64(offset);
907 header.refcount_table_clusters = cpu_to_be32(1);
908 offset += s->cluster_size;
909 s->refcount_block_offset = offset;
911 /* count how many refcount blocks needed */
912 tmp = offset >> s->cluster_bits;
913 ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
914 for (i=0; i < ref_clusters; i++) {
915 s->refcount_table[i] = cpu_to_be64(offset);
916 offset += s->cluster_size;
919 s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
921 /* update refcounts */
922 qcow2_create_refcount_update(s, 0, header_size);
923 qcow2_create_refcount_update(s, s->l1_table_offset,
924 l1_size * sizeof(uint64_t));
925 qcow2_create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
926 qcow2_create_refcount_update(s, s->refcount_block_offset,
927 ref_clusters * s->cluster_size);
929 /* write all the data */
930 write(fd, &header, sizeof(header));
931 if (backing_file) {
932 if (backing_format_len) {
933 char zero[16];
934 int padding = rounded_ext_bf_len - (ext_bf.len + sizeof(ext_bf));
936 memset(zero, 0, sizeof(zero));
937 cpu_to_be32s(&ext_bf.magic);
938 cpu_to_be32s(&ext_bf.len);
939 write(fd, &ext_bf, sizeof(ext_bf));
940 write(fd, backing_format, backing_format_len);
941 if (padding > 0) {
942 write(fd, zero, padding);
945 write(fd, backing_file, backing_filename_len);
947 lseek(fd, s->l1_table_offset, SEEK_SET);
948 tmp = 0;
949 for(i = 0;i < l1_size; i++) {
950 write(fd, &tmp, sizeof(tmp));
952 lseek(fd, s->refcount_table_offset, SEEK_SET);
953 write(fd, s->refcount_table, s->cluster_size);
955 lseek(fd, s->refcount_block_offset, SEEK_SET);
956 write(fd, s->refcount_block, ref_clusters * s->cluster_size);
958 qemu_free(s->refcount_table);
959 qemu_free(s->refcount_block);
960 close(fd);
962 /* Preallocate metadata */
963 if (prealloc) {
964 BlockDriverState *bs;
965 bs = bdrv_new("");
966 bdrv_open(bs, filename, BDRV_O_CACHE_WB);
967 preallocate(bs);
968 bdrv_close(bs);
971 return 0;
974 static int qcow_create(const char *filename, QEMUOptionParameter *options)
976 const char *backing_file = NULL;
977 const char *backing_fmt = NULL;
978 uint64_t sectors = 0;
979 int flags = 0;
980 size_t cluster_size = 65536;
981 int prealloc = 0;
983 /* Read out options */
984 while (options && options->name) {
985 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
986 sectors = options->value.n / 512;
987 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
988 backing_file = options->value.s;
989 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
990 backing_fmt = options->value.s;
991 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
992 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
993 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
994 if (options->value.n) {
995 cluster_size = options->value.n;
997 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
998 if (!options->value.s || !strcmp(options->value.s, "off")) {
999 prealloc = 0;
1000 } else if (!strcmp(options->value.s, "metadata")) {
1001 prealloc = 1;
1002 } else {
1003 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1004 options->value.s);
1005 return -EINVAL;
1008 options++;
1011 if (backing_file && prealloc) {
1012 fprintf(stderr, "Backing file and preallocation cannot be used at "
1013 "the same time\n");
1014 return -EINVAL;
1017 return qcow_create2(filename, sectors, backing_file, backing_fmt, flags,
1018 cluster_size, prealloc);
1021 static int qcow_make_empty(BlockDriverState *bs)
1023 #if 0
1024 /* XXX: not correct */
1025 BDRVQcowState *s = bs->opaque;
1026 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1027 int ret;
1029 memset(s->l1_table, 0, l1_length);
1030 if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1031 return -1;
1032 ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1033 if (ret < 0)
1034 return ret;
1036 l2_cache_reset(bs);
1037 #endif
1038 return 0;
1041 /* XXX: put compressed sectors first, then all the cluster aligned
1042 tables to avoid losing bytes in alignment */
1043 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1044 const uint8_t *buf, int nb_sectors)
1046 BDRVQcowState *s = bs->opaque;
1047 z_stream strm;
1048 int ret, out_len;
1049 uint8_t *out_buf;
1050 uint64_t cluster_offset;
1052 if (nb_sectors == 0) {
1053 /* align end of file to a sector boundary to ease reading with
1054 sector based I/Os */
1055 cluster_offset = bdrv_getlength(s->hd);
1056 cluster_offset = (cluster_offset + 511) & ~511;
1057 bdrv_truncate(s->hd, cluster_offset);
1058 return 0;
1061 if (nb_sectors != s->cluster_sectors)
1062 return -EINVAL;
1064 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1066 /* best compression, small window, no zlib header */
1067 memset(&strm, 0, sizeof(strm));
1068 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1069 Z_DEFLATED, -12,
1070 9, Z_DEFAULT_STRATEGY);
1071 if (ret != 0) {
1072 qemu_free(out_buf);
1073 return -1;
1076 strm.avail_in = s->cluster_size;
1077 strm.next_in = (uint8_t *)buf;
1078 strm.avail_out = s->cluster_size;
1079 strm.next_out = out_buf;
1081 ret = deflate(&strm, Z_FINISH);
1082 if (ret != Z_STREAM_END && ret != Z_OK) {
1083 qemu_free(out_buf);
1084 deflateEnd(&strm);
1085 return -1;
1087 out_len = strm.next_out - out_buf;
1089 deflateEnd(&strm);
1091 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1092 /* could not compress: write normal cluster */
1093 bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1094 } else {
1095 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1096 sector_num << 9, out_len);
1097 if (!cluster_offset)
1098 return -1;
1099 cluster_offset &= s->cluster_offset_mask;
1100 if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1101 qemu_free(out_buf);
1102 return -1;
1106 qemu_free(out_buf);
1107 return 0;
1110 static void qcow_flush(BlockDriverState *bs)
1112 BDRVQcowState *s = bs->opaque;
1113 bdrv_flush(s->hd);
1116 static BlockDriverAIOCB *qcow_aio_flush(BlockDriverState *bs,
1117 BlockDriverCompletionFunc *cb, void *opaque)
1119 BDRVQcowState *s = bs->opaque;
1121 return bdrv_aio_flush(s->hd, cb, opaque);
1124 static int64_t qcow_vm_state_offset(BDRVQcowState *s)
1126 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1129 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1131 BDRVQcowState *s = bs->opaque;
1132 bdi->cluster_size = s->cluster_size;
1133 bdi->vm_state_offset = qcow_vm_state_offset(s);
1134 return 0;
1138 static int qcow_check(BlockDriverState *bs)
1140 return qcow2_check_refcounts(bs);
1143 #if 0
1144 static void dump_refcounts(BlockDriverState *bs)
1146 BDRVQcowState *s = bs->opaque;
1147 int64_t nb_clusters, k, k1, size;
1148 int refcount;
1150 size = bdrv_getlength(s->hd);
1151 nb_clusters = size_to_clusters(s, size);
1152 for(k = 0; k < nb_clusters;) {
1153 k1 = k;
1154 refcount = get_refcount(bs, k);
1155 k++;
1156 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1157 k++;
1158 printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
1161 #endif
1163 static int qcow_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1164 int64_t pos, int size)
1166 BDRVQcowState *s = bs->opaque;
1167 int growable = bs->growable;
1168 int ret;
1170 bs->growable = 1;
1171 ret = bdrv_pwrite(bs, qcow_vm_state_offset(s) + pos, buf, size);
1172 bs->growable = growable;
1174 return ret;
1177 static int qcow_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1178 int64_t pos, int size)
1180 BDRVQcowState *s = bs->opaque;
1181 int growable = bs->growable;
1182 int ret;
1184 bs->growable = 1;
1185 ret = bdrv_pread(bs, qcow_vm_state_offset(s) + pos, buf, size);
1186 bs->growable = growable;
1188 return ret;
1191 static QEMUOptionParameter qcow_create_options[] = {
1193 .name = BLOCK_OPT_SIZE,
1194 .type = OPT_SIZE,
1195 .help = "Virtual disk size"
1198 .name = BLOCK_OPT_BACKING_FILE,
1199 .type = OPT_STRING,
1200 .help = "File name of a base image"
1203 .name = BLOCK_OPT_BACKING_FMT,
1204 .type = OPT_STRING,
1205 .help = "Image format of the base image"
1208 .name = BLOCK_OPT_ENCRYPT,
1209 .type = OPT_FLAG,
1210 .help = "Encrypt the image"
1213 .name = BLOCK_OPT_CLUSTER_SIZE,
1214 .type = OPT_SIZE,
1215 .help = "qcow2 cluster size"
1218 .name = BLOCK_OPT_PREALLOC,
1219 .type = OPT_STRING,
1220 .help = "Preallocation mode (allowed values: off, metadata)"
1222 { NULL }
1225 static BlockDriver bdrv_qcow2 = {
1226 .format_name = "qcow2",
1227 .instance_size = sizeof(BDRVQcowState),
1228 .bdrv_probe = qcow_probe,
1229 .bdrv_open = qcow_open,
1230 .bdrv_close = qcow_close,
1231 .bdrv_create = qcow_create,
1232 .bdrv_flush = qcow_flush,
1233 .bdrv_is_allocated = qcow_is_allocated,
1234 .bdrv_set_key = qcow_set_key,
1235 .bdrv_make_empty = qcow_make_empty,
1237 .bdrv_aio_readv = qcow_aio_readv,
1238 .bdrv_aio_writev = qcow_aio_writev,
1239 .bdrv_aio_flush = qcow_aio_flush,
1240 .bdrv_write_compressed = qcow_write_compressed,
1242 .bdrv_snapshot_create = qcow2_snapshot_create,
1243 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1244 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1245 .bdrv_snapshot_list = qcow2_snapshot_list,
1246 .bdrv_get_info = qcow_get_info,
1248 .bdrv_save_vmstate = qcow_save_vmstate,
1249 .bdrv_load_vmstate = qcow_load_vmstate,
1251 .bdrv_change_backing_file = qcow2_change_backing_file,
1253 .create_options = qcow_create_options,
1254 .bdrv_check = qcow_check,
1257 static void bdrv_qcow2_init(void)
1259 bdrv_register(&bdrv_qcow2);
1262 block_init(bdrv_qcow2_init);