nbd: add git tree to MAINTAINERS
[qemu/kevin.git] / block / qcow2.c
blob3692b4523b43a049dd40a451c990ba84c182eb55
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "block_int.h"
26 #include "module.h"
27 #include <zlib.h>
28 #include "aes.h"
29 #include "block/qcow2.h"
30 #include "qemu-error.h"
31 #include "qerror.h"
34 Differences with QCOW:
36 - Support for multiple incremental snapshots.
37 - Memory management by reference counts.
38 - Clusters which have a reference count of one have the bit
39 QCOW_OFLAG_COPIED to optimize write performance.
40 - Size of compressed clusters is stored in sectors to reduce bit usage
41 in the cluster offsets.
42 - Support for storing additional data (such as the VM state) in the
43 snapshots.
44 - If a backing store is used, the cluster size is not constrained
45 (could be backported to QCOW).
46 - L2 tables have always a size of one cluster.
50 typedef struct {
51 uint32_t magic;
52 uint32_t len;
53 } QCowExtension;
54 #define QCOW2_EXT_MAGIC_END 0
55 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
57 static int qcow2_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 qcow2_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;
83 int ret;
85 #ifdef DEBUG_EXT
86 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
87 #endif
88 offset = start_offset;
89 while (offset < end_offset) {
91 #ifdef DEBUG_EXT
92 BDRVQcowState *s = bs->opaque;
93 /* Sanity check */
94 if (offset > s->cluster_size)
95 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
97 printf("attempting to read extended header in offset %lu\n", offset);
98 #endif
100 if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
101 fprintf(stderr, "qcow2_read_extension: ERROR: "
102 "pread fail from offset %" PRIu64 "\n",
103 offset);
104 return 1;
106 be32_to_cpus(&ext.magic);
107 be32_to_cpus(&ext.len);
108 offset += sizeof(ext);
109 #ifdef DEBUG_EXT
110 printf("ext.magic = 0x%x\n", ext.magic);
111 #endif
112 switch (ext.magic) {
113 case QCOW2_EXT_MAGIC_END:
114 return 0;
116 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
117 if (ext.len >= sizeof(bs->backing_format)) {
118 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
119 " (>=%zu)\n",
120 ext.len, sizeof(bs->backing_format));
121 return 2;
123 if (bdrv_pread(bs->file, offset , bs->backing_format,
124 ext.len) != ext.len)
125 return 3;
126 bs->backing_format[ext.len] = '\0';
127 #ifdef DEBUG_EXT
128 printf("Qcow2: Got format extension %s\n", bs->backing_format);
129 #endif
130 offset = ((offset + ext.len + 7) & ~7);
131 break;
133 default:
134 /* unknown magic - save it in case we need to rewrite the header */
136 Qcow2UnknownHeaderExtension *uext;
138 uext = g_malloc0(sizeof(*uext) + ext.len);
139 uext->magic = ext.magic;
140 uext->len = ext.len;
141 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
143 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
144 if (ret < 0) {
145 return ret;
148 offset = ((offset + ext.len + 7) & ~7);
150 break;
154 return 0;
157 static void cleanup_unknown_header_ext(BlockDriverState *bs)
159 BDRVQcowState *s = bs->opaque;
160 Qcow2UnknownHeaderExtension *uext, *next;
162 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
163 QLIST_REMOVE(uext, next);
164 g_free(uext);
168 static int qcow2_open(BlockDriverState *bs, int flags)
170 BDRVQcowState *s = bs->opaque;
171 int len, i, ret = 0;
172 QCowHeader header;
173 uint64_t ext_end;
174 bool writethrough;
176 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
177 if (ret < 0) {
178 goto fail;
180 be32_to_cpus(&header.magic);
181 be32_to_cpus(&header.version);
182 be64_to_cpus(&header.backing_file_offset);
183 be32_to_cpus(&header.backing_file_size);
184 be64_to_cpus(&header.size);
185 be32_to_cpus(&header.cluster_bits);
186 be32_to_cpus(&header.crypt_method);
187 be64_to_cpus(&header.l1_table_offset);
188 be32_to_cpus(&header.l1_size);
189 be64_to_cpus(&header.refcount_table_offset);
190 be32_to_cpus(&header.refcount_table_clusters);
191 be64_to_cpus(&header.snapshots_offset);
192 be32_to_cpus(&header.nb_snapshots);
194 if (header.magic != QCOW_MAGIC) {
195 ret = -EINVAL;
196 goto fail;
198 if (header.version != QCOW_VERSION) {
199 char version[64];
200 snprintf(version, sizeof(version), "QCOW version %d", header.version);
201 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
202 bs->device_name, "qcow2", version);
203 ret = -ENOTSUP;
204 goto fail;
206 if (header.cluster_bits < MIN_CLUSTER_BITS ||
207 header.cluster_bits > MAX_CLUSTER_BITS) {
208 ret = -EINVAL;
209 goto fail;
211 if (header.crypt_method > QCOW_CRYPT_AES) {
212 ret = -EINVAL;
213 goto fail;
215 s->crypt_method_header = header.crypt_method;
216 if (s->crypt_method_header) {
217 bs->encrypted = 1;
219 s->cluster_bits = header.cluster_bits;
220 s->cluster_size = 1 << s->cluster_bits;
221 s->cluster_sectors = 1 << (s->cluster_bits - 9);
222 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
223 s->l2_size = 1 << s->l2_bits;
224 bs->total_sectors = header.size / 512;
225 s->csize_shift = (62 - (s->cluster_bits - 8));
226 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
227 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
228 s->refcount_table_offset = header.refcount_table_offset;
229 s->refcount_table_size =
230 header.refcount_table_clusters << (s->cluster_bits - 3);
232 s->snapshots_offset = header.snapshots_offset;
233 s->nb_snapshots = header.nb_snapshots;
235 /* read the level 1 table */
236 s->l1_size = header.l1_size;
237 s->l1_vm_state_index = size_to_l1(s, header.size);
238 /* the L1 table must contain at least enough entries to put
239 header.size bytes */
240 if (s->l1_size < s->l1_vm_state_index) {
241 ret = -EINVAL;
242 goto fail;
244 s->l1_table_offset = header.l1_table_offset;
245 if (s->l1_size > 0) {
246 s->l1_table = g_malloc0(
247 align_offset(s->l1_size * sizeof(uint64_t), 512));
248 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
249 s->l1_size * sizeof(uint64_t));
250 if (ret < 0) {
251 goto fail;
253 for(i = 0;i < s->l1_size; i++) {
254 be64_to_cpus(&s->l1_table[i]);
258 /* alloc L2 table/refcount block cache */
259 writethrough = ((flags & BDRV_O_CACHE_WB) == 0);
260 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE, writethrough);
261 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE,
262 writethrough);
264 s->cluster_cache = g_malloc(s->cluster_size);
265 /* one more sector for decompressed data alignment */
266 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
267 + 512);
268 s->cluster_cache_offset = -1;
269 s->flags = flags;
271 ret = qcow2_refcount_init(bs);
272 if (ret != 0) {
273 goto fail;
276 QLIST_INIT(&s->cluster_allocs);
278 /* read qcow2 extensions */
279 if (header.backing_file_offset) {
280 ext_end = header.backing_file_offset;
281 } else {
282 ext_end = s->cluster_size;
284 if (qcow2_read_extensions(bs, sizeof(header), ext_end)) {
285 ret = -EINVAL;
286 goto fail;
289 /* read the backing file name */
290 if (header.backing_file_offset != 0) {
291 len = header.backing_file_size;
292 if (len > 1023) {
293 len = 1023;
295 ret = bdrv_pread(bs->file, header.backing_file_offset,
296 bs->backing_file, len);
297 if (ret < 0) {
298 goto fail;
300 bs->backing_file[len] = '\0';
303 ret = qcow2_read_snapshots(bs);
304 if (ret < 0) {
305 goto fail;
308 /* Initialise locks */
309 qemu_co_mutex_init(&s->lock);
311 #ifdef DEBUG_ALLOC
313 BdrvCheckResult result = {0};
314 qcow2_check_refcounts(bs, &result);
316 #endif
317 return ret;
319 fail:
320 cleanup_unknown_header_ext(bs);
321 qcow2_free_snapshots(bs);
322 qcow2_refcount_close(bs);
323 g_free(s->l1_table);
324 if (s->l2_table_cache) {
325 qcow2_cache_destroy(bs, s->l2_table_cache);
327 g_free(s->cluster_cache);
328 qemu_vfree(s->cluster_data);
329 return ret;
332 static int qcow2_set_key(BlockDriverState *bs, const char *key)
334 BDRVQcowState *s = bs->opaque;
335 uint8_t keybuf[16];
336 int len, i;
338 memset(keybuf, 0, 16);
339 len = strlen(key);
340 if (len > 16)
341 len = 16;
342 /* XXX: we could compress the chars to 7 bits to increase
343 entropy */
344 for(i = 0;i < len;i++) {
345 keybuf[i] = key[i];
347 s->crypt_method = s->crypt_method_header;
349 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
350 return -1;
351 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
352 return -1;
353 #if 0
354 /* test */
356 uint8_t in[16];
357 uint8_t out[16];
358 uint8_t tmp[16];
359 for(i=0;i<16;i++)
360 in[i] = i;
361 AES_encrypt(in, tmp, &s->aes_encrypt_key);
362 AES_decrypt(tmp, out, &s->aes_decrypt_key);
363 for(i = 0; i < 16; i++)
364 printf(" %02x", tmp[i]);
365 printf("\n");
366 for(i = 0; i < 16; i++)
367 printf(" %02x", out[i]);
368 printf("\n");
370 #endif
371 return 0;
374 static int coroutine_fn qcow2_co_is_allocated(BlockDriverState *bs,
375 int64_t sector_num, int nb_sectors, int *pnum)
377 BDRVQcowState *s = bs->opaque;
378 uint64_t cluster_offset;
379 int ret;
381 *pnum = nb_sectors;
382 /* FIXME We can get errors here, but the bdrv_co_is_allocated interface
383 * can't pass them on today */
384 qemu_co_mutex_lock(&s->lock);
385 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
386 qemu_co_mutex_unlock(&s->lock);
387 if (ret < 0) {
388 *pnum = 0;
391 return (cluster_offset != 0);
394 /* handle reading after the end of the backing file */
395 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
396 int64_t sector_num, int nb_sectors)
398 int n1;
399 if ((sector_num + nb_sectors) <= bs->total_sectors)
400 return nb_sectors;
401 if (sector_num >= bs->total_sectors)
402 n1 = 0;
403 else
404 n1 = bs->total_sectors - sector_num;
406 qemu_iovec_memset_skip(qiov, 0, 512 * (nb_sectors - n1), 512 * n1);
408 return n1;
411 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
412 int remaining_sectors, QEMUIOVector *qiov)
414 BDRVQcowState *s = bs->opaque;
415 int index_in_cluster, n1;
416 int ret;
417 int cur_nr_sectors; /* number of sectors in current iteration */
418 uint64_t cluster_offset = 0;
419 uint64_t bytes_done = 0;
420 QEMUIOVector hd_qiov;
421 uint8_t *cluster_data = NULL;
423 qemu_iovec_init(&hd_qiov, qiov->niov);
425 qemu_co_mutex_lock(&s->lock);
427 while (remaining_sectors != 0) {
429 /* prepare next request */
430 cur_nr_sectors = remaining_sectors;
431 if (s->crypt_method) {
432 cur_nr_sectors = MIN(cur_nr_sectors,
433 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
436 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
437 &cur_nr_sectors, &cluster_offset);
438 if (ret < 0) {
439 goto fail;
442 index_in_cluster = sector_num & (s->cluster_sectors - 1);
444 qemu_iovec_reset(&hd_qiov);
445 qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
446 cur_nr_sectors * 512);
448 if (!cluster_offset) {
450 if (bs->backing_hd) {
451 /* read from the base image */
452 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
453 sector_num, cur_nr_sectors);
454 if (n1 > 0) {
455 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
456 qemu_co_mutex_unlock(&s->lock);
457 ret = bdrv_co_readv(bs->backing_hd, sector_num,
458 n1, &hd_qiov);
459 qemu_co_mutex_lock(&s->lock);
460 if (ret < 0) {
461 goto fail;
464 } else {
465 /* Note: in this case, no need to wait */
466 qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);
468 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
469 /* add AIO support for compressed blocks ? */
470 ret = qcow2_decompress_cluster(bs, cluster_offset);
471 if (ret < 0) {
472 goto fail;
475 qemu_iovec_from_buffer(&hd_qiov,
476 s->cluster_cache + index_in_cluster * 512,
477 512 * cur_nr_sectors);
478 } else {
479 if ((cluster_offset & 511) != 0) {
480 ret = -EIO;
481 goto fail;
484 if (s->crypt_method) {
486 * For encrypted images, read everything into a temporary
487 * contiguous buffer on which the AES functions can work.
489 if (!cluster_data) {
490 cluster_data =
491 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
494 assert(cur_nr_sectors <=
495 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
496 qemu_iovec_reset(&hd_qiov);
497 qemu_iovec_add(&hd_qiov, cluster_data,
498 512 * cur_nr_sectors);
501 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
502 qemu_co_mutex_unlock(&s->lock);
503 ret = bdrv_co_readv(bs->file,
504 (cluster_offset >> 9) + index_in_cluster,
505 cur_nr_sectors, &hd_qiov);
506 qemu_co_mutex_lock(&s->lock);
507 if (ret < 0) {
508 goto fail;
510 if (s->crypt_method) {
511 qcow2_encrypt_sectors(s, sector_num, cluster_data,
512 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
513 qemu_iovec_reset(&hd_qiov);
514 qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
515 cur_nr_sectors * 512);
516 qemu_iovec_from_buffer(&hd_qiov, cluster_data,
517 512 * cur_nr_sectors);
521 remaining_sectors -= cur_nr_sectors;
522 sector_num += cur_nr_sectors;
523 bytes_done += cur_nr_sectors * 512;
525 ret = 0;
527 fail:
528 qemu_co_mutex_unlock(&s->lock);
530 qemu_iovec_destroy(&hd_qiov);
531 qemu_vfree(cluster_data);
533 return ret;
536 static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m)
538 /* Take the request off the list of running requests */
539 if (m->nb_clusters != 0) {
540 QLIST_REMOVE(m, next_in_flight);
543 /* Restart all dependent requests */
544 if (!qemu_co_queue_empty(&m->dependent_requests)) {
545 qemu_co_mutex_unlock(&s->lock);
546 qemu_co_queue_restart_all(&m->dependent_requests);
547 qemu_co_mutex_lock(&s->lock);
551 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
552 int64_t sector_num,
553 int remaining_sectors,
554 QEMUIOVector *qiov)
556 BDRVQcowState *s = bs->opaque;
557 int index_in_cluster;
558 int n_end;
559 int ret;
560 int cur_nr_sectors; /* number of sectors in current iteration */
561 uint64_t cluster_offset;
562 QEMUIOVector hd_qiov;
563 uint64_t bytes_done = 0;
564 uint8_t *cluster_data = NULL;
565 QCowL2Meta l2meta = {
566 .nb_clusters = 0,
569 qemu_co_queue_init(&l2meta.dependent_requests);
571 qemu_iovec_init(&hd_qiov, qiov->niov);
573 s->cluster_cache_offset = -1; /* disable compressed cache */
575 qemu_co_mutex_lock(&s->lock);
577 while (remaining_sectors != 0) {
579 index_in_cluster = sector_num & (s->cluster_sectors - 1);
580 n_end = index_in_cluster + remaining_sectors;
581 if (s->crypt_method &&
582 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
583 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
586 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
587 index_in_cluster, n_end, &cur_nr_sectors, &l2meta);
588 if (ret < 0) {
589 goto fail;
592 cluster_offset = l2meta.cluster_offset;
593 assert((cluster_offset & 511) == 0);
595 qemu_iovec_reset(&hd_qiov);
596 qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
597 cur_nr_sectors * 512);
599 if (s->crypt_method) {
600 if (!cluster_data) {
601 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
602 s->cluster_size);
605 assert(hd_qiov.size <=
606 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
607 qemu_iovec_to_buffer(&hd_qiov, cluster_data);
609 qcow2_encrypt_sectors(s, sector_num, cluster_data,
610 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
612 qemu_iovec_reset(&hd_qiov);
613 qemu_iovec_add(&hd_qiov, cluster_data,
614 cur_nr_sectors * 512);
617 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
618 qemu_co_mutex_unlock(&s->lock);
619 ret = bdrv_co_writev(bs->file,
620 (cluster_offset >> 9) + index_in_cluster,
621 cur_nr_sectors, &hd_qiov);
622 qemu_co_mutex_lock(&s->lock);
623 if (ret < 0) {
624 goto fail;
627 ret = qcow2_alloc_cluster_link_l2(bs, &l2meta);
628 if (ret < 0) {
629 goto fail;
632 run_dependent_requests(s, &l2meta);
634 remaining_sectors -= cur_nr_sectors;
635 sector_num += cur_nr_sectors;
636 bytes_done += cur_nr_sectors * 512;
638 ret = 0;
640 fail:
641 run_dependent_requests(s, &l2meta);
643 qemu_co_mutex_unlock(&s->lock);
645 qemu_iovec_destroy(&hd_qiov);
646 qemu_vfree(cluster_data);
648 return ret;
651 static void qcow2_close(BlockDriverState *bs)
653 BDRVQcowState *s = bs->opaque;
654 g_free(s->l1_table);
656 qcow2_cache_flush(bs, s->l2_table_cache);
657 qcow2_cache_flush(bs, s->refcount_block_cache);
659 qcow2_cache_destroy(bs, s->l2_table_cache);
660 qcow2_cache_destroy(bs, s->refcount_block_cache);
662 cleanup_unknown_header_ext(bs);
663 g_free(s->cluster_cache);
664 qemu_vfree(s->cluster_data);
665 qcow2_refcount_close(bs);
666 qcow2_free_snapshots(bs);
669 static void qcow2_invalidate_cache(BlockDriverState *bs)
671 BDRVQcowState *s = bs->opaque;
672 int flags = s->flags;
673 AES_KEY aes_encrypt_key;
674 AES_KEY aes_decrypt_key;
675 uint32_t crypt_method = 0;
678 * Backing files are read-only which makes all of their metadata immutable,
679 * that means we don't have to worry about reopening them here.
682 if (s->crypt_method) {
683 crypt_method = s->crypt_method;
684 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
685 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
688 qcow2_close(bs);
690 memset(s, 0, sizeof(BDRVQcowState));
691 qcow2_open(bs, flags);
693 if (crypt_method) {
694 s->crypt_method = crypt_method;
695 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
696 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
700 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
701 size_t len, size_t buflen)
703 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
704 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
706 if (buflen < ext_len) {
707 return -ENOSPC;
710 *ext_backing_fmt = (QCowExtension) {
711 .magic = cpu_to_be32(magic),
712 .len = cpu_to_be32(len),
714 memcpy(buf + sizeof(QCowExtension), s, len);
716 return ext_len;
720 * Updates the qcow2 header, including the variable length parts of it, i.e.
721 * the backing file name and all extensions. qcow2 was not designed to allow
722 * such changes, so if we run out of space (we can only use the first cluster)
723 * this function may fail.
725 * Returns 0 on success, -errno in error cases.
727 int qcow2_update_header(BlockDriverState *bs)
729 BDRVQcowState *s = bs->opaque;
730 QCowHeader *header;
731 char *buf;
732 size_t buflen = s->cluster_size;
733 int ret;
734 uint64_t total_size;
735 uint32_t refcount_table_clusters;
736 Qcow2UnknownHeaderExtension *uext;
738 buf = qemu_blockalign(bs, buflen);
739 memset(buf, 0, s->cluster_size);
741 /* Header structure */
742 header = (QCowHeader*) buf;
744 if (buflen < sizeof(*header)) {
745 ret = -ENOSPC;
746 goto fail;
749 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
750 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
752 *header = (QCowHeader) {
753 .magic = cpu_to_be32(QCOW_MAGIC),
754 .version = cpu_to_be32(QCOW_VERSION),
755 .backing_file_offset = 0,
756 .backing_file_size = 0,
757 .cluster_bits = cpu_to_be32(s->cluster_bits),
758 .size = cpu_to_be64(total_size),
759 .crypt_method = cpu_to_be32(s->crypt_method_header),
760 .l1_size = cpu_to_be32(s->l1_size),
761 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
762 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
763 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
764 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
765 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
768 buf += sizeof(*header);
769 buflen -= sizeof(*header);
771 /* Backing file format header extension */
772 if (*bs->backing_format) {
773 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
774 bs->backing_format, strlen(bs->backing_format),
775 buflen);
776 if (ret < 0) {
777 goto fail;
780 buf += ret;
781 buflen -= ret;
784 /* Keep unknown header extensions */
785 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
786 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
787 if (ret < 0) {
788 goto fail;
791 buf += ret;
792 buflen -= ret;
795 /* End of header extensions */
796 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
797 if (ret < 0) {
798 goto fail;
801 buf += ret;
802 buflen -= ret;
804 /* Backing file name */
805 if (*bs->backing_file) {
806 size_t backing_file_len = strlen(bs->backing_file);
808 if (buflen < backing_file_len) {
809 ret = -ENOSPC;
810 goto fail;
813 strncpy(buf, bs->backing_file, buflen);
815 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
816 header->backing_file_size = cpu_to_be32(backing_file_len);
819 /* Write the new header */
820 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
821 if (ret < 0) {
822 goto fail;
825 ret = 0;
826 fail:
827 qemu_vfree(header);
828 return ret;
831 static int qcow2_change_backing_file(BlockDriverState *bs,
832 const char *backing_file, const char *backing_fmt)
834 /* Backing file format doesn't make sense without a backing file */
835 if (backing_fmt && !backing_file) {
836 return -EINVAL;
839 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
840 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
842 return qcow2_update_header(bs);
845 static int preallocate(BlockDriverState *bs)
847 uint64_t nb_sectors;
848 uint64_t offset;
849 int num;
850 int ret;
851 QCowL2Meta meta;
853 nb_sectors = bdrv_getlength(bs) >> 9;
854 offset = 0;
855 qemu_co_queue_init(&meta.dependent_requests);
856 meta.cluster_offset = 0;
858 while (nb_sectors) {
859 num = MIN(nb_sectors, INT_MAX >> 9);
860 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
861 if (ret < 0) {
862 return ret;
865 ret = qcow2_alloc_cluster_link_l2(bs, &meta);
866 if (ret < 0) {
867 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
868 return ret;
871 /* There are no dependent requests, but we need to remove our request
872 * from the list of in-flight requests */
873 run_dependent_requests(bs->opaque, &meta);
875 /* TODO Preallocate data if requested */
877 nb_sectors -= num;
878 offset += num << 9;
882 * It is expected that the image file is large enough to actually contain
883 * all of the allocated clusters (otherwise we get failing reads after
884 * EOF). Extend the image to the last allocated sector.
886 if (meta.cluster_offset != 0) {
887 uint8_t buf[512];
888 memset(buf, 0, 512);
889 ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
890 if (ret < 0) {
891 return ret;
895 return 0;
898 static int qcow2_create2(const char *filename, int64_t total_size,
899 const char *backing_file, const char *backing_format,
900 int flags, size_t cluster_size, int prealloc,
901 QEMUOptionParameter *options)
903 /* Calculate cluster_bits */
904 int cluster_bits;
905 cluster_bits = ffs(cluster_size) - 1;
906 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
907 (1 << cluster_bits) != cluster_size)
909 error_report(
910 "Cluster size must be a power of two between %d and %dk",
911 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
912 return -EINVAL;
916 * Open the image file and write a minimal qcow2 header.
918 * We keep things simple and start with a zero-sized image. We also
919 * do without refcount blocks or a L1 table for now. We'll fix the
920 * inconsistency later.
922 * We do need a refcount table because growing the refcount table means
923 * allocating two new refcount blocks - the seconds of which would be at
924 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
925 * size for any qcow2 image.
927 BlockDriverState* bs;
928 QCowHeader header;
929 uint8_t* refcount_table;
930 int ret;
932 ret = bdrv_create_file(filename, options);
933 if (ret < 0) {
934 return ret;
937 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
938 if (ret < 0) {
939 return ret;
942 /* Write the header */
943 memset(&header, 0, sizeof(header));
944 header.magic = cpu_to_be32(QCOW_MAGIC);
945 header.version = cpu_to_be32(QCOW_VERSION);
946 header.cluster_bits = cpu_to_be32(cluster_bits);
947 header.size = cpu_to_be64(0);
948 header.l1_table_offset = cpu_to_be64(0);
949 header.l1_size = cpu_to_be32(0);
950 header.refcount_table_offset = cpu_to_be64(cluster_size);
951 header.refcount_table_clusters = cpu_to_be32(1);
953 if (flags & BLOCK_FLAG_ENCRYPT) {
954 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
955 } else {
956 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
959 ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
960 if (ret < 0) {
961 goto out;
964 /* Write an empty refcount table */
965 refcount_table = g_malloc0(cluster_size);
966 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
967 g_free(refcount_table);
969 if (ret < 0) {
970 goto out;
973 bdrv_close(bs);
976 * And now open the image and make it consistent first (i.e. increase the
977 * refcount of the cluster that is occupied by the header and the refcount
978 * table)
980 BlockDriver* drv = bdrv_find_format("qcow2");
981 assert(drv != NULL);
982 ret = bdrv_open(bs, filename,
983 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv);
984 if (ret < 0) {
985 goto out;
988 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
989 if (ret < 0) {
990 goto out;
992 } else if (ret != 0) {
993 error_report("Huh, first cluster in empty image is already in use?");
994 abort();
997 /* Okay, now that we have a valid image, let's give it the right size */
998 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
999 if (ret < 0) {
1000 goto out;
1003 /* Want a backing file? There you go.*/
1004 if (backing_file) {
1005 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1006 if (ret < 0) {
1007 goto out;
1011 /* And if we're supposed to preallocate metadata, do that now */
1012 if (prealloc) {
1013 ret = preallocate(bs);
1014 if (ret < 0) {
1015 goto out;
1019 ret = 0;
1020 out:
1021 bdrv_delete(bs);
1022 return ret;
1025 static int qcow2_create(const char *filename, QEMUOptionParameter *options)
1027 const char *backing_file = NULL;
1028 const char *backing_fmt = NULL;
1029 uint64_t sectors = 0;
1030 int flags = 0;
1031 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1032 int prealloc = 0;
1034 /* Read out options */
1035 while (options && options->name) {
1036 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1037 sectors = options->value.n / 512;
1038 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1039 backing_file = options->value.s;
1040 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1041 backing_fmt = options->value.s;
1042 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1043 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1044 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1045 if (options->value.n) {
1046 cluster_size = options->value.n;
1048 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1049 if (!options->value.s || !strcmp(options->value.s, "off")) {
1050 prealloc = 0;
1051 } else if (!strcmp(options->value.s, "metadata")) {
1052 prealloc = 1;
1053 } else {
1054 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1055 options->value.s);
1056 return -EINVAL;
1059 options++;
1062 if (backing_file && prealloc) {
1063 fprintf(stderr, "Backing file and preallocation cannot be used at "
1064 "the same time\n");
1065 return -EINVAL;
1068 return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1069 cluster_size, prealloc, options);
1072 static int qcow2_make_empty(BlockDriverState *bs)
1074 #if 0
1075 /* XXX: not correct */
1076 BDRVQcowState *s = bs->opaque;
1077 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1078 int ret;
1080 memset(s->l1_table, 0, l1_length);
1081 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1082 return -1;
1083 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1084 if (ret < 0)
1085 return ret;
1087 l2_cache_reset(bs);
1088 #endif
1089 return 0;
1092 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1093 int64_t sector_num, int nb_sectors)
1095 int ret;
1096 BDRVQcowState *s = bs->opaque;
1098 qemu_co_mutex_lock(&s->lock);
1099 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1100 nb_sectors);
1101 qemu_co_mutex_unlock(&s->lock);
1102 return ret;
1105 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1107 BDRVQcowState *s = bs->opaque;
1108 int ret, new_l1_size;
1110 if (offset & 511) {
1111 return -EINVAL;
1114 /* cannot proceed if image has snapshots */
1115 if (s->nb_snapshots) {
1116 return -ENOTSUP;
1119 /* shrinking is currently not supported */
1120 if (offset < bs->total_sectors * 512) {
1121 return -ENOTSUP;
1124 new_l1_size = size_to_l1(s, offset);
1125 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1126 if (ret < 0) {
1127 return ret;
1130 /* write updated header.size */
1131 offset = cpu_to_be64(offset);
1132 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1133 &offset, sizeof(uint64_t));
1134 if (ret < 0) {
1135 return ret;
1138 s->l1_vm_state_index = new_l1_size;
1139 return 0;
1142 /* XXX: put compressed sectors first, then all the cluster aligned
1143 tables to avoid losing bytes in alignment */
1144 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1145 const uint8_t *buf, int nb_sectors)
1147 BDRVQcowState *s = bs->opaque;
1148 z_stream strm;
1149 int ret, out_len;
1150 uint8_t *out_buf;
1151 uint64_t cluster_offset;
1153 if (nb_sectors == 0) {
1154 /* align end of file to a sector boundary to ease reading with
1155 sector based I/Os */
1156 cluster_offset = bdrv_getlength(bs->file);
1157 cluster_offset = (cluster_offset + 511) & ~511;
1158 bdrv_truncate(bs->file, cluster_offset);
1159 return 0;
1162 if (nb_sectors != s->cluster_sectors)
1163 return -EINVAL;
1165 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1167 /* best compression, small window, no zlib header */
1168 memset(&strm, 0, sizeof(strm));
1169 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1170 Z_DEFLATED, -12,
1171 9, Z_DEFAULT_STRATEGY);
1172 if (ret != 0) {
1173 ret = -EINVAL;
1174 goto fail;
1177 strm.avail_in = s->cluster_size;
1178 strm.next_in = (uint8_t *)buf;
1179 strm.avail_out = s->cluster_size;
1180 strm.next_out = out_buf;
1182 ret = deflate(&strm, Z_FINISH);
1183 if (ret != Z_STREAM_END && ret != Z_OK) {
1184 deflateEnd(&strm);
1185 ret = -EINVAL;
1186 goto fail;
1188 out_len = strm.next_out - out_buf;
1190 deflateEnd(&strm);
1192 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1193 /* could not compress: write normal cluster */
1194 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1195 if (ret < 0) {
1196 goto fail;
1198 } else {
1199 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1200 sector_num << 9, out_len);
1201 if (!cluster_offset) {
1202 ret = -EIO;
1203 goto fail;
1205 cluster_offset &= s->cluster_offset_mask;
1206 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1207 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1208 if (ret < 0) {
1209 goto fail;
1213 ret = 0;
1214 fail:
1215 g_free(out_buf);
1216 return ret;
1219 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1221 BDRVQcowState *s = bs->opaque;
1222 int ret;
1224 qemu_co_mutex_lock(&s->lock);
1225 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1226 if (ret < 0) {
1227 qemu_co_mutex_unlock(&s->lock);
1228 return ret;
1231 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1232 if (ret < 0) {
1233 qemu_co_mutex_unlock(&s->lock);
1234 return ret;
1236 qemu_co_mutex_unlock(&s->lock);
1238 return 0;
1241 static coroutine_fn int qcow2_co_flush_to_disk(BlockDriverState *bs)
1243 return bdrv_co_flush(bs->file);
1246 static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
1248 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1251 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1253 BDRVQcowState *s = bs->opaque;
1254 bdi->cluster_size = s->cluster_size;
1255 bdi->vm_state_offset = qcow2_vm_state_offset(s);
1256 return 0;
1260 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result)
1262 return qcow2_check_refcounts(bs, result);
1265 #if 0
1266 static void dump_refcounts(BlockDriverState *bs)
1268 BDRVQcowState *s = bs->opaque;
1269 int64_t nb_clusters, k, k1, size;
1270 int refcount;
1272 size = bdrv_getlength(bs->file);
1273 nb_clusters = size_to_clusters(s, size);
1274 for(k = 0; k < nb_clusters;) {
1275 k1 = k;
1276 refcount = get_refcount(bs, k);
1277 k++;
1278 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1279 k++;
1280 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1281 k - k1);
1284 #endif
1286 static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1287 int64_t pos, int size)
1289 BDRVQcowState *s = bs->opaque;
1290 int growable = bs->growable;
1291 int ret;
1293 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1294 bs->growable = 1;
1295 ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1296 bs->growable = growable;
1298 return ret;
1301 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1302 int64_t pos, int size)
1304 BDRVQcowState *s = bs->opaque;
1305 int growable = bs->growable;
1306 int ret;
1308 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1309 bs->growable = 1;
1310 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1311 bs->growable = growable;
1313 return ret;
1316 static QEMUOptionParameter qcow2_create_options[] = {
1318 .name = BLOCK_OPT_SIZE,
1319 .type = OPT_SIZE,
1320 .help = "Virtual disk size"
1323 .name = BLOCK_OPT_BACKING_FILE,
1324 .type = OPT_STRING,
1325 .help = "File name of a base image"
1328 .name = BLOCK_OPT_BACKING_FMT,
1329 .type = OPT_STRING,
1330 .help = "Image format of the base image"
1333 .name = BLOCK_OPT_ENCRYPT,
1334 .type = OPT_FLAG,
1335 .help = "Encrypt the image"
1338 .name = BLOCK_OPT_CLUSTER_SIZE,
1339 .type = OPT_SIZE,
1340 .help = "qcow2 cluster size",
1341 .value = { .n = DEFAULT_CLUSTER_SIZE },
1344 .name = BLOCK_OPT_PREALLOC,
1345 .type = OPT_STRING,
1346 .help = "Preallocation mode (allowed values: off, metadata)"
1348 { NULL }
1351 static BlockDriver bdrv_qcow2 = {
1352 .format_name = "qcow2",
1353 .instance_size = sizeof(BDRVQcowState),
1354 .bdrv_probe = qcow2_probe,
1355 .bdrv_open = qcow2_open,
1356 .bdrv_close = qcow2_close,
1357 .bdrv_create = qcow2_create,
1358 .bdrv_co_is_allocated = qcow2_co_is_allocated,
1359 .bdrv_set_key = qcow2_set_key,
1360 .bdrv_make_empty = qcow2_make_empty,
1362 .bdrv_co_readv = qcow2_co_readv,
1363 .bdrv_co_writev = qcow2_co_writev,
1364 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
1365 .bdrv_co_flush_to_disk = qcow2_co_flush_to_disk,
1367 .bdrv_co_discard = qcow2_co_discard,
1368 .bdrv_truncate = qcow2_truncate,
1369 .bdrv_write_compressed = qcow2_write_compressed,
1371 .bdrv_snapshot_create = qcow2_snapshot_create,
1372 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1373 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1374 .bdrv_snapshot_list = qcow2_snapshot_list,
1375 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
1376 .bdrv_get_info = qcow2_get_info,
1378 .bdrv_save_vmstate = qcow2_save_vmstate,
1379 .bdrv_load_vmstate = qcow2_load_vmstate,
1381 .bdrv_change_backing_file = qcow2_change_backing_file,
1383 .bdrv_invalidate_cache = qcow2_invalidate_cache,
1385 .create_options = qcow2_create_options,
1386 .bdrv_check = qcow2_check,
1389 static void bdrv_qcow2_init(void)
1391 bdrv_register(&bdrv_qcow2);
1394 block_init(bdrv_qcow2_init);