Merge branch 'stable_0_10' of git://git.sv.gnu.org/qemu into maint/2.6.30
[qemu-kvm/fedora.git] / block-qcow2.c
blob74a0dfa1569418fb5a04e17eb4046b331c2441fb
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 <zlib.h>
27 #include "aes.h"
28 #include <assert.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
40 snapshots.
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.
46 //#define DEBUG_ALLOC
47 //#define DEBUG_ALLOC2
49 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
50 #define QCOW_VERSION 2
52 #define QCOW_CRYPT_NONE 0
53 #define QCOW_CRYPT_AES 1
55 #define QCOW_MAX_CRYPT_CLUSTERS 32
57 /* indicate that the refcount of the referenced cluster is exactly one. */
58 #define QCOW_OFLAG_COPIED (1LL << 63)
59 /* indicate that the cluster is compressed (they never have the copied flag) */
60 #define QCOW_OFLAG_COMPRESSED (1LL << 62)
62 #define REFCOUNT_SHIFT 1 /* refcount size is 2 bytes */
64 typedef struct QCowHeader {
65 uint32_t magic;
66 uint32_t version;
67 uint64_t backing_file_offset;
68 uint32_t backing_file_size;
69 uint32_t cluster_bits;
70 uint64_t size; /* in bytes */
71 uint32_t crypt_method;
72 uint32_t l1_size; /* XXX: save number of clusters instead ? */
73 uint64_t l1_table_offset;
74 uint64_t refcount_table_offset;
75 uint32_t refcount_table_clusters;
76 uint32_t nb_snapshots;
77 uint64_t snapshots_offset;
78 } QCowHeader;
80 typedef struct __attribute__((packed)) QCowSnapshotHeader {
81 /* header is 8 byte aligned */
82 uint64_t l1_table_offset;
84 uint32_t l1_size;
85 uint16_t id_str_size;
86 uint16_t name_size;
88 uint32_t date_sec;
89 uint32_t date_nsec;
91 uint64_t vm_clock_nsec;
93 uint32_t vm_state_size;
94 uint32_t extra_data_size; /* for extension */
95 /* extra data follows */
96 /* id_str follows */
97 /* name follows */
98 } QCowSnapshotHeader;
100 #define L2_CACHE_SIZE 16
102 typedef struct QCowSnapshot {
103 uint64_t l1_table_offset;
104 uint32_t l1_size;
105 char *id_str;
106 char *name;
107 uint32_t vm_state_size;
108 uint32_t date_sec;
109 uint32_t date_nsec;
110 uint64_t vm_clock_nsec;
111 } QCowSnapshot;
113 typedef struct BDRVQcowState {
114 BlockDriverState *hd;
115 int cluster_bits;
116 int cluster_size;
117 int cluster_sectors;
118 int l2_bits;
119 int l2_size;
120 int l1_size;
121 int l1_vm_state_index;
122 int csize_shift;
123 int csize_mask;
124 uint64_t cluster_offset_mask;
125 uint64_t l1_table_offset;
126 uint64_t *l1_table;
127 uint64_t *l2_cache;
128 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
129 uint32_t l2_cache_counts[L2_CACHE_SIZE];
130 uint8_t *cluster_cache;
131 uint8_t *cluster_data;
132 uint64_t cluster_cache_offset;
134 uint64_t *refcount_table;
135 uint64_t refcount_table_offset;
136 uint32_t refcount_table_size;
137 uint64_t refcount_block_cache_offset;
138 uint16_t *refcount_block_cache;
139 int64_t free_cluster_index;
140 int64_t free_byte_offset;
142 uint32_t crypt_method; /* current crypt method, 0 if no key yet */
143 uint32_t crypt_method_header;
144 AES_KEY aes_encrypt_key;
145 AES_KEY aes_decrypt_key;
146 uint64_t snapshots_offset;
147 int snapshots_size;
148 int nb_snapshots;
149 QCowSnapshot *snapshots;
150 } BDRVQcowState;
152 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset);
153 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
154 uint8_t *buf, int nb_sectors);
155 static int qcow_read_snapshots(BlockDriverState *bs);
156 static void qcow_free_snapshots(BlockDriverState *bs);
157 static int refcount_init(BlockDriverState *bs);
158 static void refcount_close(BlockDriverState *bs);
159 static int get_refcount(BlockDriverState *bs, int64_t cluster_index);
160 static int update_cluster_refcount(BlockDriverState *bs,
161 int64_t cluster_index,
162 int addend);
163 static void update_refcount(BlockDriverState *bs,
164 int64_t offset, int64_t length,
165 int addend);
166 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size);
167 static int64_t alloc_bytes(BlockDriverState *bs, int size);
168 static void free_clusters(BlockDriverState *bs,
169 int64_t offset, int64_t size);
170 #ifdef DEBUG_ALLOC
171 static void check_refcounts(BlockDriverState *bs);
172 #endif
174 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
176 const QCowHeader *cow_header = (const void *)buf;
178 if (buf_size >= sizeof(QCowHeader) &&
179 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
180 be32_to_cpu(cow_header->version) == QCOW_VERSION)
181 return 100;
182 else
183 return 0;
186 static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
188 BDRVQcowState *s = bs->opaque;
189 int len, i, shift, ret;
190 QCowHeader header;
192 /* Performance is terrible right now with cache=writethrough due mainly
193 * to reference count updates. If the user does not explicitly specify
194 * a caching type, force to writeback caching.
196 if ((flags & BDRV_O_CACHE_DEF)) {
197 flags |= BDRV_O_CACHE_WB;
198 flags &= ~BDRV_O_CACHE_DEF;
200 ret = bdrv_file_open(&s->hd, filename, flags);
201 if (ret < 0)
202 return ret;
203 if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
204 goto fail;
205 be32_to_cpus(&header.magic);
206 be32_to_cpus(&header.version);
207 be64_to_cpus(&header.backing_file_offset);
208 be32_to_cpus(&header.backing_file_size);
209 be64_to_cpus(&header.size);
210 be32_to_cpus(&header.cluster_bits);
211 be32_to_cpus(&header.crypt_method);
212 be64_to_cpus(&header.l1_table_offset);
213 be32_to_cpus(&header.l1_size);
214 be64_to_cpus(&header.refcount_table_offset);
215 be32_to_cpus(&header.refcount_table_clusters);
216 be64_to_cpus(&header.snapshots_offset);
217 be32_to_cpus(&header.nb_snapshots);
219 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
220 goto fail;
221 if (header.size <= 1 ||
222 header.cluster_bits < 9 ||
223 header.cluster_bits > 16)
224 goto fail;
225 if (header.crypt_method > QCOW_CRYPT_AES)
226 goto fail;
227 s->crypt_method_header = header.crypt_method;
228 if (s->crypt_method_header)
229 bs->encrypted = 1;
230 s->cluster_bits = header.cluster_bits;
231 s->cluster_size = 1 << s->cluster_bits;
232 s->cluster_sectors = 1 << (s->cluster_bits - 9);
233 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
234 s->l2_size = 1 << s->l2_bits;
235 bs->total_sectors = header.size / 512;
236 s->csize_shift = (62 - (s->cluster_bits - 8));
237 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
238 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
239 s->refcount_table_offset = header.refcount_table_offset;
240 s->refcount_table_size =
241 header.refcount_table_clusters << (s->cluster_bits - 3);
243 s->snapshots_offset = header.snapshots_offset;
244 s->nb_snapshots = header.nb_snapshots;
246 /* read the level 1 table */
247 s->l1_size = header.l1_size;
248 shift = s->cluster_bits + s->l2_bits;
249 s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
250 /* the L1 table must contain at least enough entries to put
251 header.size bytes */
252 if (s->l1_size < s->l1_vm_state_index)
253 goto fail;
254 s->l1_table_offset = header.l1_table_offset;
255 s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
256 if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
257 s->l1_size * sizeof(uint64_t))
258 goto fail;
259 for(i = 0;i < s->l1_size; i++) {
260 be64_to_cpus(&s->l1_table[i]);
262 /* alloc L2 cache */
263 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
264 s->cluster_cache = qemu_malloc(s->cluster_size);
265 /* one more sector for decompressed data alignment */
266 s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
267 + 512);
268 s->cluster_cache_offset = -1;
270 if (refcount_init(bs) < 0)
271 goto fail;
273 /* read the backing file name */
274 if (header.backing_file_offset != 0) {
275 len = header.backing_file_size;
276 if (len > 1023)
277 len = 1023;
278 if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
279 goto fail;
280 bs->backing_file[len] = '\0';
282 if (qcow_read_snapshots(bs) < 0)
283 goto fail;
285 #ifdef DEBUG_ALLOC
286 check_refcounts(bs);
287 #endif
288 return 0;
290 fail:
291 qcow_free_snapshots(bs);
292 refcount_close(bs);
293 qemu_free(s->l1_table);
294 qemu_free(s->l2_cache);
295 qemu_free(s->cluster_cache);
296 qemu_free(s->cluster_data);
297 bdrv_delete(s->hd);
298 return -1;
301 static int qcow_set_key(BlockDriverState *bs, const char *key)
303 BDRVQcowState *s = bs->opaque;
304 uint8_t keybuf[16];
305 int len, i;
307 memset(keybuf, 0, 16);
308 len = strlen(key);
309 if (len > 16)
310 len = 16;
311 /* XXX: we could compress the chars to 7 bits to increase
312 entropy */
313 for(i = 0;i < len;i++) {
314 keybuf[i] = key[i];
316 s->crypt_method = s->crypt_method_header;
318 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
319 return -1;
320 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
321 return -1;
322 #if 0
323 /* test */
325 uint8_t in[16];
326 uint8_t out[16];
327 uint8_t tmp[16];
328 for(i=0;i<16;i++)
329 in[i] = i;
330 AES_encrypt(in, tmp, &s->aes_encrypt_key);
331 AES_decrypt(tmp, out, &s->aes_decrypt_key);
332 for(i = 0; i < 16; i++)
333 printf(" %02x", tmp[i]);
334 printf("\n");
335 for(i = 0; i < 16; i++)
336 printf(" %02x", out[i]);
337 printf("\n");
339 #endif
340 return 0;
343 /* The crypt function is compatible with the linux cryptoloop
344 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
345 supported */
346 static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
347 uint8_t *out_buf, const uint8_t *in_buf,
348 int nb_sectors, int enc,
349 const AES_KEY *key)
351 union {
352 uint64_t ll[2];
353 uint8_t b[16];
354 } ivec;
355 int i;
357 for(i = 0; i < nb_sectors; i++) {
358 ivec.ll[0] = cpu_to_le64(sector_num);
359 ivec.ll[1] = 0;
360 AES_cbc_encrypt(in_buf, out_buf, 512, key,
361 ivec.b, enc);
362 sector_num++;
363 in_buf += 512;
364 out_buf += 512;
368 static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,
369 uint64_t cluster_offset, int n_start, int n_end)
371 BDRVQcowState *s = bs->opaque;
372 int n, ret;
374 n = n_end - n_start;
375 if (n <= 0)
376 return 0;
377 ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);
378 if (ret < 0)
379 return ret;
380 if (s->crypt_method) {
381 encrypt_sectors(s, start_sect + n_start,
382 s->cluster_data,
383 s->cluster_data, n, 1,
384 &s->aes_encrypt_key);
386 ret = bdrv_write(s->hd, (cluster_offset >> 9) + n_start,
387 s->cluster_data, n);
388 if (ret < 0)
389 return ret;
390 return 0;
393 static void l2_cache_reset(BlockDriverState *bs)
395 BDRVQcowState *s = bs->opaque;
397 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
398 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
399 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
402 static inline int l2_cache_new_entry(BlockDriverState *bs)
404 BDRVQcowState *s = bs->opaque;
405 uint32_t min_count;
406 int min_index, i;
408 /* find a new entry in the least used one */
409 min_index = 0;
410 min_count = 0xffffffff;
411 for(i = 0; i < L2_CACHE_SIZE; i++) {
412 if (s->l2_cache_counts[i] < min_count) {
413 min_count = s->l2_cache_counts[i];
414 min_index = i;
417 return min_index;
420 static int64_t align_offset(int64_t offset, int n)
422 offset = (offset + n - 1) & ~(n - 1);
423 return offset;
426 static int grow_l1_table(BlockDriverState *bs, int min_size)
428 BDRVQcowState *s = bs->opaque;
429 int new_l1_size, new_l1_size2, ret, i;
430 uint64_t *new_l1_table;
431 uint64_t new_l1_table_offset;
432 uint8_t data[12];
434 new_l1_size = s->l1_size;
435 if (min_size <= new_l1_size)
436 return 0;
437 while (min_size > new_l1_size) {
438 new_l1_size = (new_l1_size * 3 + 1) / 2;
440 #ifdef DEBUG_ALLOC2
441 printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
442 #endif
444 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
445 new_l1_table = qemu_mallocz(new_l1_size2);
446 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
448 /* write new table (align to cluster) */
449 new_l1_table_offset = alloc_clusters(bs, new_l1_size2);
451 for(i = 0; i < s->l1_size; i++)
452 new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
453 ret = bdrv_pwrite(s->hd, new_l1_table_offset, new_l1_table, new_l1_size2);
454 if (ret != new_l1_size2)
455 goto fail;
456 for(i = 0; i < s->l1_size; i++)
457 new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
459 /* set new table */
460 cpu_to_be32w((uint32_t*)data, new_l1_size);
461 cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);
462 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, l1_size), data,
463 sizeof(data)) != sizeof(data))
464 goto fail;
465 qemu_free(s->l1_table);
466 free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
467 s->l1_table_offset = new_l1_table_offset;
468 s->l1_table = new_l1_table;
469 s->l1_size = new_l1_size;
470 return 0;
471 fail:
472 qemu_free(s->l1_table);
473 return -EIO;
477 * seek_l2_table
479 * seek l2_offset in the l2_cache table
480 * if not found, return NULL,
481 * if found,
482 * increments the l2 cache hit count of the entry,
483 * if counter overflow, divide by two all counters
484 * return the pointer to the l2 cache entry
488 static uint64_t *seek_l2_table(BDRVQcowState *s, uint64_t l2_offset)
490 int i, j;
492 for(i = 0; i < L2_CACHE_SIZE; i++) {
493 if (l2_offset == s->l2_cache_offsets[i]) {
494 /* increment the hit count */
495 if (++s->l2_cache_counts[i] == 0xffffffff) {
496 for(j = 0; j < L2_CACHE_SIZE; j++) {
497 s->l2_cache_counts[j] >>= 1;
500 return s->l2_cache + (i << s->l2_bits);
503 return NULL;
507 * l2_load
509 * Loads a L2 table into memory. If the table is in the cache, the cache
510 * is used; otherwise the L2 table is loaded from the image file.
512 * Returns a pointer to the L2 table on success, or NULL if the read from
513 * the image file failed.
516 static uint64_t *l2_load(BlockDriverState *bs, uint64_t l2_offset)
518 BDRVQcowState *s = bs->opaque;
519 int min_index;
520 uint64_t *l2_table;
522 /* seek if the table for the given offset is in the cache */
524 l2_table = seek_l2_table(s, l2_offset);
525 if (l2_table != NULL)
526 return l2_table;
528 /* not found: load a new entry in the least used one */
530 min_index = l2_cache_new_entry(bs);
531 l2_table = s->l2_cache + (min_index << s->l2_bits);
532 if (bdrv_pread(s->hd, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
533 s->l2_size * sizeof(uint64_t))
534 return NULL;
535 s->l2_cache_offsets[min_index] = l2_offset;
536 s->l2_cache_counts[min_index] = 1;
538 return l2_table;
542 * l2_allocate
544 * Allocate a new l2 entry in the file. If l1_index points to an already
545 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
546 * table) copy the contents of the old L2 table into the newly allocated one.
547 * Otherwise the new table is initialized with zeros.
551 static uint64_t *l2_allocate(BlockDriverState *bs, int l1_index)
553 BDRVQcowState *s = bs->opaque;
554 int min_index;
555 uint64_t old_l2_offset, tmp;
556 uint64_t *l2_table, l2_offset;
558 old_l2_offset = s->l1_table[l1_index];
560 /* allocate a new l2 entry */
562 l2_offset = alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
564 /* update the L1 entry */
566 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
568 tmp = cpu_to_be64(l2_offset | QCOW_OFLAG_COPIED);
569 if (bdrv_pwrite(s->hd, s->l1_table_offset + l1_index * sizeof(tmp),
570 &tmp, sizeof(tmp)) != sizeof(tmp))
571 return NULL;
573 /* allocate a new entry in the l2 cache */
575 min_index = l2_cache_new_entry(bs);
576 l2_table = s->l2_cache + (min_index << s->l2_bits);
578 if (old_l2_offset == 0) {
579 /* if there was no old l2 table, clear the new table */
580 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
581 } else {
582 /* if there was an old l2 table, read it from the disk */
583 if (bdrv_pread(s->hd, old_l2_offset,
584 l2_table, s->l2_size * sizeof(uint64_t)) !=
585 s->l2_size * sizeof(uint64_t))
586 return NULL;
588 /* write the l2 table to the file */
589 if (bdrv_pwrite(s->hd, l2_offset,
590 l2_table, s->l2_size * sizeof(uint64_t)) !=
591 s->l2_size * sizeof(uint64_t))
592 return NULL;
594 /* update the l2 cache entry */
596 s->l2_cache_offsets[min_index] = l2_offset;
597 s->l2_cache_counts[min_index] = 1;
599 return l2_table;
602 static int size_to_clusters(BDRVQcowState *s, int64_t size)
604 return (size + (s->cluster_size - 1)) >> s->cluster_bits;
607 static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
608 uint64_t *l2_table, uint64_t start, uint64_t mask)
610 int i;
611 uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask;
613 if (!offset)
614 return 0;
616 for (i = start; i < start + nb_clusters; i++)
617 if (offset + i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask))
618 break;
620 return (i - start);
623 static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
625 int i = 0;
627 while(nb_clusters-- && l2_table[i] == 0)
628 i++;
630 return i;
634 * get_cluster_offset
636 * For a given offset of the disk image, return cluster offset in
637 * qcow2 file.
639 * on entry, *num is the number of contiguous clusters we'd like to
640 * access following offset.
642 * on exit, *num is the number of contiguous clusters we can read.
644 * Return 1, if the offset is found
645 * Return 0, otherwise.
649 static uint64_t get_cluster_offset(BlockDriverState *bs,
650 uint64_t offset, int *num)
652 BDRVQcowState *s = bs->opaque;
653 int l1_index, l2_index;
654 uint64_t l2_offset, *l2_table, cluster_offset;
655 int l1_bits, c;
656 int index_in_cluster, nb_available, nb_needed, nb_clusters;
658 index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
659 nb_needed = *num + index_in_cluster;
661 l1_bits = s->l2_bits + s->cluster_bits;
663 /* compute how many bytes there are between the offset and
664 * the end of the l1 entry
667 nb_available = (1 << l1_bits) - (offset & ((1 << l1_bits) - 1));
669 /* compute the number of available sectors */
671 nb_available = (nb_available >> 9) + index_in_cluster;
673 if (nb_needed > nb_available) {
674 nb_needed = nb_available;
677 cluster_offset = 0;
679 /* seek the the l2 offset in the l1 table */
681 l1_index = offset >> l1_bits;
682 if (l1_index >= s->l1_size)
683 goto out;
685 l2_offset = s->l1_table[l1_index];
687 /* seek the l2 table of the given l2 offset */
689 if (!l2_offset)
690 goto out;
692 /* load the l2 table in memory */
694 l2_offset &= ~QCOW_OFLAG_COPIED;
695 l2_table = l2_load(bs, l2_offset);
696 if (l2_table == NULL)
697 return 0;
699 /* find the cluster offset for the given disk offset */
701 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
702 cluster_offset = be64_to_cpu(l2_table[l2_index]);
703 nb_clusters = size_to_clusters(s, nb_needed << 9);
705 if (!cluster_offset) {
706 /* how many empty clusters ? */
707 c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
708 } else {
709 /* how many allocated clusters ? */
710 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
711 &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);
714 nb_available = (c * s->cluster_sectors);
715 out:
716 if (nb_available > nb_needed)
717 nb_available = nb_needed;
719 *num = nb_available - index_in_cluster;
721 return cluster_offset & ~QCOW_OFLAG_COPIED;
725 * free_any_clusters
727 * free clusters according to its type: compressed or not
731 static void free_any_clusters(BlockDriverState *bs,
732 uint64_t cluster_offset, int nb_clusters)
734 BDRVQcowState *s = bs->opaque;
736 /* free the cluster */
738 if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
739 int nb_csectors;
740 nb_csectors = ((cluster_offset >> s->csize_shift) &
741 s->csize_mask) + 1;
742 free_clusters(bs, (cluster_offset & s->cluster_offset_mask) & ~511,
743 nb_csectors * 512);
744 return;
747 free_clusters(bs, cluster_offset, nb_clusters << s->cluster_bits);
749 return;
753 * get_cluster_table
755 * for a given disk offset, load (and allocate if needed)
756 * the l2 table.
758 * the l2 table offset in the qcow2 file and the cluster index
759 * in the l2 table are given to the caller.
763 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
764 uint64_t **new_l2_table,
765 uint64_t *new_l2_offset,
766 int *new_l2_index)
768 BDRVQcowState *s = bs->opaque;
769 int l1_index, l2_index, ret;
770 uint64_t l2_offset, *l2_table;
772 /* seek the the l2 offset in the l1 table */
774 l1_index = offset >> (s->l2_bits + s->cluster_bits);
775 if (l1_index >= s->l1_size) {
776 ret = grow_l1_table(bs, l1_index + 1);
777 if (ret < 0)
778 return 0;
780 l2_offset = s->l1_table[l1_index];
782 /* seek the l2 table of the given l2 offset */
784 if (l2_offset & QCOW_OFLAG_COPIED) {
785 /* load the l2 table in memory */
786 l2_offset &= ~QCOW_OFLAG_COPIED;
787 l2_table = l2_load(bs, l2_offset);
788 if (l2_table == NULL)
789 return 0;
790 } else {
791 if (l2_offset)
792 free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
793 l2_table = l2_allocate(bs, l1_index);
794 if (l2_table == NULL)
795 return 0;
796 l2_offset = s->l1_table[l1_index] & ~QCOW_OFLAG_COPIED;
799 /* find the cluster offset for the given disk offset */
801 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
803 *new_l2_table = l2_table;
804 *new_l2_offset = l2_offset;
805 *new_l2_index = l2_index;
807 return 1;
811 * alloc_compressed_cluster_offset
813 * For a given offset of the disk image, return cluster offset in
814 * qcow2 file.
816 * If the offset is not found, allocate a new compressed cluster.
818 * Return the cluster offset if successful,
819 * Return 0, otherwise.
823 static uint64_t alloc_compressed_cluster_offset(BlockDriverState *bs,
824 uint64_t offset,
825 int compressed_size)
827 BDRVQcowState *s = bs->opaque;
828 int l2_index, ret;
829 uint64_t l2_offset, *l2_table, cluster_offset;
830 int nb_csectors;
832 ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
833 if (ret == 0)
834 return 0;
836 cluster_offset = be64_to_cpu(l2_table[l2_index]);
837 if (cluster_offset & QCOW_OFLAG_COPIED)
838 return cluster_offset & ~QCOW_OFLAG_COPIED;
840 if (cluster_offset)
841 free_any_clusters(bs, cluster_offset, 1);
843 cluster_offset = alloc_bytes(bs, compressed_size);
844 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
845 (cluster_offset >> 9);
847 cluster_offset |= QCOW_OFLAG_COMPRESSED |
848 ((uint64_t)nb_csectors << s->csize_shift);
850 /* update L2 table */
852 /* compressed clusters never have the copied flag */
854 l2_table[l2_index] = cpu_to_be64(cluster_offset);
855 if (bdrv_pwrite(s->hd,
856 l2_offset + l2_index * sizeof(uint64_t),
857 l2_table + l2_index,
858 sizeof(uint64_t)) != sizeof(uint64_t))
859 return 0;
861 return cluster_offset;
864 typedef struct QCowL2Meta
866 uint64_t offset;
867 int n_start;
868 int nb_available;
869 int nb_clusters;
870 } QCowL2Meta;
872 static int alloc_cluster_link_l2(BlockDriverState *bs, uint64_t cluster_offset,
873 QCowL2Meta *m)
875 BDRVQcowState *s = bs->opaque;
876 int i, j = 0, l2_index, ret;
877 uint64_t *old_cluster, start_sect, l2_offset, *l2_table;
879 if (m->nb_clusters == 0)
880 return 0;
882 old_cluster = qemu_malloc(m->nb_clusters * sizeof(uint64_t));
884 /* copy content of unmodified sectors */
885 start_sect = (m->offset & ~(s->cluster_size - 1)) >> 9;
886 if (m->n_start) {
887 ret = copy_sectors(bs, start_sect, cluster_offset, 0, m->n_start);
888 if (ret < 0)
889 goto err;
892 if (m->nb_available & (s->cluster_sectors - 1)) {
893 uint64_t end = m->nb_available & ~(uint64_t)(s->cluster_sectors - 1);
894 ret = copy_sectors(bs, start_sect + end, cluster_offset + (end << 9),
895 m->nb_available - end, s->cluster_sectors);
896 if (ret < 0)
897 goto err;
900 ret = -EIO;
901 /* update L2 table */
902 if (!get_cluster_table(bs, m->offset, &l2_table, &l2_offset, &l2_index))
903 goto err;
905 for (i = 0; i < m->nb_clusters; i++) {
906 if(l2_table[l2_index + i] != 0)
907 old_cluster[j++] = l2_table[l2_index + i];
909 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
910 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
913 if (bdrv_pwrite(s->hd, l2_offset + l2_index * sizeof(uint64_t),
914 l2_table + l2_index, m->nb_clusters * sizeof(uint64_t)) !=
915 m->nb_clusters * sizeof(uint64_t))
916 goto err;
918 for (i = 0; i < j; i++)
919 free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1);
921 ret = 0;
922 err:
923 qemu_free(old_cluster);
924 return ret;
928 * alloc_cluster_offset
930 * For a given offset of the disk image, return cluster offset in
931 * qcow2 file.
933 * If the offset is not found, allocate a new cluster.
935 * Return the cluster offset if successful,
936 * Return 0, otherwise.
940 static uint64_t alloc_cluster_offset(BlockDriverState *bs,
941 uint64_t offset,
942 int n_start, int n_end,
943 int *num, QCowL2Meta *m)
945 BDRVQcowState *s = bs->opaque;
946 int l2_index, ret;
947 uint64_t l2_offset, *l2_table, cluster_offset;
948 int nb_clusters, i = 0;
950 ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
951 if (ret == 0)
952 return 0;
954 nb_clusters = size_to_clusters(s, n_end << 9);
956 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
958 cluster_offset = be64_to_cpu(l2_table[l2_index]);
960 /* We keep all QCOW_OFLAG_COPIED clusters */
962 if (cluster_offset & QCOW_OFLAG_COPIED) {
963 nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
964 &l2_table[l2_index], 0, 0);
966 cluster_offset &= ~QCOW_OFLAG_COPIED;
967 m->nb_clusters = 0;
969 goto out;
972 /* for the moment, multiple compressed clusters are not managed */
974 if (cluster_offset & QCOW_OFLAG_COMPRESSED)
975 nb_clusters = 1;
977 /* how many available clusters ? */
979 while (i < nb_clusters) {
980 i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
981 &l2_table[l2_index], i, 0);
983 if(be64_to_cpu(l2_table[l2_index + i]))
984 break;
986 i += count_contiguous_free_clusters(nb_clusters - i,
987 &l2_table[l2_index + i]);
989 cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
991 if ((cluster_offset & QCOW_OFLAG_COPIED) ||
992 (cluster_offset & QCOW_OFLAG_COMPRESSED))
993 break;
995 nb_clusters = i;
997 /* allocate a new cluster */
999 cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);
1001 /* save info needed for meta data update */
1002 m->offset = offset;
1003 m->n_start = n_start;
1004 m->nb_clusters = nb_clusters;
1006 out:
1007 m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
1009 *num = m->nb_available - n_start;
1011 return cluster_offset;
1014 static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
1015 int nb_sectors, int *pnum)
1017 uint64_t cluster_offset;
1019 *pnum = nb_sectors;
1020 cluster_offset = get_cluster_offset(bs, sector_num << 9, pnum);
1022 return (cluster_offset != 0);
1025 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1026 const uint8_t *buf, int buf_size)
1028 z_stream strm1, *strm = &strm1;
1029 int ret, out_len;
1031 memset(strm, 0, sizeof(*strm));
1033 strm->next_in = (uint8_t *)buf;
1034 strm->avail_in = buf_size;
1035 strm->next_out = out_buf;
1036 strm->avail_out = out_buf_size;
1038 ret = inflateInit2(strm, -12);
1039 if (ret != Z_OK)
1040 return -1;
1041 ret = inflate(strm, Z_FINISH);
1042 out_len = strm->next_out - out_buf;
1043 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1044 out_len != out_buf_size) {
1045 inflateEnd(strm);
1046 return -1;
1048 inflateEnd(strm);
1049 return 0;
1052 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
1054 int ret, csize, nb_csectors, sector_offset;
1055 uint64_t coffset;
1057 coffset = cluster_offset & s->cluster_offset_mask;
1058 if (s->cluster_cache_offset != coffset) {
1059 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1060 sector_offset = coffset & 511;
1061 csize = nb_csectors * 512 - sector_offset;
1062 ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
1063 if (ret < 0) {
1064 return -1;
1066 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1067 s->cluster_data + sector_offset, csize) < 0) {
1068 return -1;
1070 s->cluster_cache_offset = coffset;
1072 return 0;
1075 /* handle reading after the end of the backing file */
1076 static int backing_read1(BlockDriverState *bs,
1077 int64_t sector_num, uint8_t *buf, int nb_sectors)
1079 int n1;
1080 if ((sector_num + nb_sectors) <= bs->total_sectors)
1081 return nb_sectors;
1082 if (sector_num >= bs->total_sectors)
1083 n1 = 0;
1084 else
1085 n1 = bs->total_sectors - sector_num;
1086 memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
1087 return n1;
1090 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
1091 uint8_t *buf, int nb_sectors)
1093 BDRVQcowState *s = bs->opaque;
1094 int ret, index_in_cluster, n, n1;
1095 uint64_t cluster_offset;
1097 while (nb_sectors > 0) {
1098 n = nb_sectors;
1099 cluster_offset = get_cluster_offset(bs, sector_num << 9, &n);
1100 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1101 if (!cluster_offset) {
1102 if (bs->backing_hd) {
1103 /* read from the base image */
1104 n1 = backing_read1(bs->backing_hd, sector_num, buf, n);
1105 if (n1 > 0) {
1106 ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
1107 if (ret < 0)
1108 return -1;
1110 } else {
1111 memset(buf, 0, 512 * n);
1113 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
1114 if (decompress_cluster(s, cluster_offset) < 0)
1115 return -1;
1116 memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
1117 } else {
1118 ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1119 if (ret != n * 512)
1120 return -1;
1121 if (s->crypt_method) {
1122 encrypt_sectors(s, sector_num, buf, buf, n, 0,
1123 &s->aes_decrypt_key);
1126 nb_sectors -= n;
1127 sector_num += n;
1128 buf += n * 512;
1130 return 0;
1133 static int qcow_write(BlockDriverState *bs, int64_t sector_num,
1134 const uint8_t *buf, int nb_sectors)
1136 BDRVQcowState *s = bs->opaque;
1137 int ret, index_in_cluster, n;
1138 uint64_t cluster_offset;
1139 int n_end;
1140 QCowL2Meta l2meta;
1142 while (nb_sectors > 0) {
1143 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1144 n_end = index_in_cluster + nb_sectors;
1145 if (s->crypt_method &&
1146 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1147 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1148 cluster_offset = alloc_cluster_offset(bs, sector_num << 9,
1149 index_in_cluster,
1150 n_end, &n, &l2meta);
1151 if (!cluster_offset)
1152 return -1;
1153 if (s->crypt_method) {
1154 encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
1155 &s->aes_encrypt_key);
1156 ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512,
1157 s->cluster_data, n * 512);
1158 } else {
1159 ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1161 if (ret != n * 512 || alloc_cluster_link_l2(bs, cluster_offset, &l2meta) < 0) {
1162 free_any_clusters(bs, cluster_offset, l2meta.nb_clusters);
1163 return -1;
1165 nb_sectors -= n;
1166 sector_num += n;
1167 buf += n * 512;
1169 s->cluster_cache_offset = -1; /* disable compressed cache */
1170 return 0;
1173 typedef struct QCowAIOCB {
1174 BlockDriverAIOCB common;
1175 int64_t sector_num;
1176 uint8_t *buf;
1177 int nb_sectors;
1178 int n;
1179 uint64_t cluster_offset;
1180 uint8_t *cluster_data;
1181 BlockDriverAIOCB *hd_aiocb;
1182 QEMUBH *bh;
1183 QCowL2Meta l2meta;
1184 } QCowAIOCB;
1186 static void qcow_aio_read_cb(void *opaque, int ret);
1187 static void qcow_aio_read_bh(void *opaque)
1189 QCowAIOCB *acb = opaque;
1190 qemu_bh_delete(acb->bh);
1191 acb->bh = NULL;
1192 qcow_aio_read_cb(opaque, 0);
1195 static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
1197 if (acb->bh)
1198 return -EIO;
1200 acb->bh = qemu_bh_new(cb, acb);
1201 if (!acb->bh)
1202 return -EIO;
1204 qemu_bh_schedule(acb->bh);
1206 return 0;
1209 static void qcow_aio_read_cb(void *opaque, int ret)
1211 QCowAIOCB *acb = opaque;
1212 BlockDriverState *bs = acb->common.bs;
1213 BDRVQcowState *s = bs->opaque;
1214 int index_in_cluster, n1;
1216 acb->hd_aiocb = NULL;
1217 if (ret < 0) {
1218 fail:
1219 acb->common.cb(acb->common.opaque, ret);
1220 qemu_aio_release(acb);
1221 return;
1224 /* post process the read buffer */
1225 if (!acb->cluster_offset) {
1226 /* nothing to do */
1227 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1228 /* nothing to do */
1229 } else {
1230 if (s->crypt_method) {
1231 encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
1232 acb->n, 0,
1233 &s->aes_decrypt_key);
1237 acb->nb_sectors -= acb->n;
1238 acb->sector_num += acb->n;
1239 acb->buf += acb->n * 512;
1241 if (acb->nb_sectors == 0) {
1242 /* request completed */
1243 acb->common.cb(acb->common.opaque, 0);
1244 qemu_aio_release(acb);
1245 return;
1248 /* prepare next AIO request */
1249 acb->n = acb->nb_sectors;
1250 acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
1251 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1253 if (!acb->cluster_offset) {
1254 if (bs->backing_hd) {
1255 /* read from the base image */
1256 n1 = backing_read1(bs->backing_hd, acb->sector_num,
1257 acb->buf, acb->n);
1258 if (n1 > 0) {
1259 acb->hd_aiocb = bdrv_aio_read(bs->backing_hd, acb->sector_num,
1260 acb->buf, acb->n, qcow_aio_read_cb, acb);
1261 if (acb->hd_aiocb == NULL)
1262 goto fail;
1263 } else {
1264 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1265 if (ret < 0)
1266 goto fail;
1268 } else {
1269 /* Note: in this case, no need to wait */
1270 memset(acb->buf, 0, 512 * acb->n);
1271 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1272 if (ret < 0)
1273 goto fail;
1275 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1276 /* add AIO support for compressed blocks ? */
1277 if (decompress_cluster(s, acb->cluster_offset) < 0)
1278 goto fail;
1279 memcpy(acb->buf,
1280 s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
1281 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1282 if (ret < 0)
1283 goto fail;
1284 } else {
1285 if ((acb->cluster_offset & 511) != 0) {
1286 ret = -EIO;
1287 goto fail;
1289 acb->hd_aiocb = bdrv_aio_read(s->hd,
1290 (acb->cluster_offset >> 9) + index_in_cluster,
1291 acb->buf, acb->n, qcow_aio_read_cb, acb);
1292 if (acb->hd_aiocb == NULL)
1293 goto fail;
1297 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
1298 int64_t sector_num, uint8_t *buf, int nb_sectors,
1299 BlockDriverCompletionFunc *cb, void *opaque)
1301 QCowAIOCB *acb;
1303 acb = qemu_aio_get(bs, cb, opaque);
1304 if (!acb)
1305 return NULL;
1306 acb->hd_aiocb = NULL;
1307 acb->sector_num = sector_num;
1308 acb->buf = buf;
1309 acb->nb_sectors = nb_sectors;
1310 acb->n = 0;
1311 acb->cluster_offset = 0;
1312 acb->l2meta.nb_clusters = 0;
1313 return acb;
1316 static BlockDriverAIOCB *qcow_aio_read(BlockDriverState *bs,
1317 int64_t sector_num, uint8_t *buf, int nb_sectors,
1318 BlockDriverCompletionFunc *cb, void *opaque)
1320 QCowAIOCB *acb;
1322 acb = qcow_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
1323 if (!acb)
1324 return NULL;
1326 qcow_aio_read_cb(acb, 0);
1327 return &acb->common;
1330 static void qcow_aio_write_cb(void *opaque, int ret)
1332 QCowAIOCB *acb = opaque;
1333 BlockDriverState *bs = acb->common.bs;
1334 BDRVQcowState *s = bs->opaque;
1335 int index_in_cluster;
1336 const uint8_t *src_buf;
1337 int n_end;
1339 acb->hd_aiocb = NULL;
1341 if (ret < 0) {
1342 fail:
1343 acb->common.cb(acb->common.opaque, ret);
1344 qemu_aio_release(acb);
1345 return;
1348 if (alloc_cluster_link_l2(bs, acb->cluster_offset, &acb->l2meta) < 0) {
1349 free_any_clusters(bs, acb->cluster_offset, acb->l2meta.nb_clusters);
1350 goto fail;
1353 acb->nb_sectors -= acb->n;
1354 acb->sector_num += acb->n;
1355 acb->buf += acb->n * 512;
1357 if (acb->nb_sectors == 0) {
1358 /* request completed */
1359 acb->common.cb(acb->common.opaque, 0);
1360 qemu_aio_release(acb);
1361 return;
1364 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1365 n_end = index_in_cluster + acb->nb_sectors;
1366 if (s->crypt_method &&
1367 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1368 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1370 acb->cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,
1371 index_in_cluster,
1372 n_end, &acb->n, &acb->l2meta);
1373 if (!acb->cluster_offset || (acb->cluster_offset & 511) != 0) {
1374 ret = -EIO;
1375 goto fail;
1377 if (s->crypt_method) {
1378 if (!acb->cluster_data) {
1379 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
1380 s->cluster_size);
1382 encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
1383 acb->n, 1, &s->aes_encrypt_key);
1384 src_buf = acb->cluster_data;
1385 } else {
1386 src_buf = acb->buf;
1388 acb->hd_aiocb = bdrv_aio_write(s->hd,
1389 (acb->cluster_offset >> 9) + index_in_cluster,
1390 src_buf, acb->n,
1391 qcow_aio_write_cb, acb);
1392 if (acb->hd_aiocb == NULL)
1393 goto fail;
1396 static BlockDriverAIOCB *qcow_aio_write(BlockDriverState *bs,
1397 int64_t sector_num, const uint8_t *buf, int nb_sectors,
1398 BlockDriverCompletionFunc *cb, void *opaque)
1400 BDRVQcowState *s = bs->opaque;
1401 QCowAIOCB *acb;
1403 s->cluster_cache_offset = -1; /* disable compressed cache */
1405 acb = qcow_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
1406 if (!acb)
1407 return NULL;
1409 qcow_aio_write_cb(acb, 0);
1410 return &acb->common;
1413 static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
1415 QCowAIOCB *acb = (QCowAIOCB *)blockacb;
1416 if (acb->hd_aiocb)
1417 bdrv_aio_cancel(acb->hd_aiocb);
1418 qemu_aio_release(acb);
1421 static void qcow_close(BlockDriverState *bs)
1423 BDRVQcowState *s = bs->opaque;
1424 qemu_free(s->l1_table);
1425 qemu_free(s->l2_cache);
1426 qemu_free(s->cluster_cache);
1427 qemu_free(s->cluster_data);
1428 refcount_close(bs);
1429 bdrv_delete(s->hd);
1432 /* XXX: use std qcow open function ? */
1433 typedef struct QCowCreateState {
1434 int cluster_size;
1435 int cluster_bits;
1436 uint16_t *refcount_block;
1437 uint64_t *refcount_table;
1438 int64_t l1_table_offset;
1439 int64_t refcount_table_offset;
1440 int64_t refcount_block_offset;
1441 } QCowCreateState;
1443 static void create_refcount_update(QCowCreateState *s,
1444 int64_t offset, int64_t size)
1446 int refcount;
1447 int64_t start, last, cluster_offset;
1448 uint16_t *p;
1450 start = offset & ~(s->cluster_size - 1);
1451 last = (offset + size - 1) & ~(s->cluster_size - 1);
1452 for(cluster_offset = start; cluster_offset <= last;
1453 cluster_offset += s->cluster_size) {
1454 p = &s->refcount_block[cluster_offset >> s->cluster_bits];
1455 refcount = be16_to_cpu(*p);
1456 refcount++;
1457 *p = cpu_to_be16(refcount);
1461 static int qcow_create(const char *filename, int64_t total_size,
1462 const char *backing_file, int flags)
1464 int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
1465 int ref_clusters;
1466 QCowHeader header;
1467 uint64_t tmp, offset;
1468 QCowCreateState s1, *s = &s1;
1470 memset(s, 0, sizeof(*s));
1472 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1473 if (fd < 0)
1474 return -1;
1475 memset(&header, 0, sizeof(header));
1476 header.magic = cpu_to_be32(QCOW_MAGIC);
1477 header.version = cpu_to_be32(QCOW_VERSION);
1478 header.size = cpu_to_be64(total_size * 512);
1479 header_size = sizeof(header);
1480 backing_filename_len = 0;
1481 if (backing_file) {
1482 header.backing_file_offset = cpu_to_be64(header_size);
1483 backing_filename_len = strlen(backing_file);
1484 header.backing_file_size = cpu_to_be32(backing_filename_len);
1485 header_size += backing_filename_len;
1487 s->cluster_bits = 12; /* 4 KB clusters */
1488 s->cluster_size = 1 << s->cluster_bits;
1489 header.cluster_bits = cpu_to_be32(s->cluster_bits);
1490 header_size = (header_size + 7) & ~7;
1491 if (flags & BLOCK_FLAG_ENCRYPT) {
1492 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1493 } else {
1494 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1496 l2_bits = s->cluster_bits - 3;
1497 shift = s->cluster_bits + l2_bits;
1498 l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
1499 offset = align_offset(header_size, s->cluster_size);
1500 s->l1_table_offset = offset;
1501 header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
1502 header.l1_size = cpu_to_be32(l1_size);
1503 offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
1505 s->refcount_table = qemu_mallocz(s->cluster_size);
1507 s->refcount_table_offset = offset;
1508 header.refcount_table_offset = cpu_to_be64(offset);
1509 header.refcount_table_clusters = cpu_to_be32(1);
1510 offset += s->cluster_size;
1511 s->refcount_block_offset = offset;
1513 /* count how many refcount blocks needed */
1514 tmp = offset >> s->cluster_bits;
1515 ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
1516 for (i=0; i < ref_clusters; i++) {
1517 s->refcount_table[i] = cpu_to_be64(offset);
1518 offset += s->cluster_size;
1521 s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
1523 /* update refcounts */
1524 create_refcount_update(s, 0, header_size);
1525 create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
1526 create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
1527 create_refcount_update(s, s->refcount_block_offset, ref_clusters * s->cluster_size);
1529 /* write all the data */
1530 write(fd, &header, sizeof(header));
1531 if (backing_file) {
1532 write(fd, backing_file, backing_filename_len);
1534 lseek(fd, s->l1_table_offset, SEEK_SET);
1535 tmp = 0;
1536 for(i = 0;i < l1_size; i++) {
1537 write(fd, &tmp, sizeof(tmp));
1539 lseek(fd, s->refcount_table_offset, SEEK_SET);
1540 write(fd, s->refcount_table, s->cluster_size);
1542 lseek(fd, s->refcount_block_offset, SEEK_SET);
1543 write(fd, s->refcount_block, ref_clusters * s->cluster_size);
1545 qemu_free(s->refcount_table);
1546 qemu_free(s->refcount_block);
1547 close(fd);
1548 return 0;
1551 static int qcow_make_empty(BlockDriverState *bs)
1553 #if 0
1554 /* XXX: not correct */
1555 BDRVQcowState *s = bs->opaque;
1556 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1557 int ret;
1559 memset(s->l1_table, 0, l1_length);
1560 if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1561 return -1;
1562 ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1563 if (ret < 0)
1564 return ret;
1566 l2_cache_reset(bs);
1567 #endif
1568 return 0;
1571 /* XXX: put compressed sectors first, then all the cluster aligned
1572 tables to avoid losing bytes in alignment */
1573 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1574 const uint8_t *buf, int nb_sectors)
1576 BDRVQcowState *s = bs->opaque;
1577 z_stream strm;
1578 int ret, out_len;
1579 uint8_t *out_buf;
1580 uint64_t cluster_offset;
1582 if (nb_sectors == 0) {
1583 /* align end of file to a sector boundary to ease reading with
1584 sector based I/Os */
1585 cluster_offset = bdrv_getlength(s->hd);
1586 cluster_offset = (cluster_offset + 511) & ~511;
1587 bdrv_truncate(s->hd, cluster_offset);
1588 return 0;
1591 if (nb_sectors != s->cluster_sectors)
1592 return -EINVAL;
1594 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1596 /* best compression, small window, no zlib header */
1597 memset(&strm, 0, sizeof(strm));
1598 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1599 Z_DEFLATED, -12,
1600 9, Z_DEFAULT_STRATEGY);
1601 if (ret != 0) {
1602 qemu_free(out_buf);
1603 return -1;
1606 strm.avail_in = s->cluster_size;
1607 strm.next_in = (uint8_t *)buf;
1608 strm.avail_out = s->cluster_size;
1609 strm.next_out = out_buf;
1611 ret = deflate(&strm, Z_FINISH);
1612 if (ret != Z_STREAM_END && ret != Z_OK) {
1613 qemu_free(out_buf);
1614 deflateEnd(&strm);
1615 return -1;
1617 out_len = strm.next_out - out_buf;
1619 deflateEnd(&strm);
1621 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1622 /* could not compress: write normal cluster */
1623 qcow_write(bs, sector_num, buf, s->cluster_sectors);
1624 } else {
1625 cluster_offset = alloc_compressed_cluster_offset(bs, sector_num << 9,
1626 out_len);
1627 if (!cluster_offset)
1628 return -1;
1629 cluster_offset &= s->cluster_offset_mask;
1630 if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1631 qemu_free(out_buf);
1632 return -1;
1636 qemu_free(out_buf);
1637 return 0;
1640 static void qcow_flush(BlockDriverState *bs)
1642 BDRVQcowState *s = bs->opaque;
1643 bdrv_flush(s->hd);
1646 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1648 BDRVQcowState *s = bs->opaque;
1649 bdi->cluster_size = s->cluster_size;
1650 bdi->vm_state_offset = (int64_t)s->l1_vm_state_index <<
1651 (s->cluster_bits + s->l2_bits);
1652 return 0;
1655 /*********************************************************/
1656 /* snapshot support */
1658 /* update the refcounts of snapshots and the copied flag */
1659 static int update_snapshot_refcount(BlockDriverState *bs,
1660 int64_t l1_table_offset,
1661 int l1_size,
1662 int addend)
1664 BDRVQcowState *s = bs->opaque;
1665 uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;
1666 int64_t old_offset, old_l2_offset;
1667 int l2_size, i, j, l1_modified, l2_modified, nb_csectors, refcount;
1669 l2_cache_reset(bs);
1671 l2_table = NULL;
1672 l1_table = NULL;
1673 l1_size2 = l1_size * sizeof(uint64_t);
1674 l1_allocated = 0;
1675 if (l1_table_offset != s->l1_table_offset) {
1676 l1_table = qemu_malloc(l1_size2);
1677 l1_allocated = 1;
1678 if (bdrv_pread(s->hd, l1_table_offset,
1679 l1_table, l1_size2) != l1_size2)
1680 goto fail;
1681 for(i = 0;i < l1_size; i++)
1682 be64_to_cpus(&l1_table[i]);
1683 } else {
1684 assert(l1_size == s->l1_size);
1685 l1_table = s->l1_table;
1686 l1_allocated = 0;
1689 l2_size = s->l2_size * sizeof(uint64_t);
1690 l2_table = qemu_malloc(l2_size);
1691 l1_modified = 0;
1692 for(i = 0; i < l1_size; i++) {
1693 l2_offset = l1_table[i];
1694 if (l2_offset) {
1695 old_l2_offset = l2_offset;
1696 l2_offset &= ~QCOW_OFLAG_COPIED;
1697 l2_modified = 0;
1698 if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
1699 goto fail;
1700 for(j = 0; j < s->l2_size; j++) {
1701 offset = be64_to_cpu(l2_table[j]);
1702 if (offset != 0) {
1703 old_offset = offset;
1704 offset &= ~QCOW_OFLAG_COPIED;
1705 if (offset & QCOW_OFLAG_COMPRESSED) {
1706 nb_csectors = ((offset >> s->csize_shift) &
1707 s->csize_mask) + 1;
1708 if (addend != 0)
1709 update_refcount(bs, (offset & s->cluster_offset_mask) & ~511,
1710 nb_csectors * 512, addend);
1711 /* compressed clusters are never modified */
1712 refcount = 2;
1713 } else {
1714 if (addend != 0) {
1715 refcount = update_cluster_refcount(bs, offset >> s->cluster_bits, addend);
1716 } else {
1717 refcount = get_refcount(bs, offset >> s->cluster_bits);
1721 if (refcount == 1) {
1722 offset |= QCOW_OFLAG_COPIED;
1724 if (offset != old_offset) {
1725 l2_table[j] = cpu_to_be64(offset);
1726 l2_modified = 1;
1730 if (l2_modified) {
1731 if (bdrv_pwrite(s->hd,
1732 l2_offset, l2_table, l2_size) != l2_size)
1733 goto fail;
1736 if (addend != 0) {
1737 refcount = update_cluster_refcount(bs, l2_offset >> s->cluster_bits, addend);
1738 } else {
1739 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1741 if (refcount == 1) {
1742 l2_offset |= QCOW_OFLAG_COPIED;
1744 if (l2_offset != old_l2_offset) {
1745 l1_table[i] = l2_offset;
1746 l1_modified = 1;
1750 if (l1_modified) {
1751 for(i = 0; i < l1_size; i++)
1752 cpu_to_be64s(&l1_table[i]);
1753 if (bdrv_pwrite(s->hd, l1_table_offset, l1_table,
1754 l1_size2) != l1_size2)
1755 goto fail;
1756 for(i = 0; i < l1_size; i++)
1757 be64_to_cpus(&l1_table[i]);
1759 if (l1_allocated)
1760 qemu_free(l1_table);
1761 qemu_free(l2_table);
1762 return 0;
1763 fail:
1764 if (l1_allocated)
1765 qemu_free(l1_table);
1766 qemu_free(l2_table);
1767 return -EIO;
1770 static void qcow_free_snapshots(BlockDriverState *bs)
1772 BDRVQcowState *s = bs->opaque;
1773 int i;
1775 for(i = 0; i < s->nb_snapshots; i++) {
1776 qemu_free(s->snapshots[i].name);
1777 qemu_free(s->snapshots[i].id_str);
1779 qemu_free(s->snapshots);
1780 s->snapshots = NULL;
1781 s->nb_snapshots = 0;
1784 static int qcow_read_snapshots(BlockDriverState *bs)
1786 BDRVQcowState *s = bs->opaque;
1787 QCowSnapshotHeader h;
1788 QCowSnapshot *sn;
1789 int i, id_str_size, name_size;
1790 int64_t offset;
1791 uint32_t extra_data_size;
1793 if (!s->nb_snapshots) {
1794 s->snapshots = NULL;
1795 s->snapshots_size = 0;
1796 return 0;
1799 offset = s->snapshots_offset;
1800 s->snapshots = qemu_mallocz(s->nb_snapshots * sizeof(QCowSnapshot));
1801 for(i = 0; i < s->nb_snapshots; i++) {
1802 offset = align_offset(offset, 8);
1803 if (bdrv_pread(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1804 goto fail;
1805 offset += sizeof(h);
1806 sn = s->snapshots + i;
1807 sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
1808 sn->l1_size = be32_to_cpu(h.l1_size);
1809 sn->vm_state_size = be32_to_cpu(h.vm_state_size);
1810 sn->date_sec = be32_to_cpu(h.date_sec);
1811 sn->date_nsec = be32_to_cpu(h.date_nsec);
1812 sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
1813 extra_data_size = be32_to_cpu(h.extra_data_size);
1815 id_str_size = be16_to_cpu(h.id_str_size);
1816 name_size = be16_to_cpu(h.name_size);
1818 offset += extra_data_size;
1820 sn->id_str = qemu_malloc(id_str_size + 1);
1821 if (bdrv_pread(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1822 goto fail;
1823 offset += id_str_size;
1824 sn->id_str[id_str_size] = '\0';
1826 sn->name = qemu_malloc(name_size + 1);
1827 if (bdrv_pread(s->hd, offset, sn->name, name_size) != name_size)
1828 goto fail;
1829 offset += name_size;
1830 sn->name[name_size] = '\0';
1832 s->snapshots_size = offset - s->snapshots_offset;
1833 return 0;
1834 fail:
1835 qcow_free_snapshots(bs);
1836 return -1;
1839 /* add at the end of the file a new list of snapshots */
1840 static int qcow_write_snapshots(BlockDriverState *bs)
1842 BDRVQcowState *s = bs->opaque;
1843 QCowSnapshot *sn;
1844 QCowSnapshotHeader h;
1845 int i, name_size, id_str_size, snapshots_size;
1846 uint64_t data64;
1847 uint32_t data32;
1848 int64_t offset, snapshots_offset;
1850 /* compute the size of the snapshots */
1851 offset = 0;
1852 for(i = 0; i < s->nb_snapshots; i++) {
1853 sn = s->snapshots + i;
1854 offset = align_offset(offset, 8);
1855 offset += sizeof(h);
1856 offset += strlen(sn->id_str);
1857 offset += strlen(sn->name);
1859 snapshots_size = offset;
1861 snapshots_offset = alloc_clusters(bs, snapshots_size);
1862 offset = snapshots_offset;
1864 for(i = 0; i < s->nb_snapshots; i++) {
1865 sn = s->snapshots + i;
1866 memset(&h, 0, sizeof(h));
1867 h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);
1868 h.l1_size = cpu_to_be32(sn->l1_size);
1869 h.vm_state_size = cpu_to_be32(sn->vm_state_size);
1870 h.date_sec = cpu_to_be32(sn->date_sec);
1871 h.date_nsec = cpu_to_be32(sn->date_nsec);
1872 h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);
1874 id_str_size = strlen(sn->id_str);
1875 name_size = strlen(sn->name);
1876 h.id_str_size = cpu_to_be16(id_str_size);
1877 h.name_size = cpu_to_be16(name_size);
1878 offset = align_offset(offset, 8);
1879 if (bdrv_pwrite(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1880 goto fail;
1881 offset += sizeof(h);
1882 if (bdrv_pwrite(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1883 goto fail;
1884 offset += id_str_size;
1885 if (bdrv_pwrite(s->hd, offset, sn->name, name_size) != name_size)
1886 goto fail;
1887 offset += name_size;
1890 /* update the various header fields */
1891 data64 = cpu_to_be64(snapshots_offset);
1892 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, snapshots_offset),
1893 &data64, sizeof(data64)) != sizeof(data64))
1894 goto fail;
1895 data32 = cpu_to_be32(s->nb_snapshots);
1896 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, nb_snapshots),
1897 &data32, sizeof(data32)) != sizeof(data32))
1898 goto fail;
1900 /* free the old snapshot table */
1901 free_clusters(bs, s->snapshots_offset, s->snapshots_size);
1902 s->snapshots_offset = snapshots_offset;
1903 s->snapshots_size = snapshots_size;
1904 return 0;
1905 fail:
1906 return -1;
1909 static void find_new_snapshot_id(BlockDriverState *bs,
1910 char *id_str, int id_str_size)
1912 BDRVQcowState *s = bs->opaque;
1913 QCowSnapshot *sn;
1914 int i, id, id_max = 0;
1916 for(i = 0; i < s->nb_snapshots; i++) {
1917 sn = s->snapshots + i;
1918 id = strtoul(sn->id_str, NULL, 10);
1919 if (id > id_max)
1920 id_max = id;
1922 snprintf(id_str, id_str_size, "%d", id_max + 1);
1925 static int find_snapshot_by_id(BlockDriverState *bs, const char *id_str)
1927 BDRVQcowState *s = bs->opaque;
1928 int i;
1930 for(i = 0; i < s->nb_snapshots; i++) {
1931 if (!strcmp(s->snapshots[i].id_str, id_str))
1932 return i;
1934 return -1;
1937 static int find_snapshot_by_id_or_name(BlockDriverState *bs, const char *name)
1939 BDRVQcowState *s = bs->opaque;
1940 int i, ret;
1942 ret = find_snapshot_by_id(bs, name);
1943 if (ret >= 0)
1944 return ret;
1945 for(i = 0; i < s->nb_snapshots; i++) {
1946 if (!strcmp(s->snapshots[i].name, name))
1947 return i;
1949 return -1;
1952 /* if no id is provided, a new one is constructed */
1953 static int qcow_snapshot_create(BlockDriverState *bs,
1954 QEMUSnapshotInfo *sn_info)
1956 BDRVQcowState *s = bs->opaque;
1957 QCowSnapshot *snapshots1, sn1, *sn = &sn1;
1958 int i, ret;
1959 uint64_t *l1_table = NULL;
1961 memset(sn, 0, sizeof(*sn));
1963 if (sn_info->id_str[0] == '\0') {
1964 /* compute a new id */
1965 find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));
1968 /* check that the ID is unique */
1969 if (find_snapshot_by_id(bs, sn_info->id_str) >= 0)
1970 return -ENOENT;
1972 sn->id_str = qemu_strdup(sn_info->id_str);
1973 if (!sn->id_str)
1974 goto fail;
1975 sn->name = qemu_strdup(sn_info->name);
1976 if (!sn->name)
1977 goto fail;
1978 sn->vm_state_size = sn_info->vm_state_size;
1979 sn->date_sec = sn_info->date_sec;
1980 sn->date_nsec = sn_info->date_nsec;
1981 sn->vm_clock_nsec = sn_info->vm_clock_nsec;
1983 ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);
1984 if (ret < 0)
1985 goto fail;
1987 /* create the L1 table of the snapshot */
1988 sn->l1_table_offset = alloc_clusters(bs, s->l1_size * sizeof(uint64_t));
1989 sn->l1_size = s->l1_size;
1991 l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
1992 for(i = 0; i < s->l1_size; i++) {
1993 l1_table[i] = cpu_to_be64(s->l1_table[i]);
1995 if (bdrv_pwrite(s->hd, sn->l1_table_offset,
1996 l1_table, s->l1_size * sizeof(uint64_t)) !=
1997 (s->l1_size * sizeof(uint64_t)))
1998 goto fail;
1999 qemu_free(l1_table);
2000 l1_table = NULL;
2002 snapshots1 = qemu_malloc((s->nb_snapshots + 1) * sizeof(QCowSnapshot));
2003 if (s->snapshots) {
2004 memcpy(snapshots1, s->snapshots, s->nb_snapshots * sizeof(QCowSnapshot));
2005 qemu_free(s->snapshots);
2007 s->snapshots = snapshots1;
2008 s->snapshots[s->nb_snapshots++] = *sn;
2010 if (qcow_write_snapshots(bs) < 0)
2011 goto fail;
2012 #ifdef DEBUG_ALLOC
2013 check_refcounts(bs);
2014 #endif
2015 return 0;
2016 fail:
2017 qemu_free(sn->name);
2018 qemu_free(l1_table);
2019 return -1;
2022 /* copy the snapshot 'snapshot_name' into the current disk image */
2023 static int qcow_snapshot_goto(BlockDriverState *bs,
2024 const char *snapshot_id)
2026 BDRVQcowState *s = bs->opaque;
2027 QCowSnapshot *sn;
2028 int i, snapshot_index, l1_size2;
2030 snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2031 if (snapshot_index < 0)
2032 return -ENOENT;
2033 sn = &s->snapshots[snapshot_index];
2035 if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, -1) < 0)
2036 goto fail;
2038 if (grow_l1_table(bs, sn->l1_size) < 0)
2039 goto fail;
2041 s->l1_size = sn->l1_size;
2042 l1_size2 = s->l1_size * sizeof(uint64_t);
2043 /* copy the snapshot l1 table to the current l1 table */
2044 if (bdrv_pread(s->hd, sn->l1_table_offset,
2045 s->l1_table, l1_size2) != l1_size2)
2046 goto fail;
2047 if (bdrv_pwrite(s->hd, s->l1_table_offset,
2048 s->l1_table, l1_size2) != l1_size2)
2049 goto fail;
2050 for(i = 0;i < s->l1_size; i++) {
2051 be64_to_cpus(&s->l1_table[i]);
2054 if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1) < 0)
2055 goto fail;
2057 #ifdef DEBUG_ALLOC
2058 check_refcounts(bs);
2059 #endif
2060 return 0;
2061 fail:
2062 return -EIO;
2065 static int qcow_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2067 BDRVQcowState *s = bs->opaque;
2068 QCowSnapshot *sn;
2069 int snapshot_index, ret;
2071 snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2072 if (snapshot_index < 0)
2073 return -ENOENT;
2074 sn = &s->snapshots[snapshot_index];
2076 ret = update_snapshot_refcount(bs, sn->l1_table_offset, sn->l1_size, -1);
2077 if (ret < 0)
2078 return ret;
2079 /* must update the copied flag on the current cluster offsets */
2080 ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
2081 if (ret < 0)
2082 return ret;
2083 free_clusters(bs, sn->l1_table_offset, sn->l1_size * sizeof(uint64_t));
2085 qemu_free(sn->id_str);
2086 qemu_free(sn->name);
2087 memmove(sn, sn + 1, (s->nb_snapshots - snapshot_index - 1) * sizeof(*sn));
2088 s->nb_snapshots--;
2089 ret = qcow_write_snapshots(bs);
2090 if (ret < 0) {
2091 /* XXX: restore snapshot if error ? */
2092 return ret;
2094 #ifdef DEBUG_ALLOC
2095 check_refcounts(bs);
2096 #endif
2097 return 0;
2100 static int qcow_snapshot_list(BlockDriverState *bs,
2101 QEMUSnapshotInfo **psn_tab)
2103 BDRVQcowState *s = bs->opaque;
2104 QEMUSnapshotInfo *sn_tab, *sn_info;
2105 QCowSnapshot *sn;
2106 int i;
2108 sn_tab = qemu_mallocz(s->nb_snapshots * sizeof(QEMUSnapshotInfo));
2109 for(i = 0; i < s->nb_snapshots; i++) {
2110 sn_info = sn_tab + i;
2111 sn = s->snapshots + i;
2112 pstrcpy(sn_info->id_str, sizeof(sn_info->id_str),
2113 sn->id_str);
2114 pstrcpy(sn_info->name, sizeof(sn_info->name),
2115 sn->name);
2116 sn_info->vm_state_size = sn->vm_state_size;
2117 sn_info->date_sec = sn->date_sec;
2118 sn_info->date_nsec = sn->date_nsec;
2119 sn_info->vm_clock_nsec = sn->vm_clock_nsec;
2121 *psn_tab = sn_tab;
2122 return s->nb_snapshots;
2125 /*********************************************************/
2126 /* refcount handling */
2128 static int refcount_init(BlockDriverState *bs)
2130 BDRVQcowState *s = bs->opaque;
2131 int ret, refcount_table_size2, i;
2133 s->refcount_block_cache = qemu_malloc(s->cluster_size);
2134 refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
2135 s->refcount_table = qemu_malloc(refcount_table_size2);
2136 if (s->refcount_table_size > 0) {
2137 ret = bdrv_pread(s->hd, s->refcount_table_offset,
2138 s->refcount_table, refcount_table_size2);
2139 if (ret != refcount_table_size2)
2140 goto fail;
2141 for(i = 0; i < s->refcount_table_size; i++)
2142 be64_to_cpus(&s->refcount_table[i]);
2144 return 0;
2145 fail:
2146 return -ENOMEM;
2149 static void refcount_close(BlockDriverState *bs)
2151 BDRVQcowState *s = bs->opaque;
2152 qemu_free(s->refcount_block_cache);
2153 qemu_free(s->refcount_table);
2157 static int load_refcount_block(BlockDriverState *bs,
2158 int64_t refcount_block_offset)
2160 BDRVQcowState *s = bs->opaque;
2161 int ret;
2162 ret = bdrv_pread(s->hd, refcount_block_offset, s->refcount_block_cache,
2163 s->cluster_size);
2164 if (ret != s->cluster_size)
2165 return -EIO;
2166 s->refcount_block_cache_offset = refcount_block_offset;
2167 return 0;
2170 static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
2172 BDRVQcowState *s = bs->opaque;
2173 int refcount_table_index, block_index;
2174 int64_t refcount_block_offset;
2176 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2177 if (refcount_table_index >= s->refcount_table_size)
2178 return 0;
2179 refcount_block_offset = s->refcount_table[refcount_table_index];
2180 if (!refcount_block_offset)
2181 return 0;
2182 if (refcount_block_offset != s->refcount_block_cache_offset) {
2183 /* better than nothing: return allocated if read error */
2184 if (load_refcount_block(bs, refcount_block_offset) < 0)
2185 return 1;
2187 block_index = cluster_index &
2188 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2189 return be16_to_cpu(s->refcount_block_cache[block_index]);
2192 /* return < 0 if error */
2193 static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)
2195 BDRVQcowState *s = bs->opaque;
2196 int i, nb_clusters;
2198 nb_clusters = size_to_clusters(s, size);
2199 retry:
2200 for(i = 0; i < nb_clusters; i++) {
2201 int64_t i = s->free_cluster_index++;
2202 if (get_refcount(bs, i) != 0)
2203 goto retry;
2205 #ifdef DEBUG_ALLOC2
2206 printf("alloc_clusters: size=%lld -> %lld\n",
2207 size,
2208 (s->free_cluster_index - nb_clusters) << s->cluster_bits);
2209 #endif
2210 return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
2213 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size)
2215 int64_t offset;
2217 offset = alloc_clusters_noref(bs, size);
2218 update_refcount(bs, offset, size, 1);
2219 return offset;
2222 /* only used to allocate compressed sectors. We try to allocate
2223 contiguous sectors. size must be <= cluster_size */
2224 static int64_t alloc_bytes(BlockDriverState *bs, int size)
2226 BDRVQcowState *s = bs->opaque;
2227 int64_t offset, cluster_offset;
2228 int free_in_cluster;
2230 assert(size > 0 && size <= s->cluster_size);
2231 if (s->free_byte_offset == 0) {
2232 s->free_byte_offset = alloc_clusters(bs, s->cluster_size);
2234 redo:
2235 free_in_cluster = s->cluster_size -
2236 (s->free_byte_offset & (s->cluster_size - 1));
2237 if (size <= free_in_cluster) {
2238 /* enough space in current cluster */
2239 offset = s->free_byte_offset;
2240 s->free_byte_offset += size;
2241 free_in_cluster -= size;
2242 if (free_in_cluster == 0)
2243 s->free_byte_offset = 0;
2244 if ((offset & (s->cluster_size - 1)) != 0)
2245 update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2246 } else {
2247 offset = alloc_clusters(bs, s->cluster_size);
2248 cluster_offset = s->free_byte_offset & ~(s->cluster_size - 1);
2249 if ((cluster_offset + s->cluster_size) == offset) {
2250 /* we are lucky: contiguous data */
2251 offset = s->free_byte_offset;
2252 update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2253 s->free_byte_offset += size;
2254 } else {
2255 s->free_byte_offset = offset;
2256 goto redo;
2259 return offset;
2262 static void free_clusters(BlockDriverState *bs,
2263 int64_t offset, int64_t size)
2265 update_refcount(bs, offset, size, -1);
2268 static int grow_refcount_table(BlockDriverState *bs, int min_size)
2270 BDRVQcowState *s = bs->opaque;
2271 int new_table_size, new_table_size2, refcount_table_clusters, i, ret;
2272 uint64_t *new_table;
2273 int64_t table_offset;
2274 uint8_t data[12];
2275 int old_table_size;
2276 int64_t old_table_offset;
2278 if (min_size <= s->refcount_table_size)
2279 return 0;
2280 /* compute new table size */
2281 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2282 for(;;) {
2283 if (refcount_table_clusters == 0) {
2284 refcount_table_clusters = 1;
2285 } else {
2286 refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
2288 new_table_size = refcount_table_clusters << (s->cluster_bits - 3);
2289 if (min_size <= new_table_size)
2290 break;
2292 #ifdef DEBUG_ALLOC2
2293 printf("grow_refcount_table from %d to %d\n",
2294 s->refcount_table_size,
2295 new_table_size);
2296 #endif
2297 new_table_size2 = new_table_size * sizeof(uint64_t);
2298 new_table = qemu_mallocz(new_table_size2);
2299 memcpy(new_table, s->refcount_table,
2300 s->refcount_table_size * sizeof(uint64_t));
2301 for(i = 0; i < s->refcount_table_size; i++)
2302 cpu_to_be64s(&new_table[i]);
2303 /* Note: we cannot update the refcount now to avoid recursion */
2304 table_offset = alloc_clusters_noref(bs, new_table_size2);
2305 ret = bdrv_pwrite(s->hd, table_offset, new_table, new_table_size2);
2306 if (ret != new_table_size2)
2307 goto fail;
2308 for(i = 0; i < s->refcount_table_size; i++)
2309 be64_to_cpus(&new_table[i]);
2311 cpu_to_be64w((uint64_t*)data, table_offset);
2312 cpu_to_be32w((uint32_t*)(data + 8), refcount_table_clusters);
2313 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, refcount_table_offset),
2314 data, sizeof(data)) != sizeof(data))
2315 goto fail;
2316 qemu_free(s->refcount_table);
2317 old_table_offset = s->refcount_table_offset;
2318 old_table_size = s->refcount_table_size;
2319 s->refcount_table = new_table;
2320 s->refcount_table_size = new_table_size;
2321 s->refcount_table_offset = table_offset;
2323 update_refcount(bs, table_offset, new_table_size2, 1);
2324 free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));
2325 return 0;
2326 fail:
2327 free_clusters(bs, table_offset, new_table_size2);
2328 qemu_free(new_table);
2329 return -EIO;
2332 /* addend must be 1 or -1 */
2333 /* XXX: cache several refcount block clusters ? */
2334 static int update_cluster_refcount(BlockDriverState *bs,
2335 int64_t cluster_index,
2336 int addend)
2338 BDRVQcowState *s = bs->opaque;
2339 int64_t offset, refcount_block_offset;
2340 int ret, refcount_table_index, block_index, refcount;
2341 uint64_t data64;
2343 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2344 if (refcount_table_index >= s->refcount_table_size) {
2345 if (addend < 0)
2346 return -EINVAL;
2347 ret = grow_refcount_table(bs, refcount_table_index + 1);
2348 if (ret < 0)
2349 return ret;
2351 refcount_block_offset = s->refcount_table[refcount_table_index];
2352 if (!refcount_block_offset) {
2353 if (addend < 0)
2354 return -EINVAL;
2355 /* create a new refcount block */
2356 /* Note: we cannot update the refcount now to avoid recursion */
2357 offset = alloc_clusters_noref(bs, s->cluster_size);
2358 memset(s->refcount_block_cache, 0, s->cluster_size);
2359 ret = bdrv_pwrite(s->hd, offset, s->refcount_block_cache, s->cluster_size);
2360 if (ret != s->cluster_size)
2361 return -EINVAL;
2362 s->refcount_table[refcount_table_index] = offset;
2363 data64 = cpu_to_be64(offset);
2364 ret = bdrv_pwrite(s->hd, s->refcount_table_offset +
2365 refcount_table_index * sizeof(uint64_t),
2366 &data64, sizeof(data64));
2367 if (ret != sizeof(data64))
2368 return -EINVAL;
2370 refcount_block_offset = offset;
2371 s->refcount_block_cache_offset = offset;
2372 update_refcount(bs, offset, s->cluster_size, 1);
2373 } else {
2374 if (refcount_block_offset != s->refcount_block_cache_offset) {
2375 if (load_refcount_block(bs, refcount_block_offset) < 0)
2376 return -EIO;
2379 /* we can update the count and save it */
2380 block_index = cluster_index &
2381 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2382 refcount = be16_to_cpu(s->refcount_block_cache[block_index]);
2383 refcount += addend;
2384 if (refcount < 0 || refcount > 0xffff)
2385 return -EINVAL;
2386 if (refcount == 0 && cluster_index < s->free_cluster_index) {
2387 s->free_cluster_index = cluster_index;
2389 s->refcount_block_cache[block_index] = cpu_to_be16(refcount);
2390 if (bdrv_pwrite(s->hd,
2391 refcount_block_offset + (block_index << REFCOUNT_SHIFT),
2392 &s->refcount_block_cache[block_index], 2) != 2)
2393 return -EIO;
2394 return refcount;
2397 static void update_refcount(BlockDriverState *bs,
2398 int64_t offset, int64_t length,
2399 int addend)
2401 BDRVQcowState *s = bs->opaque;
2402 int64_t start, last, cluster_offset;
2404 #ifdef DEBUG_ALLOC2
2405 printf("update_refcount: offset=%lld size=%lld addend=%d\n",
2406 offset, length, addend);
2407 #endif
2408 if (length <= 0)
2409 return;
2410 start = offset & ~(s->cluster_size - 1);
2411 last = (offset + length - 1) & ~(s->cluster_size - 1);
2412 for(cluster_offset = start; cluster_offset <= last;
2413 cluster_offset += s->cluster_size) {
2414 update_cluster_refcount(bs, cluster_offset >> s->cluster_bits, addend);
2418 #ifdef DEBUG_ALLOC
2419 static void inc_refcounts(BlockDriverState *bs,
2420 uint16_t *refcount_table,
2421 int refcount_table_size,
2422 int64_t offset, int64_t size)
2424 BDRVQcowState *s = bs->opaque;
2425 int64_t start, last, cluster_offset;
2426 int k;
2428 if (size <= 0)
2429 return;
2431 start = offset & ~(s->cluster_size - 1);
2432 last = (offset + size - 1) & ~(s->cluster_size - 1);
2433 for(cluster_offset = start; cluster_offset <= last;
2434 cluster_offset += s->cluster_size) {
2435 k = cluster_offset >> s->cluster_bits;
2436 if (k < 0 || k >= refcount_table_size) {
2437 printf("ERROR: invalid cluster offset=0x%llx\n", cluster_offset);
2438 } else {
2439 if (++refcount_table[k] == 0) {
2440 printf("ERROR: overflow cluster offset=0x%llx\n", cluster_offset);
2446 static int check_refcounts_l1(BlockDriverState *bs,
2447 uint16_t *refcount_table,
2448 int refcount_table_size,
2449 int64_t l1_table_offset, int l1_size,
2450 int check_copied)
2452 BDRVQcowState *s = bs->opaque;
2453 uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2;
2454 int l2_size, i, j, nb_csectors, refcount;
2456 l2_table = NULL;
2457 l1_size2 = l1_size * sizeof(uint64_t);
2459 inc_refcounts(bs, refcount_table, refcount_table_size,
2460 l1_table_offset, l1_size2);
2462 l1_table = qemu_malloc(l1_size2);
2463 if (bdrv_pread(s->hd, l1_table_offset,
2464 l1_table, l1_size2) != l1_size2)
2465 goto fail;
2466 for(i = 0;i < l1_size; i++)
2467 be64_to_cpus(&l1_table[i]);
2469 l2_size = s->l2_size * sizeof(uint64_t);
2470 l2_table = qemu_malloc(l2_size);
2471 for(i = 0; i < l1_size; i++) {
2472 l2_offset = l1_table[i];
2473 if (l2_offset) {
2474 if (check_copied) {
2475 refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
2476 if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
2477 printf("ERROR OFLAG_COPIED: l2_offset=%llx refcount=%d\n",
2478 l2_offset, refcount);
2481 l2_offset &= ~QCOW_OFLAG_COPIED;
2482 if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
2483 goto fail;
2484 for(j = 0; j < s->l2_size; j++) {
2485 offset = be64_to_cpu(l2_table[j]);
2486 if (offset != 0) {
2487 if (offset & QCOW_OFLAG_COMPRESSED) {
2488 if (offset & QCOW_OFLAG_COPIED) {
2489 printf("ERROR: cluster %lld: copied flag must never be set for compressed clusters\n",
2490 offset >> s->cluster_bits);
2491 offset &= ~QCOW_OFLAG_COPIED;
2493 nb_csectors = ((offset >> s->csize_shift) &
2494 s->csize_mask) + 1;
2495 offset &= s->cluster_offset_mask;
2496 inc_refcounts(bs, refcount_table,
2497 refcount_table_size,
2498 offset & ~511, nb_csectors * 512);
2499 } else {
2500 if (check_copied) {
2501 refcount = get_refcount(bs, (offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
2502 if ((refcount == 1) != ((offset & QCOW_OFLAG_COPIED) != 0)) {
2503 printf("ERROR OFLAG_COPIED: offset=%llx refcount=%d\n",
2504 offset, refcount);
2507 offset &= ~QCOW_OFLAG_COPIED;
2508 inc_refcounts(bs, refcount_table,
2509 refcount_table_size,
2510 offset, s->cluster_size);
2514 inc_refcounts(bs, refcount_table,
2515 refcount_table_size,
2516 l2_offset,
2517 s->cluster_size);
2520 qemu_free(l1_table);
2521 qemu_free(l2_table);
2522 return 0;
2523 fail:
2524 printf("ERROR: I/O error in check_refcounts_l1\n");
2525 qemu_free(l1_table);
2526 qemu_free(l2_table);
2527 return -EIO;
2530 static void check_refcounts(BlockDriverState *bs)
2532 BDRVQcowState *s = bs->opaque;
2533 int64_t size;
2534 int nb_clusters, refcount1, refcount2, i;
2535 QCowSnapshot *sn;
2536 uint16_t *refcount_table;
2538 size = bdrv_getlength(s->hd);
2539 nb_clusters = size_to_clusters(s, size);
2540 refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));
2542 /* header */
2543 inc_refcounts(bs, refcount_table, nb_clusters,
2544 0, s->cluster_size);
2546 check_refcounts_l1(bs, refcount_table, nb_clusters,
2547 s->l1_table_offset, s->l1_size, 1);
2549 /* snapshots */
2550 for(i = 0; i < s->nb_snapshots; i++) {
2551 sn = s->snapshots + i;
2552 check_refcounts_l1(bs, refcount_table, nb_clusters,
2553 sn->l1_table_offset, sn->l1_size, 0);
2555 inc_refcounts(bs, refcount_table, nb_clusters,
2556 s->snapshots_offset, s->snapshots_size);
2558 /* refcount data */
2559 inc_refcounts(bs, refcount_table, nb_clusters,
2560 s->refcount_table_offset,
2561 s->refcount_table_size * sizeof(uint64_t));
2562 for(i = 0; i < s->refcount_table_size; i++) {
2563 int64_t offset;
2564 offset = s->refcount_table[i];
2565 if (offset != 0) {
2566 inc_refcounts(bs, refcount_table, nb_clusters,
2567 offset, s->cluster_size);
2571 /* compare ref counts */
2572 for(i = 0; i < nb_clusters; i++) {
2573 refcount1 = get_refcount(bs, i);
2574 refcount2 = refcount_table[i];
2575 if (refcount1 != refcount2)
2576 printf("ERROR cluster %d refcount=%d reference=%d\n",
2577 i, refcount1, refcount2);
2580 qemu_free(refcount_table);
2583 #if 0
2584 static void dump_refcounts(BlockDriverState *bs)
2586 BDRVQcowState *s = bs->opaque;
2587 int64_t nb_clusters, k, k1, size;
2588 int refcount;
2590 size = bdrv_getlength(s->hd);
2591 nb_clusters = size_to_clusters(s, size);
2592 for(k = 0; k < nb_clusters;) {
2593 k1 = k;
2594 refcount = get_refcount(bs, k);
2595 k++;
2596 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2597 k++;
2598 printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
2601 #endif
2602 #endif
2604 static int qcow_put_buffer(BlockDriverState *bs, const uint8_t *buf,
2605 int64_t pos, int size)
2607 int growable = bs->growable;
2609 bs->growable = 1;
2610 bdrv_pwrite(bs, pos, buf, size);
2611 bs->growable = growable;
2613 return size;
2616 static int qcow_get_buffer(BlockDriverState *bs, uint8_t *buf,
2617 int64_t pos, int size)
2619 int growable = bs->growable;
2620 int ret;
2622 bs->growable = 1;
2623 ret = bdrv_pread(bs, pos, buf, size);
2624 bs->growable = growable;
2626 return ret;
2629 BlockDriver bdrv_qcow2 = {
2630 "qcow2",
2631 sizeof(BDRVQcowState),
2632 qcow_probe,
2633 qcow_open,
2634 NULL,
2635 NULL,
2636 qcow_close,
2637 qcow_create,
2638 qcow_flush,
2639 qcow_is_allocated,
2640 qcow_set_key,
2641 qcow_make_empty,
2643 .bdrv_aio_read = qcow_aio_read,
2644 .bdrv_aio_write = qcow_aio_write,
2645 .bdrv_aio_cancel = qcow_aio_cancel,
2646 .aiocb_size = sizeof(QCowAIOCB),
2647 .bdrv_write_compressed = qcow_write_compressed,
2649 .bdrv_snapshot_create = qcow_snapshot_create,
2650 .bdrv_snapshot_goto = qcow_snapshot_goto,
2651 .bdrv_snapshot_delete = qcow_snapshot_delete,
2652 .bdrv_snapshot_list = qcow_snapshot_list,
2653 .bdrv_get_info = qcow_get_info,
2655 .bdrv_put_buffer = qcow_put_buffer,
2656 .bdrv_get_buffer = qcow_get_buffer,