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
24 #include "qemu-common.h"
25 #include "block_int.h"
31 Differences with QCOW:
33 - Support for multiple incremental snapshots.
34 - Memory management by reference counts.
35 - Clusters which have a reference count of one have the bit
36 QCOW_OFLAG_COPIED to optimize write performance.
37 - Size of compressed clusters is stored in sectors to reduce bit usage
38 in the cluster offsets.
39 - Support for storing additional data (such as the VM state) in the
41 - If a backing store is used, the cluster size is not constrained
42 (could be backported to QCOW).
43 - L2 tables have always a size of one cluster.
47 //#define DEBUG_ALLOC2
50 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
51 #define QCOW_VERSION 2
53 #define QCOW_CRYPT_NONE 0
54 #define QCOW_CRYPT_AES 1
56 #define QCOW_MAX_CRYPT_CLUSTERS 32
58 /* indicate that the refcount of the referenced cluster is exactly one. */
59 #define QCOW_OFLAG_COPIED (1LL << 63)
60 /* indicate that the cluster is compressed (they never have the copied flag) */
61 #define QCOW_OFLAG_COMPRESSED (1LL << 62)
63 #define REFCOUNT_SHIFT 1 /* refcount size is 2 bytes */
65 typedef struct QCowHeader {
68 uint64_t backing_file_offset;
69 uint32_t backing_file_size;
70 uint32_t cluster_bits;
71 uint64_t size; /* in bytes */
72 uint32_t crypt_method;
73 uint32_t l1_size; /* XXX: save number of clusters instead ? */
74 uint64_t l1_table_offset;
75 uint64_t refcount_table_offset;
76 uint32_t refcount_table_clusters;
77 uint32_t nb_snapshots;
78 uint64_t snapshots_offset;
86 #define QCOW_EXT_MAGIC_END 0
87 #define QCOW_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
90 typedef struct __attribute__((packed)) QCowSnapshotHeader {
91 /* header is 8 byte aligned */
92 uint64_t l1_table_offset;
101 uint64_t vm_clock_nsec;
103 uint32_t vm_state_size;
104 uint32_t extra_data_size; /* for extension */
105 /* extra data follows */
108 } QCowSnapshotHeader;
110 #define L2_CACHE_SIZE 16
112 typedef struct QCowSnapshot {
113 uint64_t l1_table_offset;
117 uint32_t vm_state_size;
120 uint64_t vm_clock_nsec;
123 typedef struct BDRVQcowState {
124 BlockDriverState *hd;
131 int l1_vm_state_index;
134 uint64_t cluster_offset_mask;
135 uint64_t l1_table_offset;
138 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
139 uint32_t l2_cache_counts[L2_CACHE_SIZE];
140 uint8_t *cluster_cache;
141 uint8_t *cluster_data;
142 uint64_t cluster_cache_offset;
144 uint64_t *refcount_table;
145 uint64_t refcount_table_offset;
146 uint32_t refcount_table_size;
147 uint64_t refcount_block_cache_offset;
148 uint16_t *refcount_block_cache;
149 int64_t free_cluster_index;
150 int64_t free_byte_offset;
152 uint32_t crypt_method; /* current crypt method, 0 if no key yet */
153 uint32_t crypt_method_header;
154 AES_KEY aes_encrypt_key;
155 AES_KEY aes_decrypt_key;
156 uint64_t snapshots_offset;
159 QCowSnapshot *snapshots;
162 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset);
163 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
164 uint8_t *buf, int nb_sectors);
165 static int qcow_read_snapshots(BlockDriverState *bs);
166 static void qcow_free_snapshots(BlockDriverState *bs);
167 static int refcount_init(BlockDriverState *bs);
168 static void refcount_close(BlockDriverState *bs);
169 static int get_refcount(BlockDriverState *bs, int64_t cluster_index);
170 static int update_cluster_refcount(BlockDriverState *bs,
171 int64_t cluster_index,
173 static void update_refcount(BlockDriverState *bs,
174 int64_t offset, int64_t length,
176 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size);
177 static int64_t alloc_bytes(BlockDriverState *bs, int size);
178 static void free_clusters(BlockDriverState *bs,
179 int64_t offset, int64_t size);
180 static int check_refcounts(BlockDriverState *bs);
182 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
184 const QCowHeader *cow_header = (const void *)buf;
186 if (buf_size >= sizeof(QCowHeader) &&
187 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
188 be32_to_cpu(cow_header->version) == QCOW_VERSION)
196 * read qcow2 extension and fill bs
197 * start reading from start_offset
198 * finish reading upon magic of value 0 or when end_offset reached
199 * unknown magic is skipped (future extension this version knows nothing about)
200 * return 0 upon success, non-0 otherwise
202 static int qcow_read_extensions(BlockDriverState *bs, uint64_t start_offset,
205 BDRVQcowState *s = bs->opaque;
210 printf("qcow_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
212 offset = start_offset;
213 while (offset < end_offset) {
217 if (offset > s->cluster_size)
218 printf("qcow_handle_extension: suspicious offset %lu\n", offset);
220 printf("attemting to read extended header in offset %lu\n", offset);
223 if (bdrv_pread(s->hd, offset, &ext, sizeof(ext)) != sizeof(ext)) {
224 fprintf(stderr, "qcow_handle_extension: ERROR: pread fail from offset %llu\n",
225 (unsigned long long)offset);
228 be32_to_cpus(&ext.magic);
229 be32_to_cpus(&ext.len);
230 offset += sizeof(ext);
232 printf("ext.magic = 0x%x\n", ext.magic);
235 case QCOW_EXT_MAGIC_END:
238 case QCOW_EXT_MAGIC_BACKING_FORMAT:
239 if (ext.len >= sizeof(bs->backing_format)) {
240 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
242 ext.len, sizeof(bs->backing_format));
245 if (bdrv_pread(s->hd, offset , bs->backing_format,
248 bs->backing_format[ext.len] = '\0';
250 printf("Qcow2: Got format extension %s\n", bs->backing_format);
252 offset += ((ext.len + 7) & ~7);
256 /* unknown magic -- just skip it */
257 offset += ((ext.len + 7) & ~7);
266 static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
268 BDRVQcowState *s = bs->opaque;
269 int len, i, shift, ret;
273 /* Performance is terrible right now with cache=writethrough due mainly
274 * to reference count updates. If the user does not explicitly specify
275 * a caching type, force to writeback caching.
277 if ((flags & BDRV_O_CACHE_DEF)) {
278 flags |= BDRV_O_CACHE_WB;
279 flags &= ~BDRV_O_CACHE_DEF;
281 ret = bdrv_file_open(&s->hd, filename, flags);
284 if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
286 be32_to_cpus(&header.magic);
287 be32_to_cpus(&header.version);
288 be64_to_cpus(&header.backing_file_offset);
289 be32_to_cpus(&header.backing_file_size);
290 be64_to_cpus(&header.size);
291 be32_to_cpus(&header.cluster_bits);
292 be32_to_cpus(&header.crypt_method);
293 be64_to_cpus(&header.l1_table_offset);
294 be32_to_cpus(&header.l1_size);
295 be64_to_cpus(&header.refcount_table_offset);
296 be32_to_cpus(&header.refcount_table_clusters);
297 be64_to_cpus(&header.snapshots_offset);
298 be32_to_cpus(&header.nb_snapshots);
300 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
302 if (header.size <= 1 ||
303 header.cluster_bits < 9 ||
304 header.cluster_bits > 16)
306 if (header.crypt_method > QCOW_CRYPT_AES)
308 s->crypt_method_header = header.crypt_method;
309 if (s->crypt_method_header)
311 s->cluster_bits = header.cluster_bits;
312 s->cluster_size = 1 << s->cluster_bits;
313 s->cluster_sectors = 1 << (s->cluster_bits - 9);
314 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
315 s->l2_size = 1 << s->l2_bits;
316 bs->total_sectors = header.size / 512;
317 s->csize_shift = (62 - (s->cluster_bits - 8));
318 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
319 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
320 s->refcount_table_offset = header.refcount_table_offset;
321 s->refcount_table_size =
322 header.refcount_table_clusters << (s->cluster_bits - 3);
324 s->snapshots_offset = header.snapshots_offset;
325 s->nb_snapshots = header.nb_snapshots;
327 /* read the level 1 table */
328 s->l1_size = header.l1_size;
329 shift = s->cluster_bits + s->l2_bits;
330 s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
331 /* the L1 table must contain at least enough entries to put
333 if (s->l1_size < s->l1_vm_state_index)
335 s->l1_table_offset = header.l1_table_offset;
336 s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
337 if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
338 s->l1_size * sizeof(uint64_t))
340 for(i = 0;i < s->l1_size; i++) {
341 be64_to_cpus(&s->l1_table[i]);
344 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
345 s->cluster_cache = qemu_malloc(s->cluster_size);
346 /* one more sector for decompressed data alignment */
347 s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
349 s->cluster_cache_offset = -1;
351 if (refcount_init(bs) < 0)
354 /* read qcow2 extensions */
355 if (header.backing_file_offset)
356 ext_end = header.backing_file_offset;
358 ext_end = s->cluster_size;
359 if (qcow_read_extensions(bs, sizeof(header), ext_end))
362 /* read the backing file name */
363 if (header.backing_file_offset != 0) {
364 len = header.backing_file_size;
367 if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
369 bs->backing_file[len] = '\0';
371 if (qcow_read_snapshots(bs) < 0)
380 qcow_free_snapshots(bs);
382 qemu_free(s->l1_table);
383 qemu_free(s->l2_cache);
384 qemu_free(s->cluster_cache);
385 qemu_free(s->cluster_data);
390 static int qcow_set_key(BlockDriverState *bs, const char *key)
392 BDRVQcowState *s = bs->opaque;
396 memset(keybuf, 0, 16);
400 /* XXX: we could compress the chars to 7 bits to increase
402 for(i = 0;i < len;i++) {
405 s->crypt_method = s->crypt_method_header;
407 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
409 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
419 AES_encrypt(in, tmp, &s->aes_encrypt_key);
420 AES_decrypt(tmp, out, &s->aes_decrypt_key);
421 for(i = 0; i < 16; i++)
422 printf(" %02x", tmp[i]);
424 for(i = 0; i < 16; i++)
425 printf(" %02x", out[i]);
432 /* The crypt function is compatible with the linux cryptoloop
433 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
435 static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
436 uint8_t *out_buf, const uint8_t *in_buf,
437 int nb_sectors, int enc,
446 for(i = 0; i < nb_sectors; i++) {
447 ivec.ll[0] = cpu_to_le64(sector_num);
449 AES_cbc_encrypt(in_buf, out_buf, 512, key,
457 static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,
458 uint64_t cluster_offset, int n_start, int n_end)
460 BDRVQcowState *s = bs->opaque;
466 ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);
469 if (s->crypt_method) {
470 encrypt_sectors(s, start_sect + n_start,
472 s->cluster_data, n, 1,
473 &s->aes_encrypt_key);
475 ret = bdrv_write(s->hd, (cluster_offset >> 9) + n_start,
482 static void l2_cache_reset(BlockDriverState *bs)
484 BDRVQcowState *s = bs->opaque;
486 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
487 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
488 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
491 static inline int l2_cache_new_entry(BlockDriverState *bs)
493 BDRVQcowState *s = bs->opaque;
497 /* find a new entry in the least used one */
499 min_count = 0xffffffff;
500 for(i = 0; i < L2_CACHE_SIZE; i++) {
501 if (s->l2_cache_counts[i] < min_count) {
502 min_count = s->l2_cache_counts[i];
509 static int64_t align_offset(int64_t offset, int n)
511 offset = (offset + n - 1) & ~(n - 1);
515 static int grow_l1_table(BlockDriverState *bs, int min_size)
517 BDRVQcowState *s = bs->opaque;
518 int new_l1_size, new_l1_size2, ret, i;
519 uint64_t *new_l1_table;
520 uint64_t new_l1_table_offset;
523 new_l1_size = s->l1_size;
524 if (min_size <= new_l1_size)
526 while (min_size > new_l1_size) {
527 new_l1_size = (new_l1_size * 3 + 1) / 2;
530 printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
533 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
534 new_l1_table = qemu_mallocz(new_l1_size2);
535 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
537 /* write new table (align to cluster) */
538 new_l1_table_offset = alloc_clusters(bs, new_l1_size2);
540 for(i = 0; i < s->l1_size; i++)
541 new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
542 ret = bdrv_pwrite(s->hd, new_l1_table_offset, new_l1_table, new_l1_size2);
543 if (ret != new_l1_size2)
545 for(i = 0; i < s->l1_size; i++)
546 new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
549 cpu_to_be32w((uint32_t*)data, new_l1_size);
550 cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);
551 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, l1_size), data,
552 sizeof(data)) != sizeof(data))
554 qemu_free(s->l1_table);
555 free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
556 s->l1_table_offset = new_l1_table_offset;
557 s->l1_table = new_l1_table;
558 s->l1_size = new_l1_size;
561 qemu_free(s->l1_table);
568 * seek l2_offset in the l2_cache table
569 * if not found, return NULL,
571 * increments the l2 cache hit count of the entry,
572 * if counter overflow, divide by two all counters
573 * return the pointer to the l2 cache entry
577 static uint64_t *seek_l2_table(BDRVQcowState *s, uint64_t l2_offset)
581 for(i = 0; i < L2_CACHE_SIZE; i++) {
582 if (l2_offset == s->l2_cache_offsets[i]) {
583 /* increment the hit count */
584 if (++s->l2_cache_counts[i] == 0xffffffff) {
585 for(j = 0; j < L2_CACHE_SIZE; j++) {
586 s->l2_cache_counts[j] >>= 1;
589 return s->l2_cache + (i << s->l2_bits);
598 * Loads a L2 table into memory. If the table is in the cache, the cache
599 * is used; otherwise the L2 table is loaded from the image file.
601 * Returns a pointer to the L2 table on success, or NULL if the read from
602 * the image file failed.
605 static uint64_t *l2_load(BlockDriverState *bs, uint64_t l2_offset)
607 BDRVQcowState *s = bs->opaque;
611 /* seek if the table for the given offset is in the cache */
613 l2_table = seek_l2_table(s, l2_offset);
614 if (l2_table != NULL)
617 /* not found: load a new entry in the least used one */
619 min_index = l2_cache_new_entry(bs);
620 l2_table = s->l2_cache + (min_index << s->l2_bits);
621 if (bdrv_pread(s->hd, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
622 s->l2_size * sizeof(uint64_t))
624 s->l2_cache_offsets[min_index] = l2_offset;
625 s->l2_cache_counts[min_index] = 1;
633 * Allocate a new l2 entry in the file. If l1_index points to an already
634 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
635 * table) copy the contents of the old L2 table into the newly allocated one.
636 * Otherwise the new table is initialized with zeros.
640 static uint64_t *l2_allocate(BlockDriverState *bs, int l1_index)
642 BDRVQcowState *s = bs->opaque;
644 uint64_t old_l2_offset, tmp;
645 uint64_t *l2_table, l2_offset;
647 old_l2_offset = s->l1_table[l1_index];
649 /* allocate a new l2 entry */
651 l2_offset = alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
653 /* update the L1 entry */
655 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
657 tmp = cpu_to_be64(l2_offset | QCOW_OFLAG_COPIED);
658 if (bdrv_pwrite(s->hd, s->l1_table_offset + l1_index * sizeof(tmp),
659 &tmp, sizeof(tmp)) != sizeof(tmp))
662 /* allocate a new entry in the l2 cache */
664 min_index = l2_cache_new_entry(bs);
665 l2_table = s->l2_cache + (min_index << s->l2_bits);
667 if (old_l2_offset == 0) {
668 /* if there was no old l2 table, clear the new table */
669 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
671 /* if there was an old l2 table, read it from the disk */
672 if (bdrv_pread(s->hd, old_l2_offset,
673 l2_table, s->l2_size * sizeof(uint64_t)) !=
674 s->l2_size * sizeof(uint64_t))
677 /* write the l2 table to the file */
678 if (bdrv_pwrite(s->hd, l2_offset,
679 l2_table, s->l2_size * sizeof(uint64_t)) !=
680 s->l2_size * sizeof(uint64_t))
683 /* update the l2 cache entry */
685 s->l2_cache_offsets[min_index] = l2_offset;
686 s->l2_cache_counts[min_index] = 1;
691 static int size_to_clusters(BDRVQcowState *s, int64_t size)
693 return (size + (s->cluster_size - 1)) >> s->cluster_bits;
696 static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
697 uint64_t *l2_table, uint64_t start, uint64_t mask)
700 uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask;
705 for (i = start; i < start + nb_clusters; i++)
706 if (offset + i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask))
712 static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
716 while(nb_clusters-- && l2_table[i] == 0)
725 * For a given offset of the disk image, return cluster offset in
728 * on entry, *num is the number of contiguous clusters we'd like to
729 * access following offset.
731 * on exit, *num is the number of contiguous clusters we can read.
733 * Return 1, if the offset is found
734 * Return 0, otherwise.
738 static uint64_t get_cluster_offset(BlockDriverState *bs,
739 uint64_t offset, int *num)
741 BDRVQcowState *s = bs->opaque;
742 int l1_index, l2_index;
743 uint64_t l2_offset, *l2_table, cluster_offset;
745 int index_in_cluster, nb_available, nb_needed, nb_clusters;
747 index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
748 nb_needed = *num + index_in_cluster;
750 l1_bits = s->l2_bits + s->cluster_bits;
752 /* compute how many bytes there are between the offset and
753 * the end of the l1 entry
756 nb_available = (1 << l1_bits) - (offset & ((1 << l1_bits) - 1));
758 /* compute the number of available sectors */
760 nb_available = (nb_available >> 9) + index_in_cluster;
762 if (nb_needed > nb_available) {
763 nb_needed = nb_available;
768 /* seek the the l2 offset in the l1 table */
770 l1_index = offset >> l1_bits;
771 if (l1_index >= s->l1_size)
774 l2_offset = s->l1_table[l1_index];
776 /* seek the l2 table of the given l2 offset */
781 /* load the l2 table in memory */
783 l2_offset &= ~QCOW_OFLAG_COPIED;
784 l2_table = l2_load(bs, l2_offset);
785 if (l2_table == NULL)
788 /* find the cluster offset for the given disk offset */
790 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
791 cluster_offset = be64_to_cpu(l2_table[l2_index]);
792 nb_clusters = size_to_clusters(s, nb_needed << 9);
794 if (!cluster_offset) {
795 /* how many empty clusters ? */
796 c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
798 /* how many allocated clusters ? */
799 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
800 &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);
803 nb_available = (c * s->cluster_sectors);
805 if (nb_available > nb_needed)
806 nb_available = nb_needed;
808 *num = nb_available - index_in_cluster;
810 return cluster_offset & ~QCOW_OFLAG_COPIED;
816 * free clusters according to its type: compressed or not
820 static void free_any_clusters(BlockDriverState *bs,
821 uint64_t cluster_offset, int nb_clusters)
823 BDRVQcowState *s = bs->opaque;
825 /* free the cluster */
827 if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
829 nb_csectors = ((cluster_offset >> s->csize_shift) &
831 free_clusters(bs, (cluster_offset & s->cluster_offset_mask) & ~511,
836 free_clusters(bs, cluster_offset, nb_clusters << s->cluster_bits);
844 * for a given disk offset, load (and allocate if needed)
847 * the l2 table offset in the qcow2 file and the cluster index
848 * in the l2 table are given to the caller.
852 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
853 uint64_t **new_l2_table,
854 uint64_t *new_l2_offset,
857 BDRVQcowState *s = bs->opaque;
858 int l1_index, l2_index, ret;
859 uint64_t l2_offset, *l2_table;
861 /* seek the the l2 offset in the l1 table */
863 l1_index = offset >> (s->l2_bits + s->cluster_bits);
864 if (l1_index >= s->l1_size) {
865 ret = grow_l1_table(bs, l1_index + 1);
869 l2_offset = s->l1_table[l1_index];
871 /* seek the l2 table of the given l2 offset */
873 if (l2_offset & QCOW_OFLAG_COPIED) {
874 /* load the l2 table in memory */
875 l2_offset &= ~QCOW_OFLAG_COPIED;
876 l2_table = l2_load(bs, l2_offset);
877 if (l2_table == NULL)
881 free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
882 l2_table = l2_allocate(bs, l1_index);
883 if (l2_table == NULL)
885 l2_offset = s->l1_table[l1_index] & ~QCOW_OFLAG_COPIED;
888 /* find the cluster offset for the given disk offset */
890 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
892 *new_l2_table = l2_table;
893 *new_l2_offset = l2_offset;
894 *new_l2_index = l2_index;
900 * alloc_compressed_cluster_offset
902 * For a given offset of the disk image, return cluster offset in
905 * If the offset is not found, allocate a new compressed cluster.
907 * Return the cluster offset if successful,
908 * Return 0, otherwise.
912 static uint64_t alloc_compressed_cluster_offset(BlockDriverState *bs,
916 BDRVQcowState *s = bs->opaque;
918 uint64_t l2_offset, *l2_table, cluster_offset;
921 ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
925 cluster_offset = be64_to_cpu(l2_table[l2_index]);
926 if (cluster_offset & QCOW_OFLAG_COPIED)
927 return cluster_offset & ~QCOW_OFLAG_COPIED;
930 free_any_clusters(bs, cluster_offset, 1);
932 cluster_offset = alloc_bytes(bs, compressed_size);
933 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
934 (cluster_offset >> 9);
936 cluster_offset |= QCOW_OFLAG_COMPRESSED |
937 ((uint64_t)nb_csectors << s->csize_shift);
939 /* update L2 table */
941 /* compressed clusters never have the copied flag */
943 l2_table[l2_index] = cpu_to_be64(cluster_offset);
944 if (bdrv_pwrite(s->hd,
945 l2_offset + l2_index * sizeof(uint64_t),
947 sizeof(uint64_t)) != sizeof(uint64_t))
950 return cluster_offset;
953 typedef struct QCowL2Meta
961 static int alloc_cluster_link_l2(BlockDriverState *bs, uint64_t cluster_offset,
964 BDRVQcowState *s = bs->opaque;
965 int i, j = 0, l2_index, ret;
966 uint64_t *old_cluster, start_sect, l2_offset, *l2_table;
968 if (m->nb_clusters == 0)
971 old_cluster = qemu_malloc(m->nb_clusters * sizeof(uint64_t));
973 /* copy content of unmodified sectors */
974 start_sect = (m->offset & ~(s->cluster_size - 1)) >> 9;
976 ret = copy_sectors(bs, start_sect, cluster_offset, 0, m->n_start);
981 if (m->nb_available & (s->cluster_sectors - 1)) {
982 uint64_t end = m->nb_available & ~(uint64_t)(s->cluster_sectors - 1);
983 ret = copy_sectors(bs, start_sect + end, cluster_offset + (end << 9),
984 m->nb_available - end, s->cluster_sectors);
990 /* update L2 table */
991 if (!get_cluster_table(bs, m->offset, &l2_table, &l2_offset, &l2_index))
994 for (i = 0; i < m->nb_clusters; i++) {
995 if(l2_table[l2_index + i] != 0)
996 old_cluster[j++] = l2_table[l2_index + i];
998 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
999 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
1002 if (bdrv_pwrite(s->hd, l2_offset + l2_index * sizeof(uint64_t),
1003 l2_table + l2_index, m->nb_clusters * sizeof(uint64_t)) !=
1004 m->nb_clusters * sizeof(uint64_t))
1007 for (i = 0; i < j; i++)
1008 free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1);
1012 qemu_free(old_cluster);
1017 * alloc_cluster_offset
1019 * For a given offset of the disk image, return cluster offset in
1022 * If the offset is not found, allocate a new cluster.
1024 * Return the cluster offset if successful,
1025 * Return 0, otherwise.
1029 static uint64_t alloc_cluster_offset(BlockDriverState *bs,
1031 int n_start, int n_end,
1032 int *num, QCowL2Meta *m)
1034 BDRVQcowState *s = bs->opaque;
1036 uint64_t l2_offset, *l2_table, cluster_offset;
1037 int nb_clusters, i = 0;
1039 ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
1043 nb_clusters = size_to_clusters(s, n_end << 9);
1045 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1047 cluster_offset = be64_to_cpu(l2_table[l2_index]);
1049 /* We keep all QCOW_OFLAG_COPIED clusters */
1051 if (cluster_offset & QCOW_OFLAG_COPIED) {
1052 nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
1053 &l2_table[l2_index], 0, 0);
1055 cluster_offset &= ~QCOW_OFLAG_COPIED;
1061 /* for the moment, multiple compressed clusters are not managed */
1063 if (cluster_offset & QCOW_OFLAG_COMPRESSED)
1066 /* how many available clusters ? */
1068 while (i < nb_clusters) {
1069 i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
1070 &l2_table[l2_index], i, 0);
1072 if(be64_to_cpu(l2_table[l2_index + i]))
1075 i += count_contiguous_free_clusters(nb_clusters - i,
1076 &l2_table[l2_index + i]);
1078 cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
1080 if ((cluster_offset & QCOW_OFLAG_COPIED) ||
1081 (cluster_offset & QCOW_OFLAG_COMPRESSED))
1086 /* allocate a new cluster */
1088 cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);
1090 /* save info needed for meta data update */
1092 m->n_start = n_start;
1093 m->nb_clusters = nb_clusters;
1096 m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
1098 *num = m->nb_available - n_start;
1100 return cluster_offset;
1103 static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
1104 int nb_sectors, int *pnum)
1106 uint64_t cluster_offset;
1109 cluster_offset = get_cluster_offset(bs, sector_num << 9, pnum);
1111 return (cluster_offset != 0);
1114 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1115 const uint8_t *buf, int buf_size)
1117 z_stream strm1, *strm = &strm1;
1120 memset(strm, 0, sizeof(*strm));
1122 strm->next_in = (uint8_t *)buf;
1123 strm->avail_in = buf_size;
1124 strm->next_out = out_buf;
1125 strm->avail_out = out_buf_size;
1127 ret = inflateInit2(strm, -12);
1130 ret = inflate(strm, Z_FINISH);
1131 out_len = strm->next_out - out_buf;
1132 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1133 out_len != out_buf_size) {
1141 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
1143 int ret, csize, nb_csectors, sector_offset;
1146 coffset = cluster_offset & s->cluster_offset_mask;
1147 if (s->cluster_cache_offset != coffset) {
1148 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1149 sector_offset = coffset & 511;
1150 csize = nb_csectors * 512 - sector_offset;
1151 ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
1155 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1156 s->cluster_data + sector_offset, csize) < 0) {
1159 s->cluster_cache_offset = coffset;
1164 /* handle reading after the end of the backing file */
1165 static int backing_read1(BlockDriverState *bs,
1166 int64_t sector_num, uint8_t *buf, int nb_sectors)
1169 if ((sector_num + nb_sectors) <= bs->total_sectors)
1171 if (sector_num >= bs->total_sectors)
1174 n1 = bs->total_sectors - sector_num;
1175 memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
1179 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
1180 uint8_t *buf, int nb_sectors)
1182 BDRVQcowState *s = bs->opaque;
1183 int ret, index_in_cluster, n, n1;
1184 uint64_t cluster_offset;
1186 while (nb_sectors > 0) {
1188 cluster_offset = get_cluster_offset(bs, sector_num << 9, &n);
1189 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1190 if (!cluster_offset) {
1191 if (bs->backing_hd) {
1192 /* read from the base image */
1193 n1 = backing_read1(bs->backing_hd, sector_num, buf, n);
1195 ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
1200 memset(buf, 0, 512 * n);
1202 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
1203 if (decompress_cluster(s, cluster_offset) < 0)
1205 memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
1207 ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1210 if (s->crypt_method) {
1211 encrypt_sectors(s, sector_num, buf, buf, n, 0,
1212 &s->aes_decrypt_key);
1222 static int qcow_write(BlockDriverState *bs, int64_t sector_num,
1223 const uint8_t *buf, int nb_sectors)
1225 BDRVQcowState *s = bs->opaque;
1226 int ret, index_in_cluster, n;
1227 uint64_t cluster_offset;
1231 while (nb_sectors > 0) {
1232 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1233 n_end = index_in_cluster + nb_sectors;
1234 if (s->crypt_method &&
1235 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1236 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1237 cluster_offset = alloc_cluster_offset(bs, sector_num << 9,
1239 n_end, &n, &l2meta);
1240 if (!cluster_offset)
1242 if (s->crypt_method) {
1243 encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
1244 &s->aes_encrypt_key);
1245 ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512,
1246 s->cluster_data, n * 512);
1248 ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1250 if (ret != n * 512 || alloc_cluster_link_l2(bs, cluster_offset, &l2meta) < 0) {
1251 free_any_clusters(bs, cluster_offset, l2meta.nb_clusters);
1258 s->cluster_cache_offset = -1; /* disable compressed cache */
1262 typedef struct QCowAIOCB {
1263 BlockDriverAIOCB common;
1270 uint64_t cluster_offset;
1271 uint8_t *cluster_data;
1272 BlockDriverAIOCB *hd_aiocb;
1273 struct iovec hd_iov;
1274 QEMUIOVector hd_qiov;
1279 static void qcow_aio_read_cb(void *opaque, int ret);
1280 static void qcow_aio_read_bh(void *opaque)
1282 QCowAIOCB *acb = opaque;
1283 qemu_bh_delete(acb->bh);
1285 qcow_aio_read_cb(opaque, 0);
1288 static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
1293 acb->bh = qemu_bh_new(cb, acb);
1297 qemu_bh_schedule(acb->bh);
1302 static void qcow_aio_read_cb(void *opaque, int ret)
1304 QCowAIOCB *acb = opaque;
1305 BlockDriverState *bs = acb->common.bs;
1306 BDRVQcowState *s = bs->opaque;
1307 int index_in_cluster, n1;
1309 acb->hd_aiocb = NULL;
1313 /* post process the read buffer */
1314 if (!acb->cluster_offset) {
1316 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1319 if (s->crypt_method) {
1320 encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
1322 &s->aes_decrypt_key);
1326 acb->nb_sectors -= acb->n;
1327 acb->sector_num += acb->n;
1328 acb->buf += acb->n * 512;
1330 if (acb->nb_sectors == 0) {
1331 /* request completed */
1336 /* prepare next AIO request */
1337 acb->n = acb->nb_sectors;
1338 acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
1339 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1341 if (!acb->cluster_offset) {
1342 if (bs->backing_hd) {
1343 /* read from the base image */
1344 n1 = backing_read1(bs->backing_hd, acb->sector_num,
1347 acb->hd_iov.iov_base = (void *)acb->buf;
1348 acb->hd_iov.iov_len = acb->n * 512;
1349 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1350 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
1351 &acb->hd_qiov, acb->n,
1352 qcow_aio_read_cb, acb);
1353 if (acb->hd_aiocb == NULL)
1356 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1361 /* Note: in this case, no need to wait */
1362 memset(acb->buf, 0, 512 * acb->n);
1363 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1367 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1368 /* add AIO support for compressed blocks ? */
1369 if (decompress_cluster(s, acb->cluster_offset) < 0)
1372 s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
1373 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1377 if ((acb->cluster_offset & 511) != 0) {
1382 acb->hd_iov.iov_base = (void *)acb->buf;
1383 acb->hd_iov.iov_len = acb->n * 512;
1384 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1385 acb->hd_aiocb = bdrv_aio_readv(s->hd,
1386 (acb->cluster_offset >> 9) + index_in_cluster,
1387 &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
1388 if (acb->hd_aiocb == NULL)
1394 if (acb->qiov->niov > 1) {
1395 qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
1396 qemu_vfree(acb->orig_buf);
1398 acb->common.cb(acb->common.opaque, ret);
1399 qemu_aio_release(acb);
1402 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
1403 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1404 BlockDriverCompletionFunc *cb, void *opaque, int is_write)
1408 acb = qemu_aio_get(bs, cb, opaque);
1411 acb->hd_aiocb = NULL;
1412 acb->sector_num = sector_num;
1414 if (qiov->niov > 1) {
1415 acb->buf = acb->orig_buf = qemu_memalign(512, qiov->size);
1417 qemu_iovec_to_buffer(qiov, acb->buf);
1419 acb->buf = (uint8_t *)qiov->iov->iov_base;
1421 acb->nb_sectors = nb_sectors;
1423 acb->cluster_offset = 0;
1424 acb->l2meta.nb_clusters = 0;
1428 static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
1429 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1430 BlockDriverCompletionFunc *cb, void *opaque)
1434 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1438 qcow_aio_read_cb(acb, 0);
1439 return &acb->common;
1442 static void qcow_aio_write_cb(void *opaque, int ret)
1444 QCowAIOCB *acb = opaque;
1445 BlockDriverState *bs = acb->common.bs;
1446 BDRVQcowState *s = bs->opaque;
1447 int index_in_cluster;
1448 const uint8_t *src_buf;
1451 acb->hd_aiocb = NULL;
1456 if (alloc_cluster_link_l2(bs, acb->cluster_offset, &acb->l2meta) < 0) {
1457 free_any_clusters(bs, acb->cluster_offset, acb->l2meta.nb_clusters);
1461 acb->nb_sectors -= acb->n;
1462 acb->sector_num += acb->n;
1463 acb->buf += acb->n * 512;
1465 if (acb->nb_sectors == 0) {
1466 /* request completed */
1471 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1472 n_end = index_in_cluster + acb->nb_sectors;
1473 if (s->crypt_method &&
1474 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1475 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1477 acb->cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,
1479 n_end, &acb->n, &acb->l2meta);
1480 if (!acb->cluster_offset || (acb->cluster_offset & 511) != 0) {
1484 if (s->crypt_method) {
1485 if (!acb->cluster_data) {
1486 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
1489 encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
1490 acb->n, 1, &s->aes_encrypt_key);
1491 src_buf = acb->cluster_data;
1495 acb->hd_iov.iov_base = (void *)src_buf;
1496 acb->hd_iov.iov_len = acb->n * 512;
1497 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1498 acb->hd_aiocb = bdrv_aio_writev(s->hd,
1499 (acb->cluster_offset >> 9) + index_in_cluster,
1500 &acb->hd_qiov, acb->n,
1501 qcow_aio_write_cb, acb);
1502 if (acb->hd_aiocb == NULL)
1508 if (acb->qiov->niov > 1)
1509 qemu_vfree(acb->orig_buf);
1510 acb->common.cb(acb->common.opaque, ret);
1511 qemu_aio_release(acb);
1514 static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
1515 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1516 BlockDriverCompletionFunc *cb, void *opaque)
1518 BDRVQcowState *s = bs->opaque;
1521 s->cluster_cache_offset = -1; /* disable compressed cache */
1523 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1527 qcow_aio_write_cb(acb, 0);
1528 return &acb->common;
1531 static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
1533 QCowAIOCB *acb = (QCowAIOCB *)blockacb;
1535 bdrv_aio_cancel(acb->hd_aiocb);
1536 qemu_aio_release(acb);
1539 static void qcow_close(BlockDriverState *bs)
1541 BDRVQcowState *s = bs->opaque;
1542 qemu_free(s->l1_table);
1543 qemu_free(s->l2_cache);
1544 qemu_free(s->cluster_cache);
1545 qemu_free(s->cluster_data);
1550 /* XXX: use std qcow open function ? */
1551 typedef struct QCowCreateState {
1554 uint16_t *refcount_block;
1555 uint64_t *refcount_table;
1556 int64_t l1_table_offset;
1557 int64_t refcount_table_offset;
1558 int64_t refcount_block_offset;
1561 static void create_refcount_update(QCowCreateState *s,
1562 int64_t offset, int64_t size)
1565 int64_t start, last, cluster_offset;
1568 start = offset & ~(s->cluster_size - 1);
1569 last = (offset + size - 1) & ~(s->cluster_size - 1);
1570 for(cluster_offset = start; cluster_offset <= last;
1571 cluster_offset += s->cluster_size) {
1572 p = &s->refcount_block[cluster_offset >> s->cluster_bits];
1573 refcount = be16_to_cpu(*p);
1575 *p = cpu_to_be16(refcount);
1579 static int qcow_create2(const char *filename, int64_t total_size,
1580 const char *backing_file, const char *backing_format,
1584 int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
1585 int ref_clusters, backing_format_len = 0;
1587 uint64_t tmp, offset;
1588 QCowCreateState s1, *s = &s1;
1589 QCowExtension ext_bf = {0, 0};
1592 memset(s, 0, sizeof(*s));
1594 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1597 memset(&header, 0, sizeof(header));
1598 header.magic = cpu_to_be32(QCOW_MAGIC);
1599 header.version = cpu_to_be32(QCOW_VERSION);
1600 header.size = cpu_to_be64(total_size * 512);
1601 header_size = sizeof(header);
1602 backing_filename_len = 0;
1604 if (backing_format) {
1605 ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
1606 backing_format_len = strlen(backing_format);
1607 ext_bf.len = (backing_format_len + 7) & ~7;
1608 header_size += ((sizeof(ext_bf) + ext_bf.len + 7) & ~7);
1610 header.backing_file_offset = cpu_to_be64(header_size);
1611 backing_filename_len = strlen(backing_file);
1612 header.backing_file_size = cpu_to_be32(backing_filename_len);
1613 header_size += backing_filename_len;
1615 s->cluster_bits = 12; /* 4 KB clusters */
1616 s->cluster_size = 1 << s->cluster_bits;
1617 header.cluster_bits = cpu_to_be32(s->cluster_bits);
1618 header_size = (header_size + 7) & ~7;
1619 if (flags & BLOCK_FLAG_ENCRYPT) {
1620 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1622 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1624 l2_bits = s->cluster_bits - 3;
1625 shift = s->cluster_bits + l2_bits;
1626 l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
1627 offset = align_offset(header_size, s->cluster_size);
1628 s->l1_table_offset = offset;
1629 header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
1630 header.l1_size = cpu_to_be32(l1_size);
1631 offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
1633 s->refcount_table = qemu_mallocz(s->cluster_size);
1635 s->refcount_table_offset = offset;
1636 header.refcount_table_offset = cpu_to_be64(offset);
1637 header.refcount_table_clusters = cpu_to_be32(1);
1638 offset += s->cluster_size;
1639 s->refcount_block_offset = offset;
1641 /* count how many refcount blocks needed */
1642 tmp = offset >> s->cluster_bits;
1643 ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
1644 for (i=0; i < ref_clusters; i++) {
1645 s->refcount_table[i] = cpu_to_be64(offset);
1646 offset += s->cluster_size;
1649 s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
1651 /* update refcounts */
1652 create_refcount_update(s, 0, header_size);
1653 create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
1654 create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
1655 create_refcount_update(s, s->refcount_block_offset, ref_clusters * s->cluster_size);
1657 /* write all the data */
1658 write(fd, &header, sizeof(header));
1660 if (backing_format_len) {
1662 int d = ext_bf.len - backing_format_len;
1664 memset(zero, 0, sizeof(zero));
1665 cpu_to_be32s(&ext_bf.magic);
1666 cpu_to_be32s(&ext_bf.len);
1667 write(fd, &ext_bf, sizeof(ext_bf));
1668 write(fd, backing_format, backing_format_len);
1673 write(fd, backing_file, backing_filename_len);
1675 lseek(fd, s->l1_table_offset, SEEK_SET);
1677 for(i = 0;i < l1_size; i++) {
1678 write(fd, &tmp, sizeof(tmp));
1680 lseek(fd, s->refcount_table_offset, SEEK_SET);
1681 write(fd, s->refcount_table, s->cluster_size);
1683 lseek(fd, s->refcount_block_offset, SEEK_SET);
1684 write(fd, s->refcount_block, ref_clusters * s->cluster_size);
1686 qemu_free(s->refcount_table);
1687 qemu_free(s->refcount_block);
1692 static int qcow_create(const char *filename, int64_t total_size,
1693 const char *backing_file, int flags)
1695 return qcow_create2(filename, total_size, backing_file, NULL, flags);
1698 static int qcow_make_empty(BlockDriverState *bs)
1701 /* XXX: not correct */
1702 BDRVQcowState *s = bs->opaque;
1703 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1706 memset(s->l1_table, 0, l1_length);
1707 if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1709 ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1718 /* XXX: put compressed sectors first, then all the cluster aligned
1719 tables to avoid losing bytes in alignment */
1720 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1721 const uint8_t *buf, int nb_sectors)
1723 BDRVQcowState *s = bs->opaque;
1727 uint64_t cluster_offset;
1729 if (nb_sectors == 0) {
1730 /* align end of file to a sector boundary to ease reading with
1731 sector based I/Os */
1732 cluster_offset = bdrv_getlength(s->hd);
1733 cluster_offset = (cluster_offset + 511) & ~511;
1734 bdrv_truncate(s->hd, cluster_offset);
1738 if (nb_sectors != s->cluster_sectors)
1741 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1743 /* best compression, small window, no zlib header */
1744 memset(&strm, 0, sizeof(strm));
1745 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1747 9, Z_DEFAULT_STRATEGY);
1753 strm.avail_in = s->cluster_size;
1754 strm.next_in = (uint8_t *)buf;
1755 strm.avail_out = s->cluster_size;
1756 strm.next_out = out_buf;
1758 ret = deflate(&strm, Z_FINISH);
1759 if (ret != Z_STREAM_END && ret != Z_OK) {
1764 out_len = strm.next_out - out_buf;
1768 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1769 /* could not compress: write normal cluster */
1770 qcow_write(bs, sector_num, buf, s->cluster_sectors);
1772 cluster_offset = alloc_compressed_cluster_offset(bs, sector_num << 9,
1774 if (!cluster_offset)
1776 cluster_offset &= s->cluster_offset_mask;
1777 if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1787 static void qcow_flush(BlockDriverState *bs)
1789 BDRVQcowState *s = bs->opaque;
1793 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1795 BDRVQcowState *s = bs->opaque;
1796 bdi->cluster_size = s->cluster_size;
1797 bdi->vm_state_offset = (int64_t)s->l1_vm_state_index <<
1798 (s->cluster_bits + s->l2_bits);
1802 /*********************************************************/
1803 /* snapshot support */
1805 /* update the refcounts of snapshots and the copied flag */
1806 static int update_snapshot_refcount(BlockDriverState *bs,
1807 int64_t l1_table_offset,
1811 BDRVQcowState *s = bs->opaque;
1812 uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;
1813 int64_t old_offset, old_l2_offset;
1814 int l2_size, i, j, l1_modified, l2_modified, nb_csectors, refcount;
1820 l1_size2 = l1_size * sizeof(uint64_t);
1822 if (l1_table_offset != s->l1_table_offset) {
1823 l1_table = qemu_malloc(l1_size2);
1825 if (bdrv_pread(s->hd, l1_table_offset,
1826 l1_table, l1_size2) != l1_size2)
1828 for(i = 0;i < l1_size; i++)
1829 be64_to_cpus(&l1_table[i]);
1831 assert(l1_size == s->l1_size);
1832 l1_table = s->l1_table;
1836 l2_size = s->l2_size * sizeof(uint64_t);
1837 l2_table = qemu_malloc(l2_size);
1839 for(i = 0; i < l1_size; i++) {
1840 l2_offset = l1_table[i];
1842 old_l2_offset = l2_offset;
1843 l2_offset &= ~QCOW_OFLAG_COPIED;
1845 if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
1847 for(j = 0; j < s->l2_size; j++) {
1848 offset = be64_to_cpu(l2_table[j]);
1850 old_offset = offset;
1851 offset &= ~QCOW_OFLAG_COPIED;
1852 if (offset & QCOW_OFLAG_COMPRESSED) {
1853 nb_csectors = ((offset >> s->csize_shift) &
1856 update_refcount(bs, (offset & s->cluster_offset_mask) & ~511,
1857 nb_csectors * 512, addend);
1858 /* compressed clusters are never modified */
1862 refcount = update_cluster_refcount(bs, offset >> s->cluster_bits, addend);
1864 refcount = get_refcount(bs, offset >> s->cluster_bits);
1868 if (refcount == 1) {
1869 offset |= QCOW_OFLAG_COPIED;
1871 if (offset != old_offset) {
1872 l2_table[j] = cpu_to_be64(offset);
1878 if (bdrv_pwrite(s->hd,
1879 l2_offset, l2_table, l2_size) != l2_size)
1884 refcount = update_cluster_refcount(bs, l2_offset >> s->cluster_bits, addend);
1886 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1888 if (refcount == 1) {
1889 l2_offset |= QCOW_OFLAG_COPIED;
1891 if (l2_offset != old_l2_offset) {
1892 l1_table[i] = l2_offset;
1898 for(i = 0; i < l1_size; i++)
1899 cpu_to_be64s(&l1_table[i]);
1900 if (bdrv_pwrite(s->hd, l1_table_offset, l1_table,
1901 l1_size2) != l1_size2)
1903 for(i = 0; i < l1_size; i++)
1904 be64_to_cpus(&l1_table[i]);
1907 qemu_free(l1_table);
1908 qemu_free(l2_table);
1912 qemu_free(l1_table);
1913 qemu_free(l2_table);
1917 static void qcow_free_snapshots(BlockDriverState *bs)
1919 BDRVQcowState *s = bs->opaque;
1922 for(i = 0; i < s->nb_snapshots; i++) {
1923 qemu_free(s->snapshots[i].name);
1924 qemu_free(s->snapshots[i].id_str);
1926 qemu_free(s->snapshots);
1927 s->snapshots = NULL;
1928 s->nb_snapshots = 0;
1931 static int qcow_read_snapshots(BlockDriverState *bs)
1933 BDRVQcowState *s = bs->opaque;
1934 QCowSnapshotHeader h;
1936 int i, id_str_size, name_size;
1938 uint32_t extra_data_size;
1940 if (!s->nb_snapshots) {
1941 s->snapshots = NULL;
1942 s->snapshots_size = 0;
1946 offset = s->snapshots_offset;
1947 s->snapshots = qemu_mallocz(s->nb_snapshots * sizeof(QCowSnapshot));
1948 for(i = 0; i < s->nb_snapshots; i++) {
1949 offset = align_offset(offset, 8);
1950 if (bdrv_pread(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1952 offset += sizeof(h);
1953 sn = s->snapshots + i;
1954 sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
1955 sn->l1_size = be32_to_cpu(h.l1_size);
1956 sn->vm_state_size = be32_to_cpu(h.vm_state_size);
1957 sn->date_sec = be32_to_cpu(h.date_sec);
1958 sn->date_nsec = be32_to_cpu(h.date_nsec);
1959 sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
1960 extra_data_size = be32_to_cpu(h.extra_data_size);
1962 id_str_size = be16_to_cpu(h.id_str_size);
1963 name_size = be16_to_cpu(h.name_size);
1965 offset += extra_data_size;
1967 sn->id_str = qemu_malloc(id_str_size + 1);
1968 if (bdrv_pread(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1970 offset += id_str_size;
1971 sn->id_str[id_str_size] = '\0';
1973 sn->name = qemu_malloc(name_size + 1);
1974 if (bdrv_pread(s->hd, offset, sn->name, name_size) != name_size)
1976 offset += name_size;
1977 sn->name[name_size] = '\0';
1979 s->snapshots_size = offset - s->snapshots_offset;
1982 qcow_free_snapshots(bs);
1986 /* add at the end of the file a new list of snapshots */
1987 static int qcow_write_snapshots(BlockDriverState *bs)
1989 BDRVQcowState *s = bs->opaque;
1991 QCowSnapshotHeader h;
1992 int i, name_size, id_str_size, snapshots_size;
1995 int64_t offset, snapshots_offset;
1997 /* compute the size of the snapshots */
1999 for(i = 0; i < s->nb_snapshots; i++) {
2000 sn = s->snapshots + i;
2001 offset = align_offset(offset, 8);
2002 offset += sizeof(h);
2003 offset += strlen(sn->id_str);
2004 offset += strlen(sn->name);
2006 snapshots_size = offset;
2008 snapshots_offset = alloc_clusters(bs, snapshots_size);
2009 offset = snapshots_offset;
2011 for(i = 0; i < s->nb_snapshots; i++) {
2012 sn = s->snapshots + i;
2013 memset(&h, 0, sizeof(h));
2014 h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);
2015 h.l1_size = cpu_to_be32(sn->l1_size);
2016 h.vm_state_size = cpu_to_be32(sn->vm_state_size);
2017 h.date_sec = cpu_to_be32(sn->date_sec);
2018 h.date_nsec = cpu_to_be32(sn->date_nsec);
2019 h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);
2021 id_str_size = strlen(sn->id_str);
2022 name_size = strlen(sn->name);
2023 h.id_str_size = cpu_to_be16(id_str_size);
2024 h.name_size = cpu_to_be16(name_size);
2025 offset = align_offset(offset, 8);
2026 if (bdrv_pwrite(s->hd, offset, &h, sizeof(h)) != sizeof(h))
2028 offset += sizeof(h);
2029 if (bdrv_pwrite(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
2031 offset += id_str_size;
2032 if (bdrv_pwrite(s->hd, offset, sn->name, name_size) != name_size)
2034 offset += name_size;
2037 /* update the various header fields */
2038 data64 = cpu_to_be64(snapshots_offset);
2039 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, snapshots_offset),
2040 &data64, sizeof(data64)) != sizeof(data64))
2042 data32 = cpu_to_be32(s->nb_snapshots);
2043 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, nb_snapshots),
2044 &data32, sizeof(data32)) != sizeof(data32))
2047 /* free the old snapshot table */
2048 free_clusters(bs, s->snapshots_offset, s->snapshots_size);
2049 s->snapshots_offset = snapshots_offset;
2050 s->snapshots_size = snapshots_size;
2056 static void find_new_snapshot_id(BlockDriverState *bs,
2057 char *id_str, int id_str_size)
2059 BDRVQcowState *s = bs->opaque;
2061 int i, id, id_max = 0;
2063 for(i = 0; i < s->nb_snapshots; i++) {
2064 sn = s->snapshots + i;
2065 id = strtoul(sn->id_str, NULL, 10);
2069 snprintf(id_str, id_str_size, "%d", id_max + 1);
2072 static int find_snapshot_by_id(BlockDriverState *bs, const char *id_str)
2074 BDRVQcowState *s = bs->opaque;
2077 for(i = 0; i < s->nb_snapshots; i++) {
2078 if (!strcmp(s->snapshots[i].id_str, id_str))
2084 static int find_snapshot_by_id_or_name(BlockDriverState *bs, const char *name)
2086 BDRVQcowState *s = bs->opaque;
2089 ret = find_snapshot_by_id(bs, name);
2092 for(i = 0; i < s->nb_snapshots; i++) {
2093 if (!strcmp(s->snapshots[i].name, name))
2099 /* if no id is provided, a new one is constructed */
2100 static int qcow_snapshot_create(BlockDriverState *bs,
2101 QEMUSnapshotInfo *sn_info)
2103 BDRVQcowState *s = bs->opaque;
2104 QCowSnapshot *snapshots1, sn1, *sn = &sn1;
2106 uint64_t *l1_table = NULL;
2108 memset(sn, 0, sizeof(*sn));
2110 if (sn_info->id_str[0] == '\0') {
2111 /* compute a new id */
2112 find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));
2115 /* check that the ID is unique */
2116 if (find_snapshot_by_id(bs, sn_info->id_str) >= 0)
2119 sn->id_str = qemu_strdup(sn_info->id_str);
2122 sn->name = qemu_strdup(sn_info->name);
2125 sn->vm_state_size = sn_info->vm_state_size;
2126 sn->date_sec = sn_info->date_sec;
2127 sn->date_nsec = sn_info->date_nsec;
2128 sn->vm_clock_nsec = sn_info->vm_clock_nsec;
2130 ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);
2134 /* create the L1 table of the snapshot */
2135 sn->l1_table_offset = alloc_clusters(bs, s->l1_size * sizeof(uint64_t));
2136 sn->l1_size = s->l1_size;
2138 l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
2139 for(i = 0; i < s->l1_size; i++) {
2140 l1_table[i] = cpu_to_be64(s->l1_table[i]);
2142 if (bdrv_pwrite(s->hd, sn->l1_table_offset,
2143 l1_table, s->l1_size * sizeof(uint64_t)) !=
2144 (s->l1_size * sizeof(uint64_t)))
2146 qemu_free(l1_table);
2149 snapshots1 = qemu_malloc((s->nb_snapshots + 1) * sizeof(QCowSnapshot));
2151 memcpy(snapshots1, s->snapshots, s->nb_snapshots * sizeof(QCowSnapshot));
2152 qemu_free(s->snapshots);
2154 s->snapshots = snapshots1;
2155 s->snapshots[s->nb_snapshots++] = *sn;
2157 if (qcow_write_snapshots(bs) < 0)
2160 check_refcounts(bs);
2164 qemu_free(sn->name);
2165 qemu_free(l1_table);
2169 /* copy the snapshot 'snapshot_name' into the current disk image */
2170 static int qcow_snapshot_goto(BlockDriverState *bs,
2171 const char *snapshot_id)
2173 BDRVQcowState *s = bs->opaque;
2175 int i, snapshot_index, l1_size2;
2177 snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2178 if (snapshot_index < 0)
2180 sn = &s->snapshots[snapshot_index];
2182 if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, -1) < 0)
2185 if (grow_l1_table(bs, sn->l1_size) < 0)
2188 s->l1_size = sn->l1_size;
2189 l1_size2 = s->l1_size * sizeof(uint64_t);
2190 /* copy the snapshot l1 table to the current l1 table */
2191 if (bdrv_pread(s->hd, sn->l1_table_offset,
2192 s->l1_table, l1_size2) != l1_size2)
2194 if (bdrv_pwrite(s->hd, s->l1_table_offset,
2195 s->l1_table, l1_size2) != l1_size2)
2197 for(i = 0;i < s->l1_size; i++) {
2198 be64_to_cpus(&s->l1_table[i]);
2201 if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1) < 0)
2205 check_refcounts(bs);
2212 static int qcow_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2214 BDRVQcowState *s = bs->opaque;
2216 int snapshot_index, ret;
2218 snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2219 if (snapshot_index < 0)
2221 sn = &s->snapshots[snapshot_index];
2223 ret = update_snapshot_refcount(bs, sn->l1_table_offset, sn->l1_size, -1);
2226 /* must update the copied flag on the current cluster offsets */
2227 ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
2230 free_clusters(bs, sn->l1_table_offset, sn->l1_size * sizeof(uint64_t));
2232 qemu_free(sn->id_str);
2233 qemu_free(sn->name);
2234 memmove(sn, sn + 1, (s->nb_snapshots - snapshot_index - 1) * sizeof(*sn));
2236 ret = qcow_write_snapshots(bs);
2238 /* XXX: restore snapshot if error ? */
2242 check_refcounts(bs);
2247 static int qcow_snapshot_list(BlockDriverState *bs,
2248 QEMUSnapshotInfo **psn_tab)
2250 BDRVQcowState *s = bs->opaque;
2251 QEMUSnapshotInfo *sn_tab, *sn_info;
2255 sn_tab = qemu_mallocz(s->nb_snapshots * sizeof(QEMUSnapshotInfo));
2256 for(i = 0; i < s->nb_snapshots; i++) {
2257 sn_info = sn_tab + i;
2258 sn = s->snapshots + i;
2259 pstrcpy(sn_info->id_str, sizeof(sn_info->id_str),
2261 pstrcpy(sn_info->name, sizeof(sn_info->name),
2263 sn_info->vm_state_size = sn->vm_state_size;
2264 sn_info->date_sec = sn->date_sec;
2265 sn_info->date_nsec = sn->date_nsec;
2266 sn_info->vm_clock_nsec = sn->vm_clock_nsec;
2269 return s->nb_snapshots;
2272 /*********************************************************/
2273 /* refcount handling */
2275 static int refcount_init(BlockDriverState *bs)
2277 BDRVQcowState *s = bs->opaque;
2278 int ret, refcount_table_size2, i;
2280 s->refcount_block_cache = qemu_malloc(s->cluster_size);
2281 refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
2282 s->refcount_table = qemu_malloc(refcount_table_size2);
2283 if (s->refcount_table_size > 0) {
2284 ret = bdrv_pread(s->hd, s->refcount_table_offset,
2285 s->refcount_table, refcount_table_size2);
2286 if (ret != refcount_table_size2)
2288 for(i = 0; i < s->refcount_table_size; i++)
2289 be64_to_cpus(&s->refcount_table[i]);
2296 static void refcount_close(BlockDriverState *bs)
2298 BDRVQcowState *s = bs->opaque;
2299 qemu_free(s->refcount_block_cache);
2300 qemu_free(s->refcount_table);
2304 static int load_refcount_block(BlockDriverState *bs,
2305 int64_t refcount_block_offset)
2307 BDRVQcowState *s = bs->opaque;
2309 ret = bdrv_pread(s->hd, refcount_block_offset, s->refcount_block_cache,
2311 if (ret != s->cluster_size)
2313 s->refcount_block_cache_offset = refcount_block_offset;
2317 static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
2319 BDRVQcowState *s = bs->opaque;
2320 int refcount_table_index, block_index;
2321 int64_t refcount_block_offset;
2323 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2324 if (refcount_table_index >= s->refcount_table_size)
2326 refcount_block_offset = s->refcount_table[refcount_table_index];
2327 if (!refcount_block_offset)
2329 if (refcount_block_offset != s->refcount_block_cache_offset) {
2330 /* better than nothing: return allocated if read error */
2331 if (load_refcount_block(bs, refcount_block_offset) < 0)
2334 block_index = cluster_index &
2335 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2336 return be16_to_cpu(s->refcount_block_cache[block_index]);
2339 /* return < 0 if error */
2340 static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)
2342 BDRVQcowState *s = bs->opaque;
2345 nb_clusters = size_to_clusters(s, size);
2347 for(i = 0; i < nb_clusters; i++) {
2348 int64_t i = s->free_cluster_index++;
2349 if (get_refcount(bs, i) != 0)
2353 printf("alloc_clusters: size=%lld -> %lld\n",
2355 (s->free_cluster_index - nb_clusters) << s->cluster_bits);
2357 return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
2360 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size)
2364 offset = alloc_clusters_noref(bs, size);
2365 update_refcount(bs, offset, size, 1);
2369 /* only used to allocate compressed sectors. We try to allocate
2370 contiguous sectors. size must be <= cluster_size */
2371 static int64_t alloc_bytes(BlockDriverState *bs, int size)
2373 BDRVQcowState *s = bs->opaque;
2374 int64_t offset, cluster_offset;
2375 int free_in_cluster;
2377 assert(size > 0 && size <= s->cluster_size);
2378 if (s->free_byte_offset == 0) {
2379 s->free_byte_offset = alloc_clusters(bs, s->cluster_size);
2382 free_in_cluster = s->cluster_size -
2383 (s->free_byte_offset & (s->cluster_size - 1));
2384 if (size <= free_in_cluster) {
2385 /* enough space in current cluster */
2386 offset = s->free_byte_offset;
2387 s->free_byte_offset += size;
2388 free_in_cluster -= size;
2389 if (free_in_cluster == 0)
2390 s->free_byte_offset = 0;
2391 if ((offset & (s->cluster_size - 1)) != 0)
2392 update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2394 offset = alloc_clusters(bs, s->cluster_size);
2395 cluster_offset = s->free_byte_offset & ~(s->cluster_size - 1);
2396 if ((cluster_offset + s->cluster_size) == offset) {
2397 /* we are lucky: contiguous data */
2398 offset = s->free_byte_offset;
2399 update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2400 s->free_byte_offset += size;
2402 s->free_byte_offset = offset;
2409 static void free_clusters(BlockDriverState *bs,
2410 int64_t offset, int64_t size)
2412 update_refcount(bs, offset, size, -1);
2415 static int grow_refcount_table(BlockDriverState *bs, int min_size)
2417 BDRVQcowState *s = bs->opaque;
2418 int new_table_size, new_table_size2, refcount_table_clusters, i, ret;
2419 uint64_t *new_table;
2420 int64_t table_offset;
2423 int64_t old_table_offset;
2425 if (min_size <= s->refcount_table_size)
2427 /* compute new table size */
2428 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2430 if (refcount_table_clusters == 0) {
2431 refcount_table_clusters = 1;
2433 refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
2435 new_table_size = refcount_table_clusters << (s->cluster_bits - 3);
2436 if (min_size <= new_table_size)
2440 printf("grow_refcount_table from %d to %d\n",
2441 s->refcount_table_size,
2444 new_table_size2 = new_table_size * sizeof(uint64_t);
2445 new_table = qemu_mallocz(new_table_size2);
2446 memcpy(new_table, s->refcount_table,
2447 s->refcount_table_size * sizeof(uint64_t));
2448 for(i = 0; i < s->refcount_table_size; i++)
2449 cpu_to_be64s(&new_table[i]);
2450 /* Note: we cannot update the refcount now to avoid recursion */
2451 table_offset = alloc_clusters_noref(bs, new_table_size2);
2452 ret = bdrv_pwrite(s->hd, table_offset, new_table, new_table_size2);
2453 if (ret != new_table_size2)
2455 for(i = 0; i < s->refcount_table_size; i++)
2456 be64_to_cpus(&new_table[i]);
2458 cpu_to_be64w((uint64_t*)data, table_offset);
2459 cpu_to_be32w((uint32_t*)(data + 8), refcount_table_clusters);
2460 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, refcount_table_offset),
2461 data, sizeof(data)) != sizeof(data))
2463 qemu_free(s->refcount_table);
2464 old_table_offset = s->refcount_table_offset;
2465 old_table_size = s->refcount_table_size;
2466 s->refcount_table = new_table;
2467 s->refcount_table_size = new_table_size;
2468 s->refcount_table_offset = table_offset;
2470 update_refcount(bs, table_offset, new_table_size2, 1);
2471 free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));
2474 free_clusters(bs, table_offset, new_table_size2);
2475 qemu_free(new_table);
2479 /* addend must be 1 or -1 */
2480 /* XXX: cache several refcount block clusters ? */
2481 static int update_cluster_refcount(BlockDriverState *bs,
2482 int64_t cluster_index,
2485 BDRVQcowState *s = bs->opaque;
2486 int64_t offset, refcount_block_offset;
2487 int ret, refcount_table_index, block_index, refcount;
2490 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2491 if (refcount_table_index >= s->refcount_table_size) {
2494 ret = grow_refcount_table(bs, refcount_table_index + 1);
2498 refcount_block_offset = s->refcount_table[refcount_table_index];
2499 if (!refcount_block_offset) {
2502 /* create a new refcount block */
2503 /* Note: we cannot update the refcount now to avoid recursion */
2504 offset = alloc_clusters_noref(bs, s->cluster_size);
2505 memset(s->refcount_block_cache, 0, s->cluster_size);
2506 ret = bdrv_pwrite(s->hd, offset, s->refcount_block_cache, s->cluster_size);
2507 if (ret != s->cluster_size)
2509 s->refcount_table[refcount_table_index] = offset;
2510 data64 = cpu_to_be64(offset);
2511 ret = bdrv_pwrite(s->hd, s->refcount_table_offset +
2512 refcount_table_index * sizeof(uint64_t),
2513 &data64, sizeof(data64));
2514 if (ret != sizeof(data64))
2517 refcount_block_offset = offset;
2518 s->refcount_block_cache_offset = offset;
2519 update_refcount(bs, offset, s->cluster_size, 1);
2521 if (refcount_block_offset != s->refcount_block_cache_offset) {
2522 if (load_refcount_block(bs, refcount_block_offset) < 0)
2526 /* we can update the count and save it */
2527 block_index = cluster_index &
2528 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2529 refcount = be16_to_cpu(s->refcount_block_cache[block_index]);
2531 if (refcount < 0 || refcount > 0xffff)
2533 if (refcount == 0 && cluster_index < s->free_cluster_index) {
2534 s->free_cluster_index = cluster_index;
2536 s->refcount_block_cache[block_index] = cpu_to_be16(refcount);
2537 if (bdrv_pwrite(s->hd,
2538 refcount_block_offset + (block_index << REFCOUNT_SHIFT),
2539 &s->refcount_block_cache[block_index], 2) != 2)
2544 static void update_refcount(BlockDriverState *bs,
2545 int64_t offset, int64_t length,
2548 BDRVQcowState *s = bs->opaque;
2549 int64_t start, last, cluster_offset;
2552 printf("update_refcount: offset=%lld size=%lld addend=%d\n",
2553 offset, length, addend);
2557 start = offset & ~(s->cluster_size - 1);
2558 last = (offset + length - 1) & ~(s->cluster_size - 1);
2559 for(cluster_offset = start; cluster_offset <= last;
2560 cluster_offset += s->cluster_size) {
2561 update_cluster_refcount(bs, cluster_offset >> s->cluster_bits, addend);
2566 * Increases the refcount for a range of clusters in a given refcount table.
2567 * This is used to construct a temporary refcount table out of L1 and L2 tables
2568 * which can be compared the the refcount table saved in the image.
2570 * Returns the number of errors in the image that were found
2572 static int inc_refcounts(BlockDriverState *bs,
2573 uint16_t *refcount_table,
2574 int refcount_table_size,
2575 int64_t offset, int64_t size)
2577 BDRVQcowState *s = bs->opaque;
2578 int64_t start, last, cluster_offset;
2585 start = offset & ~(s->cluster_size - 1);
2586 last = (offset + size - 1) & ~(s->cluster_size - 1);
2587 for(cluster_offset = start; cluster_offset <= last;
2588 cluster_offset += s->cluster_size) {
2589 k = cluster_offset >> s->cluster_bits;
2590 if (k < 0 || k >= refcount_table_size) {
2591 fprintf(stderr, "ERROR: invalid cluster offset=0x%" PRIx64 "\n",
2595 if (++refcount_table[k] == 0) {
2596 fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64
2597 "\n", cluster_offset);
2607 * Increases the refcount in the given refcount table for the all clusters
2608 * referenced in the L2 table. While doing so, performs some checks on L2
2611 * Returns the number of errors found by the checks or -errno if an internal
2614 static int check_refcounts_l2(BlockDriverState *bs,
2615 uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,
2618 BDRVQcowState *s = bs->opaque;
2619 uint64_t *l2_table, offset;
2620 int i, l2_size, nb_csectors, refcount;
2623 /* Read L2 table from disk */
2624 l2_size = s->l2_size * sizeof(uint64_t);
2625 l2_table = qemu_malloc(l2_size);
2627 if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
2630 /* Do the actual checks */
2631 for(i = 0; i < s->l2_size; i++) {
2632 offset = be64_to_cpu(l2_table[i]);
2634 if (offset & QCOW_OFLAG_COMPRESSED) {
2635 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
2636 if (offset & QCOW_OFLAG_COPIED) {
2637 fprintf(stderr, "ERROR: cluster %" PRId64 ": "
2638 "copied flag must never be set for compressed "
2639 "clusters\n", offset >> s->cluster_bits);
2640 offset &= ~QCOW_OFLAG_COPIED;
2644 /* Mark cluster as used */
2645 nb_csectors = ((offset >> s->csize_shift) &
2647 offset &= s->cluster_offset_mask;
2648 errors += inc_refcounts(bs, refcount_table,
2649 refcount_table_size,
2650 offset & ~511, nb_csectors * 512);
2652 /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
2654 uint64_t entry = offset;
2655 offset &= ~QCOW_OFLAG_COPIED;
2656 refcount = get_refcount(bs, offset >> s->cluster_bits);
2657 if ((refcount == 1) != ((entry & QCOW_OFLAG_COPIED) != 0)) {
2658 fprintf(stderr, "ERROR OFLAG_COPIED: offset=%"
2659 PRIx64 " refcount=%d\n", entry, refcount);
2664 /* Mark cluster as used */
2665 offset &= ~QCOW_OFLAG_COPIED;
2666 errors += inc_refcounts(bs, refcount_table,
2667 refcount_table_size,
2668 offset, s->cluster_size);
2670 /* Correct offsets are cluster aligned */
2671 if (offset & (s->cluster_size - 1)) {
2672 fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "
2673 "properly aligned; L2 entry corrupted.\n", offset);
2680 qemu_free(l2_table);
2684 fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
2685 qemu_free(l2_table);
2690 * Increases the refcount for the L1 table, its L2 tables and all referenced
2691 * clusters in the given refcount table. While doing so, performs some checks
2692 * on L1 and L2 entries.
2694 * Returns the number of errors found by the checks or -errno if an internal
2697 static int check_refcounts_l1(BlockDriverState *bs,
2698 uint16_t *refcount_table,
2699 int refcount_table_size,
2700 int64_t l1_table_offset, int l1_size,
2703 BDRVQcowState *s = bs->opaque;
2704 uint64_t *l1_table, l2_offset, l1_size2;
2705 int i, refcount, ret;
2708 l1_size2 = l1_size * sizeof(uint64_t);
2710 /* Mark L1 table as used */
2711 errors += inc_refcounts(bs, refcount_table, refcount_table_size,
2712 l1_table_offset, l1_size2);
2714 /* Read L1 table entries from disk */
2715 l1_table = qemu_malloc(l1_size2);
2716 if (bdrv_pread(s->hd, l1_table_offset,
2717 l1_table, l1_size2) != l1_size2)
2719 for(i = 0;i < l1_size; i++)
2720 be64_to_cpus(&l1_table[i]);
2722 /* Do the actual checks */
2723 for(i = 0; i < l1_size; i++) {
2724 l2_offset = l1_table[i];
2726 /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
2728 refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED)
2729 >> s->cluster_bits);
2730 if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
2731 fprintf(stderr, "ERROR OFLAG_COPIED: l2_offset=%" PRIx64
2732 " refcount=%d\n", l2_offset, refcount);
2737 /* Mark L2 table as used */
2738 l2_offset &= ~QCOW_OFLAG_COPIED;
2739 errors += inc_refcounts(bs, refcount_table,
2740 refcount_table_size,
2744 /* L2 tables are cluster aligned */
2745 if (l2_offset & (s->cluster_size - 1)) {
2746 fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "
2747 "cluster aligned; L1 entry corrupted\n", l2_offset);
2751 /* Process and check L2 entries */
2752 ret = check_refcounts_l2(bs, refcount_table, refcount_table_size,
2753 l2_offset, check_copied);
2760 qemu_free(l1_table);
2764 fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
2765 qemu_free(l1_table);
2770 * Checks an image for refcount consistency.
2772 * Returns 0 if no errors are found, the number of errors in case the image is
2773 * detected as corrupted, and -errno when an internal error occured.
2775 static int check_refcounts(BlockDriverState *bs)
2777 BDRVQcowState *s = bs->opaque;
2779 int nb_clusters, refcount1, refcount2, i;
2781 uint16_t *refcount_table;
2782 int ret, errors = 0;
2784 size = bdrv_getlength(s->hd);
2785 nb_clusters = size_to_clusters(s, size);
2786 refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));
2789 errors += inc_refcounts(bs, refcount_table, nb_clusters,
2790 0, s->cluster_size);
2792 /* current L1 table */
2793 ret = check_refcounts_l1(bs, refcount_table, nb_clusters,
2794 s->l1_table_offset, s->l1_size, 1);
2801 for(i = 0; i < s->nb_snapshots; i++) {
2802 sn = s->snapshots + i;
2803 check_refcounts_l1(bs, refcount_table, nb_clusters,
2804 sn->l1_table_offset, sn->l1_size, 0);
2806 errors += inc_refcounts(bs, refcount_table, nb_clusters,
2807 s->snapshots_offset, s->snapshots_size);
2810 errors += inc_refcounts(bs, refcount_table, nb_clusters,
2811 s->refcount_table_offset,
2812 s->refcount_table_size * sizeof(uint64_t));
2813 for(i = 0; i < s->refcount_table_size; i++) {
2815 offset = s->refcount_table[i];
2817 errors += inc_refcounts(bs, refcount_table, nb_clusters,
2818 offset, s->cluster_size);
2822 /* compare ref counts */
2823 for(i = 0; i < nb_clusters; i++) {
2824 refcount1 = get_refcount(bs, i);
2825 refcount2 = refcount_table[i];
2826 if (refcount1 != refcount2) {
2827 fprintf(stderr, "ERROR cluster %d refcount=%d reference=%d\n",
2828 i, refcount1, refcount2);
2833 qemu_free(refcount_table);
2838 static int qcow_check(BlockDriverState *bs)
2840 return check_refcounts(bs);
2844 static void dump_refcounts(BlockDriverState *bs)
2846 BDRVQcowState *s = bs->opaque;
2847 int64_t nb_clusters, k, k1, size;
2850 size = bdrv_getlength(s->hd);
2851 nb_clusters = size_to_clusters(s, size);
2852 for(k = 0; k < nb_clusters;) {
2854 refcount = get_refcount(bs, k);
2856 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2858 printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
2863 static int qcow_put_buffer(BlockDriverState *bs, const uint8_t *buf,
2864 int64_t pos, int size)
2866 int growable = bs->growable;
2869 bdrv_pwrite(bs, pos, buf, size);
2870 bs->growable = growable;
2875 static int qcow_get_buffer(BlockDriverState *bs, uint8_t *buf,
2876 int64_t pos, int size)
2878 int growable = bs->growable;
2882 ret = bdrv_pread(bs, pos, buf, size);
2883 bs->growable = growable;
2888 BlockDriver bdrv_qcow2 = {
2889 .format_name = "qcow2",
2890 .instance_size = sizeof(BDRVQcowState),
2891 .bdrv_probe = qcow_probe,
2892 .bdrv_open = qcow_open,
2893 .bdrv_close = qcow_close,
2894 .bdrv_create = qcow_create,
2895 .bdrv_flush = qcow_flush,
2896 .bdrv_is_allocated = qcow_is_allocated,
2897 .bdrv_set_key = qcow_set_key,
2898 .bdrv_make_empty = qcow_make_empty,
2900 .bdrv_aio_readv = qcow_aio_readv,
2901 .bdrv_aio_writev = qcow_aio_writev,
2902 .bdrv_aio_cancel = qcow_aio_cancel,
2903 .aiocb_size = sizeof(QCowAIOCB),
2904 .bdrv_write_compressed = qcow_write_compressed,
2906 .bdrv_snapshot_create = qcow_snapshot_create,
2907 .bdrv_snapshot_goto = qcow_snapshot_goto,
2908 .bdrv_snapshot_delete = qcow_snapshot_delete,
2909 .bdrv_snapshot_list = qcow_snapshot_list,
2910 .bdrv_get_info = qcow_get_info,
2912 .bdrv_put_buffer = qcow_put_buffer,
2913 .bdrv_get_buffer = qcow_get_buffer,
2915 .bdrv_create2 = qcow_create2,
2916 .bdrv_check = qcow_check,