Cleanup {alloc|get}_cluster_offset() (Gleb Natapov)
[qemu] / block-qcow2.c
1 /*
2  * Block driver for the QCOW version 2 format
3  *
4  * Copyright (c) 2004-2006 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 #include "qemu-common.h"
25 #include "block_int.h"
26 #include <zlib.h>
27 #include "aes.h"
28 #include <assert.h>
29
30 /*
31   Differences with QCOW:
32
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.
44 */
45
46 //#define DEBUG_ALLOC
47 //#define DEBUG_ALLOC2
48
49 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
50 #define QCOW_VERSION 2
51
52 #define QCOW_CRYPT_NONE 0
53 #define QCOW_CRYPT_AES  1
54
55 #define QCOW_MAX_CRYPT_CLUSTERS 32
56
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)
61
62 #define REFCOUNT_SHIFT 1 /* refcount size is 2 bytes */
63
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;
79
80 typedef struct __attribute__((packed)) QCowSnapshotHeader {
81     /* header is 8 byte aligned */
82     uint64_t l1_table_offset;
83
84     uint32_t l1_size;
85     uint16_t id_str_size;
86     uint16_t name_size;
87
88     uint32_t date_sec;
89     uint32_t date_nsec;
90
91     uint64_t vm_clock_nsec;
92
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;
99
100 #define L2_CACHE_SIZE 16
101
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;
112
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;
133
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;
141
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;
151
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
173
174 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
175 {
176     const QCowHeader *cow_header = (const void *)buf;
177
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;
184 }
185
186 static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
187 {
188     BDRVQcowState *s = bs->opaque;
189     int len, i, shift, ret;
190     QCowHeader header;
191
192     ret = bdrv_file_open(&s->hd, filename, flags);
193     if (ret < 0)
194         return ret;
195     if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
196         goto fail;
197     be32_to_cpus(&header.magic);
198     be32_to_cpus(&header.version);
199     be64_to_cpus(&header.backing_file_offset);
200     be32_to_cpus(&header.backing_file_size);
201     be64_to_cpus(&header.size);
202     be32_to_cpus(&header.cluster_bits);
203     be32_to_cpus(&header.crypt_method);
204     be64_to_cpus(&header.l1_table_offset);
205     be32_to_cpus(&header.l1_size);
206     be64_to_cpus(&header.refcount_table_offset);
207     be32_to_cpus(&header.refcount_table_clusters);
208     be64_to_cpus(&header.snapshots_offset);
209     be32_to_cpus(&header.nb_snapshots);
210
211     if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
212         goto fail;
213     if (header.size <= 1 ||
214         header.cluster_bits < 9 ||
215         header.cluster_bits > 16)
216         goto fail;
217     if (header.crypt_method > QCOW_CRYPT_AES)
218         goto fail;
219     s->crypt_method_header = header.crypt_method;
220     if (s->crypt_method_header)
221         bs->encrypted = 1;
222     s->cluster_bits = header.cluster_bits;
223     s->cluster_size = 1 << s->cluster_bits;
224     s->cluster_sectors = 1 << (s->cluster_bits - 9);
225     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
226     s->l2_size = 1 << s->l2_bits;
227     bs->total_sectors = header.size / 512;
228     s->csize_shift = (62 - (s->cluster_bits - 8));
229     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
230     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
231     s->refcount_table_offset = header.refcount_table_offset;
232     s->refcount_table_size =
233         header.refcount_table_clusters << (s->cluster_bits - 3);
234
235     s->snapshots_offset = header.snapshots_offset;
236     s->nb_snapshots = header.nb_snapshots;
237
238     /* read the level 1 table */
239     s->l1_size = header.l1_size;
240     shift = s->cluster_bits + s->l2_bits;
241     s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
242     /* the L1 table must contain at least enough entries to put
243        header.size bytes */
244     if (s->l1_size < s->l1_vm_state_index)
245         goto fail;
246     s->l1_table_offset = header.l1_table_offset;
247     s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
248     if (!s->l1_table)
249         goto fail;
250     if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
251         s->l1_size * sizeof(uint64_t))
252         goto fail;
253     for(i = 0;i < s->l1_size; i++) {
254         be64_to_cpus(&s->l1_table[i]);
255     }
256     /* alloc L2 cache */
257     s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
258     if (!s->l2_cache)
259         goto fail;
260     s->cluster_cache = qemu_malloc(s->cluster_size);
261     if (!s->cluster_cache)
262         goto fail;
263     /* one more sector for decompressed data alignment */
264     s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
265                                   + 512);
266     if (!s->cluster_data)
267         goto fail;
268     s->cluster_cache_offset = -1;
269
270     if (refcount_init(bs) < 0)
271         goto fail;
272
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';
281     }
282     if (qcow_read_snapshots(bs) < 0)
283         goto fail;
284
285 #ifdef DEBUG_ALLOC
286     check_refcounts(bs);
287 #endif
288     return 0;
289
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;
299 }
300
301 static int qcow_set_key(BlockDriverState *bs, const char *key)
302 {
303     BDRVQcowState *s = bs->opaque;
304     uint8_t keybuf[16];
305     int len, i;
306
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];
315     }
316     s->crypt_method = s->crypt_method_header;
317
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 */
324     {
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");
338     }
339 #endif
340     return 0;
341 }
342
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)
350 {
351     union {
352         uint64_t ll[2];
353         uint8_t b[16];
354     } ivec;
355     int i;
356
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;
365     }
366 }
367
368 static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,
369                         uint64_t cluster_offset, int n_start, int n_end)
370 {
371     BDRVQcowState *s = bs->opaque;
372     int n, ret;
373
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);
385     }
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;
391 }
392
393 static void l2_cache_reset(BlockDriverState *bs)
394 {
395     BDRVQcowState *s = bs->opaque;
396
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));
400 }
401
402 static inline int l2_cache_new_entry(BlockDriverState *bs)
403 {
404     BDRVQcowState *s = bs->opaque;
405     uint32_t min_count;
406     int min_index, i;
407
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;
415         }
416     }
417     return min_index;
418 }
419
420 static int64_t align_offset(int64_t offset, int n)
421 {
422     offset = (offset + n - 1) & ~(n - 1);
423     return offset;
424 }
425
426 static int grow_l1_table(BlockDriverState *bs, int min_size)
427 {
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];
433
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;
439     }
440 #ifdef DEBUG_ALLOC2
441     printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
442 #endif
443
444     new_l1_size2 = sizeof(uint64_t) * new_l1_size;
445     new_l1_table = qemu_mallocz(new_l1_size2);
446     if (!new_l1_table)
447         return -ENOMEM;
448     memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
449
450     /* write new table (align to cluster) */
451     new_l1_table_offset = alloc_clusters(bs, new_l1_size2);
452
453     for(i = 0; i < s->l1_size; i++)
454         new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
455     ret = bdrv_pwrite(s->hd, new_l1_table_offset, new_l1_table, new_l1_size2);
456     if (ret != new_l1_size2)
457         goto fail;
458     for(i = 0; i < s->l1_size; i++)
459         new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
460
461     /* set new table */
462     cpu_to_be32w((uint32_t*)data, new_l1_size);
463     cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);
464     if (bdrv_pwrite(s->hd, offsetof(QCowHeader, l1_size), data,
465                 sizeof(data)) != sizeof(data))
466         goto fail;
467     qemu_free(s->l1_table);
468     free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
469     s->l1_table_offset = new_l1_table_offset;
470     s->l1_table = new_l1_table;
471     s->l1_size = new_l1_size;
472     return 0;
473  fail:
474     qemu_free(s->l1_table);
475     return -EIO;
476 }
477
478 /*
479  * seek_l2_table
480  *
481  * seek l2_offset in the l2_cache table
482  * if not found, return NULL,
483  * if found,
484  *   increments the l2 cache hit count of the entry,
485  *   if counter overflow, divide by two all counters
486  *   return the pointer to the l2 cache entry
487  *
488  */
489
490 static uint64_t *seek_l2_table(BDRVQcowState *s, uint64_t l2_offset)
491 {
492     int i, j;
493
494     for(i = 0; i < L2_CACHE_SIZE; i++) {
495         if (l2_offset == s->l2_cache_offsets[i]) {
496             /* increment the hit count */
497             if (++s->l2_cache_counts[i] == 0xffffffff) {
498                 for(j = 0; j < L2_CACHE_SIZE; j++) {
499                     s->l2_cache_counts[j] >>= 1;
500                 }
501             }
502             return s->l2_cache + (i << s->l2_bits);
503         }
504     }
505     return NULL;
506 }
507
508 /*
509  * l2_load
510  *
511  * Loads a L2 table into memory. If the table is in the cache, the cache
512  * is used; otherwise the L2 table is loaded from the image file.
513  *
514  * Returns a pointer to the L2 table on success, or NULL if the read from
515  * the image file failed.
516  */
517
518 static uint64_t *l2_load(BlockDriverState *bs, uint64_t l2_offset)
519 {
520     BDRVQcowState *s = bs->opaque;
521     int min_index;
522     uint64_t *l2_table;
523
524     /* seek if the table for the given offset is in the cache */
525
526     l2_table = seek_l2_table(s, l2_offset);
527     if (l2_table != NULL)
528         return l2_table;
529
530     /* not found: load a new entry in the least used one */
531
532     min_index = l2_cache_new_entry(bs);
533     l2_table = s->l2_cache + (min_index << s->l2_bits);
534     if (bdrv_pread(s->hd, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
535         s->l2_size * sizeof(uint64_t))
536         return NULL;
537     s->l2_cache_offsets[min_index] = l2_offset;
538     s->l2_cache_counts[min_index] = 1;
539
540     return l2_table;
541 }
542
543 /*
544  * l2_allocate
545  *
546  * Allocate a new l2 entry in the file. If l1_index points to an already
547  * used entry in the L2 table (i.e. we are doing a copy on write for the L2
548  * table) copy the contents of the old L2 table into the newly allocated one.
549  * Otherwise the new table is initialized with zeros.
550  *
551  */
552
553 static uint64_t *l2_allocate(BlockDriverState *bs, int l1_index)
554 {
555     BDRVQcowState *s = bs->opaque;
556     int min_index;
557     uint64_t old_l2_offset, tmp;
558     uint64_t *l2_table, l2_offset;
559
560     old_l2_offset = s->l1_table[l1_index];
561
562     /* allocate a new l2 entry */
563
564     l2_offset = alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
565
566     /* update the L1 entry */
567
568     s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
569
570     tmp = cpu_to_be64(l2_offset | QCOW_OFLAG_COPIED);
571     if (bdrv_pwrite(s->hd, s->l1_table_offset + l1_index * sizeof(tmp),
572                     &tmp, sizeof(tmp)) != sizeof(tmp))
573         return NULL;
574
575     /* allocate a new entry in the l2 cache */
576
577     min_index = l2_cache_new_entry(bs);
578     l2_table = s->l2_cache + (min_index << s->l2_bits);
579
580     if (old_l2_offset == 0) {
581         /* if there was no old l2 table, clear the new table */
582         memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
583     } else {
584         /* if there was an old l2 table, read it from the disk */
585         if (bdrv_pread(s->hd, old_l2_offset,
586                        l2_table, s->l2_size * sizeof(uint64_t)) !=
587             s->l2_size * sizeof(uint64_t))
588             return NULL;
589     }
590     /* write the l2 table to the file */
591     if (bdrv_pwrite(s->hd, l2_offset,
592                     l2_table, s->l2_size * sizeof(uint64_t)) !=
593         s->l2_size * sizeof(uint64_t))
594         return NULL;
595
596     /* update the l2 cache entry */
597
598     s->l2_cache_offsets[min_index] = l2_offset;
599     s->l2_cache_counts[min_index] = 1;
600
601     return l2_table;
602 }
603
604 static int size_to_clusters(BDRVQcowState *s, int64_t size)
605 {
606     return (size + (s->cluster_size - 1)) >> s->cluster_bits;
607 }
608
609 static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
610         uint64_t *l2_table, uint64_t mask)
611 {
612     int i;
613     uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask;
614
615     for (i = 0; i < nb_clusters; i++)
616         if (offset + i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask))
617             break;
618
619         return i;
620 }
621
622 static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
623 {
624     int i = 0;
625
626     while(nb_clusters-- && l2_table[i] == 0)
627         i++;
628
629     return i;
630 }
631
632 /*
633  * get_cluster_offset
634  *
635  * For a given offset of the disk image, return cluster offset in
636  * qcow2 file.
637  *
638  * on entry, *num is the number of contiguous clusters we'd like to
639  * access following offset.
640  *
641  * on exit, *num is the number of contiguous clusters we can read.
642  *
643  * Return 1, if the offset is found
644  * Return 0, otherwise.
645  *
646  */
647
648 static uint64_t get_cluster_offset(BlockDriverState *bs,
649                                    uint64_t offset, int *num)
650 {
651     BDRVQcowState *s = bs->opaque;
652     int l1_index, l2_index;
653     uint64_t l2_offset, *l2_table, cluster_offset;
654     int l1_bits, c;
655     int index_in_cluster, nb_available, nb_needed, nb_clusters;
656
657     index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
658     nb_needed = *num + index_in_cluster;
659
660     l1_bits = s->l2_bits + s->cluster_bits;
661
662     /* compute how many bytes there are between the offset and
663      * the end of the l1 entry
664      */
665
666     nb_available = (1 << l1_bits) - (offset & ((1 << l1_bits) - 1));
667
668     /* compute the number of available sectors */
669
670     nb_available = (nb_available >> 9) + index_in_cluster;
671
672     cluster_offset = 0;
673
674     /* seek the the l2 offset in the l1 table */
675
676     l1_index = offset >> l1_bits;
677     if (l1_index >= s->l1_size)
678         goto out;
679
680     l2_offset = s->l1_table[l1_index];
681
682     /* seek the l2 table of the given l2 offset */
683
684     if (!l2_offset)
685         goto out;
686
687     /* load the l2 table in memory */
688
689     l2_offset &= ~QCOW_OFLAG_COPIED;
690     l2_table = l2_load(bs, l2_offset);
691     if (l2_table == NULL)
692         return 0;
693
694     /* find the cluster offset for the given disk offset */
695
696     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
697     cluster_offset = be64_to_cpu(l2_table[l2_index]);
698     nb_clusters = size_to_clusters(s, nb_needed << 9);
699
700     if (!cluster_offset) {
701         /* how many empty clusters ? */
702         c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
703     } else {
704         /* how many allocated clusters ? */
705         c = count_contiguous_clusters(nb_clusters, s->cluster_size,
706                 &l2_table[l2_index], QCOW_OFLAG_COPIED);
707     }
708
709    nb_available = (c * s->cluster_sectors);
710 out:
711     if (nb_available > nb_needed)
712         nb_available = nb_needed;
713
714     *num = nb_available - index_in_cluster;
715
716     return cluster_offset & ~QCOW_OFLAG_COPIED;
717 }
718
719 /*
720  * free_any_clusters
721  *
722  * free clusters according to its type: compressed or not
723  *
724  */
725
726 static void free_any_clusters(BlockDriverState *bs,
727                               uint64_t cluster_offset, int nb_clusters)
728 {
729     BDRVQcowState *s = bs->opaque;
730
731     /* free the cluster */
732
733     if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
734         int nb_csectors;
735         nb_csectors = ((cluster_offset >> s->csize_shift) &
736                        s->csize_mask) + 1;
737         free_clusters(bs, (cluster_offset & s->cluster_offset_mask) & ~511,
738                       nb_csectors * 512);
739         return;
740     }
741
742     free_clusters(bs, cluster_offset, nb_clusters << s->cluster_bits);
743
744     return;
745 }
746
747 /*
748  * get_cluster_table
749  *
750  * for a given disk offset, load (and allocate if needed)
751  * the l2 table.
752  *
753  * the l2 table offset in the qcow2 file and the cluster index
754  * in the l2 table are given to the caller.
755  *
756  */
757
758 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
759                              uint64_t **new_l2_table,
760                              uint64_t *new_l2_offset,
761                              int *new_l2_index)
762 {
763     BDRVQcowState *s = bs->opaque;
764     int l1_index, l2_index, ret;
765     uint64_t l2_offset, *l2_table;
766
767     /* seek the the l2 offset in the l1 table */
768
769     l1_index = offset >> (s->l2_bits + s->cluster_bits);
770     if (l1_index >= s->l1_size) {
771         ret = grow_l1_table(bs, l1_index + 1);
772         if (ret < 0)
773             return 0;
774     }
775     l2_offset = s->l1_table[l1_index];
776
777     /* seek the l2 table of the given l2 offset */
778
779     if (l2_offset & QCOW_OFLAG_COPIED) {
780         /* load the l2 table in memory */
781         l2_offset &= ~QCOW_OFLAG_COPIED;
782         l2_table = l2_load(bs, l2_offset);
783         if (l2_table == NULL)
784             return 0;
785     } else {
786         if (l2_offset)
787             free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
788         l2_table = l2_allocate(bs, l1_index);
789         if (l2_table == NULL)
790             return 0;
791         l2_offset = s->l1_table[l1_index] & ~QCOW_OFLAG_COPIED;
792     }
793
794     /* find the cluster offset for the given disk offset */
795
796     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
797
798     *new_l2_table = l2_table;
799     *new_l2_offset = l2_offset;
800     *new_l2_index = l2_index;
801
802     return 1;
803 }
804
805 /*
806  * alloc_compressed_cluster_offset
807  *
808  * For a given offset of the disk image, return cluster offset in
809  * qcow2 file.
810  *
811  * If the offset is not found, allocate a new compressed cluster.
812  *
813  * Return the cluster offset if successful,
814  * Return 0, otherwise.
815  *
816  */
817
818 static uint64_t alloc_compressed_cluster_offset(BlockDriverState *bs,
819                                                 uint64_t offset,
820                                                 int compressed_size)
821 {
822     BDRVQcowState *s = bs->opaque;
823     int l2_index, ret;
824     uint64_t l2_offset, *l2_table, cluster_offset;
825     int nb_csectors;
826
827     ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
828     if (ret == 0)
829         return 0;
830
831     cluster_offset = be64_to_cpu(l2_table[l2_index]);
832     if (cluster_offset & QCOW_OFLAG_COPIED)
833         return cluster_offset & ~QCOW_OFLAG_COPIED;
834
835     if (cluster_offset)
836         free_any_clusters(bs, cluster_offset, 1);
837
838     cluster_offset = alloc_bytes(bs, compressed_size);
839     nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
840                   (cluster_offset >> 9);
841
842     cluster_offset |= QCOW_OFLAG_COMPRESSED |
843                       ((uint64_t)nb_csectors << s->csize_shift);
844
845     /* update L2 table */
846
847     /* compressed clusters never have the copied flag */
848
849     l2_table[l2_index] = cpu_to_be64(cluster_offset);
850     if (bdrv_pwrite(s->hd,
851                     l2_offset + l2_index * sizeof(uint64_t),
852                     l2_table + l2_index,
853                     sizeof(uint64_t)) != sizeof(uint64_t))
854         return 0;
855
856     return cluster_offset;
857 }
858
859 /*
860  * alloc_cluster_offset
861  *
862  * For a given offset of the disk image, return cluster offset in
863  * qcow2 file.
864  *
865  * If the offset is not found, allocate a new cluster.
866  *
867  * Return the cluster offset if successful,
868  * Return 0, otherwise.
869  *
870  */
871
872 static uint64_t alloc_cluster_offset(BlockDriverState *bs,
873                                      uint64_t offset,
874                                      int n_start, int n_end,
875                                      int *num)
876 {
877     BDRVQcowState *s = bs->opaque;
878     int l2_index, ret;
879     uint64_t l2_offset, *l2_table, cluster_offset;
880     int nb_available, nb_clusters, i = 0;
881     uint64_t start_sect;
882
883     ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
884     if (ret == 0)
885         return 0;
886
887     nb_clusters = size_to_clusters(s, n_end << 9);
888
889     if (nb_clusters > s->l2_size - l2_index)
890             nb_clusters = s->l2_size - l2_index;
891
892     cluster_offset = be64_to_cpu(l2_table[l2_index]);
893
894     /* We keep all QCOW_OFLAG_COPIED clusters */
895
896     if (cluster_offset & QCOW_OFLAG_COPIED) {
897         nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
898                 &l2_table[l2_index], 0);
899
900         nb_available = nb_clusters << (s->cluster_bits - 9);
901         if (nb_available > n_end)
902             nb_available = n_end;
903
904         cluster_offset &= ~QCOW_OFLAG_COPIED;
905
906         goto out;
907     }
908
909     /* for the moment, multiple compressed clusters are not managed */
910
911     if (cluster_offset & QCOW_OFLAG_COMPRESSED)
912         nb_clusters = 1;
913
914     /* how many available clusters ? */
915
916     while (i < nb_clusters) {
917         int j;
918         i += count_contiguous_free_clusters(nb_clusters - i,
919                 &l2_table[l2_index + i]);
920
921         cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
922
923         if ((cluster_offset & QCOW_OFLAG_COPIED) ||
924                 (cluster_offset & QCOW_OFLAG_COMPRESSED))
925             break;
926
927         j = count_contiguous_clusters(nb_clusters - i, s->cluster_size,
928                 &l2_table[l2_index + i], 0);
929
930         if (j)
931             free_any_clusters(bs, cluster_offset, j);
932
933         i += j;
934
935         if(be64_to_cpu(l2_table[l2_index + i]))
936             break;
937     }
938     nb_clusters = i;
939
940     /* allocate a new cluster */
941
942     cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);
943
944     /* we must initialize the cluster content which won't be
945        written */
946
947     nb_available = nb_clusters << (s->cluster_bits - 9);
948     if (nb_available > n_end)
949         nb_available = n_end;
950
951     /* copy content of unmodified sectors */
952
953     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
954     if (n_start) {
955         ret = copy_sectors(bs, start_sect, cluster_offset, 0, n_start);
956         if (ret < 0)
957             return 0;
958     }
959
960     if (nb_available & (s->cluster_sectors - 1)) {
961         uint64_t end = nb_available & ~(uint64_t)(s->cluster_sectors - 1);
962         ret = copy_sectors(bs, start_sect + end,
963                            cluster_offset + (end << 9),
964                            nb_available - end,
965                            s->cluster_sectors);
966         if (ret < 0)
967             return 0;
968     }
969
970     /* update L2 table */
971
972     for (i = 0; i < nb_clusters; i++)
973         l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
974                                              (i << s->cluster_bits)) |
975                                              QCOW_OFLAG_COPIED);
976
977     if (bdrv_pwrite(s->hd,
978                     l2_offset + l2_index * sizeof(uint64_t),
979                     l2_table + l2_index,
980                     nb_clusters * sizeof(uint64_t)) !=
981                     nb_clusters * sizeof(uint64_t))
982         return 0;
983
984 out:
985     *num = nb_available - n_start;
986
987     return cluster_offset;
988 }
989
990 static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
991                              int nb_sectors, int *pnum)
992 {
993     uint64_t cluster_offset;
994
995     *pnum = nb_sectors;
996     cluster_offset = get_cluster_offset(bs, sector_num << 9, pnum);
997
998     return (cluster_offset != 0);
999 }
1000
1001 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1002                              const uint8_t *buf, int buf_size)
1003 {
1004     z_stream strm1, *strm = &strm1;
1005     int ret, out_len;
1006
1007     memset(strm, 0, sizeof(*strm));
1008
1009     strm->next_in = (uint8_t *)buf;
1010     strm->avail_in = buf_size;
1011     strm->next_out = out_buf;
1012     strm->avail_out = out_buf_size;
1013
1014     ret = inflateInit2(strm, -12);
1015     if (ret != Z_OK)
1016         return -1;
1017     ret = inflate(strm, Z_FINISH);
1018     out_len = strm->next_out - out_buf;
1019     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1020         out_len != out_buf_size) {
1021         inflateEnd(strm);
1022         return -1;
1023     }
1024     inflateEnd(strm);
1025     return 0;
1026 }
1027
1028 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
1029 {
1030     int ret, csize, nb_csectors, sector_offset;
1031     uint64_t coffset;
1032
1033     coffset = cluster_offset & s->cluster_offset_mask;
1034     if (s->cluster_cache_offset != coffset) {
1035         nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1036         sector_offset = coffset & 511;
1037         csize = nb_csectors * 512 - sector_offset;
1038         ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
1039         if (ret < 0) {
1040             return -1;
1041         }
1042         if (decompress_buffer(s->cluster_cache, s->cluster_size,
1043                               s->cluster_data + sector_offset, csize) < 0) {
1044             return -1;
1045         }
1046         s->cluster_cache_offset = coffset;
1047     }
1048     return 0;
1049 }
1050
1051 /* handle reading after the end of the backing file */
1052 static int backing_read1(BlockDriverState *bs,
1053                          int64_t sector_num, uint8_t *buf, int nb_sectors)
1054 {
1055     int n1;
1056     if ((sector_num + nb_sectors) <= bs->total_sectors)
1057         return nb_sectors;
1058     if (sector_num >= bs->total_sectors)
1059         n1 = 0;
1060     else
1061         n1 = bs->total_sectors - sector_num;
1062     memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
1063     return n1;
1064 }
1065
1066 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
1067                      uint8_t *buf, int nb_sectors)
1068 {
1069     BDRVQcowState *s = bs->opaque;
1070     int ret, index_in_cluster, n, n1;
1071     uint64_t cluster_offset;
1072
1073     while (nb_sectors > 0) {
1074         n = nb_sectors;
1075         cluster_offset = get_cluster_offset(bs, sector_num << 9, &n);
1076         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1077         if (!cluster_offset) {
1078             if (bs->backing_hd) {
1079                 /* read from the base image */
1080                 n1 = backing_read1(bs->backing_hd, sector_num, buf, n);
1081                 if (n1 > 0) {
1082                     ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
1083                     if (ret < 0)
1084                         return -1;
1085                 }
1086             } else {
1087                 memset(buf, 0, 512 * n);
1088             }
1089         } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
1090             if (decompress_cluster(s, cluster_offset) < 0)
1091                 return -1;
1092             memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
1093         } else {
1094             ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1095             if (ret != n * 512)
1096                 return -1;
1097             if (s->crypt_method) {
1098                 encrypt_sectors(s, sector_num, buf, buf, n, 0,
1099                                 &s->aes_decrypt_key);
1100             }
1101         }
1102         nb_sectors -= n;
1103         sector_num += n;
1104         buf += n * 512;
1105     }
1106     return 0;
1107 }
1108
1109 static int qcow_write(BlockDriverState *bs, int64_t sector_num,
1110                      const uint8_t *buf, int nb_sectors)
1111 {
1112     BDRVQcowState *s = bs->opaque;
1113     int ret, index_in_cluster, n;
1114     uint64_t cluster_offset;
1115     int n_end;
1116
1117     while (nb_sectors > 0) {
1118         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1119         n_end = index_in_cluster + nb_sectors;
1120         if (s->crypt_method &&
1121             n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1122             n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1123         cluster_offset = alloc_cluster_offset(bs, sector_num << 9,
1124                                               index_in_cluster,
1125                                               n_end, &n);
1126         if (!cluster_offset)
1127             return -1;
1128         if (s->crypt_method) {
1129             encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
1130                             &s->aes_encrypt_key);
1131             ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512,
1132                               s->cluster_data, n * 512);
1133         } else {
1134             ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1135         }
1136         if (ret != n * 512)
1137             return -1;
1138         nb_sectors -= n;
1139         sector_num += n;
1140         buf += n * 512;
1141     }
1142     s->cluster_cache_offset = -1; /* disable compressed cache */
1143     return 0;
1144 }
1145
1146 typedef struct QCowAIOCB {
1147     BlockDriverAIOCB common;
1148     int64_t sector_num;
1149     uint8_t *buf;
1150     int nb_sectors;
1151     int n;
1152     uint64_t cluster_offset;
1153     uint8_t *cluster_data;
1154     BlockDriverAIOCB *hd_aiocb;
1155     QEMUBH *bh;
1156 } QCowAIOCB;
1157
1158 static void qcow_aio_read_cb(void *opaque, int ret);
1159 static void qcow_aio_read_bh(void *opaque)
1160 {
1161     QCowAIOCB *acb = opaque;
1162     qemu_bh_delete(acb->bh);
1163     acb->bh = NULL;
1164     qcow_aio_read_cb(opaque, 0);
1165 }
1166
1167 static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
1168 {
1169     if (acb->bh)
1170         return -EIO;
1171
1172     acb->bh = qemu_bh_new(cb, acb);
1173     if (!acb->bh)
1174         return -EIO;
1175
1176     qemu_bh_schedule(acb->bh);
1177
1178     return 0;
1179 }
1180
1181 static void qcow_aio_read_cb(void *opaque, int ret)
1182 {
1183     QCowAIOCB *acb = opaque;
1184     BlockDriverState *bs = acb->common.bs;
1185     BDRVQcowState *s = bs->opaque;
1186     int index_in_cluster, n1;
1187
1188     acb->hd_aiocb = NULL;
1189     if (ret < 0) {
1190 fail:
1191         acb->common.cb(acb->common.opaque, ret);
1192         qemu_aio_release(acb);
1193         return;
1194     }
1195
1196     /* post process the read buffer */
1197     if (!acb->cluster_offset) {
1198         /* nothing to do */
1199     } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1200         /* nothing to do */
1201     } else {
1202         if (s->crypt_method) {
1203             encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
1204                             acb->n, 0,
1205                             &s->aes_decrypt_key);
1206         }
1207     }
1208
1209     acb->nb_sectors -= acb->n;
1210     acb->sector_num += acb->n;
1211     acb->buf += acb->n * 512;
1212
1213     if (acb->nb_sectors == 0) {
1214         /* request completed */
1215         acb->common.cb(acb->common.opaque, 0);
1216         qemu_aio_release(acb);
1217         return;
1218     }
1219
1220     /* prepare next AIO request */
1221     acb->n = acb->nb_sectors;
1222     acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
1223     index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1224
1225     if (!acb->cluster_offset) {
1226         if (bs->backing_hd) {
1227             /* read from the base image */
1228             n1 = backing_read1(bs->backing_hd, acb->sector_num,
1229                                acb->buf, acb->n);
1230             if (n1 > 0) {
1231                 acb->hd_aiocb = bdrv_aio_read(bs->backing_hd, acb->sector_num,
1232                                     acb->buf, acb->n, qcow_aio_read_cb, acb);
1233                 if (acb->hd_aiocb == NULL)
1234                     goto fail;
1235             } else {
1236                 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1237                 if (ret < 0)
1238                     goto fail;
1239             }
1240         } else {
1241             /* Note: in this case, no need to wait */
1242             memset(acb->buf, 0, 512 * acb->n);
1243             ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1244             if (ret < 0)
1245                 goto fail;
1246         }
1247     } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1248         /* add AIO support for compressed blocks ? */
1249         if (decompress_cluster(s, acb->cluster_offset) < 0)
1250             goto fail;
1251         memcpy(acb->buf,
1252                s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
1253         ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1254         if (ret < 0)
1255             goto fail;
1256     } else {
1257         if ((acb->cluster_offset & 511) != 0) {
1258             ret = -EIO;
1259             goto fail;
1260         }
1261         acb->hd_aiocb = bdrv_aio_read(s->hd,
1262                             (acb->cluster_offset >> 9) + index_in_cluster,
1263                             acb->buf, acb->n, qcow_aio_read_cb, acb);
1264         if (acb->hd_aiocb == NULL)
1265             goto fail;
1266     }
1267 }
1268
1269 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
1270         int64_t sector_num, uint8_t *buf, int nb_sectors,
1271         BlockDriverCompletionFunc *cb, void *opaque)
1272 {
1273     QCowAIOCB *acb;
1274
1275     acb = qemu_aio_get(bs, cb, opaque);
1276     if (!acb)
1277         return NULL;
1278     acb->hd_aiocb = NULL;
1279     acb->sector_num = sector_num;
1280     acb->buf = buf;
1281     acb->nb_sectors = nb_sectors;
1282     acb->n = 0;
1283     acb->cluster_offset = 0;
1284     return acb;
1285 }
1286
1287 static BlockDriverAIOCB *qcow_aio_read(BlockDriverState *bs,
1288         int64_t sector_num, uint8_t *buf, int nb_sectors,
1289         BlockDriverCompletionFunc *cb, void *opaque)
1290 {
1291     QCowAIOCB *acb;
1292
1293     acb = qcow_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
1294     if (!acb)
1295         return NULL;
1296
1297     qcow_aio_read_cb(acb, 0);
1298     return &acb->common;
1299 }
1300
1301 static void qcow_aio_write_cb(void *opaque, int ret)
1302 {
1303     QCowAIOCB *acb = opaque;
1304     BlockDriverState *bs = acb->common.bs;
1305     BDRVQcowState *s = bs->opaque;
1306     int index_in_cluster;
1307     uint64_t cluster_offset;
1308     const uint8_t *src_buf;
1309     int n_end;
1310
1311     acb->hd_aiocb = NULL;
1312
1313     if (ret < 0) {
1314     fail:
1315         acb->common.cb(acb->common.opaque, ret);
1316         qemu_aio_release(acb);
1317         return;
1318     }
1319
1320     acb->nb_sectors -= acb->n;
1321     acb->sector_num += acb->n;
1322     acb->buf += acb->n * 512;
1323
1324     if (acb->nb_sectors == 0) {
1325         /* request completed */
1326         acb->common.cb(acb->common.opaque, 0);
1327         qemu_aio_release(acb);
1328         return;
1329     }
1330
1331     index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1332     n_end = index_in_cluster + acb->nb_sectors;
1333     if (s->crypt_method &&
1334         n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1335         n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1336
1337     cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,
1338                                           index_in_cluster,
1339                                           n_end, &acb->n);
1340     if (!cluster_offset || (cluster_offset & 511) != 0) {
1341         ret = -EIO;
1342         goto fail;
1343     }
1344     if (s->crypt_method) {
1345         if (!acb->cluster_data) {
1346             acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
1347                                              s->cluster_size);
1348             if (!acb->cluster_data) {
1349                 ret = -ENOMEM;
1350                 goto fail;
1351             }
1352         }
1353         encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
1354                         acb->n, 1, &s->aes_encrypt_key);
1355         src_buf = acb->cluster_data;
1356     } else {
1357         src_buf = acb->buf;
1358     }
1359     acb->hd_aiocb = bdrv_aio_write(s->hd,
1360                                    (cluster_offset >> 9) + index_in_cluster,
1361                                    src_buf, acb->n,
1362                                    qcow_aio_write_cb, acb);
1363     if (acb->hd_aiocb == NULL)
1364         goto fail;
1365 }
1366
1367 static BlockDriverAIOCB *qcow_aio_write(BlockDriverState *bs,
1368         int64_t sector_num, const uint8_t *buf, int nb_sectors,
1369         BlockDriverCompletionFunc *cb, void *opaque)
1370 {
1371     BDRVQcowState *s = bs->opaque;
1372     QCowAIOCB *acb;
1373
1374     s->cluster_cache_offset = -1; /* disable compressed cache */
1375
1376     acb = qcow_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
1377     if (!acb)
1378         return NULL;
1379
1380     qcow_aio_write_cb(acb, 0);
1381     return &acb->common;
1382 }
1383
1384 static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
1385 {
1386     QCowAIOCB *acb = (QCowAIOCB *)blockacb;
1387     if (acb->hd_aiocb)
1388         bdrv_aio_cancel(acb->hd_aiocb);
1389     qemu_aio_release(acb);
1390 }
1391
1392 static void qcow_close(BlockDriverState *bs)
1393 {
1394     BDRVQcowState *s = bs->opaque;
1395     qemu_free(s->l1_table);
1396     qemu_free(s->l2_cache);
1397     qemu_free(s->cluster_cache);
1398     qemu_free(s->cluster_data);
1399     refcount_close(bs);
1400     bdrv_delete(s->hd);
1401 }
1402
1403 /* XXX: use std qcow open function ? */
1404 typedef struct QCowCreateState {
1405     int cluster_size;
1406     int cluster_bits;
1407     uint16_t *refcount_block;
1408     uint64_t *refcount_table;
1409     int64_t l1_table_offset;
1410     int64_t refcount_table_offset;
1411     int64_t refcount_block_offset;
1412 } QCowCreateState;
1413
1414 static void create_refcount_update(QCowCreateState *s,
1415                                    int64_t offset, int64_t size)
1416 {
1417     int refcount;
1418     int64_t start, last, cluster_offset;
1419     uint16_t *p;
1420
1421     start = offset & ~(s->cluster_size - 1);
1422     last = (offset + size - 1)  & ~(s->cluster_size - 1);
1423     for(cluster_offset = start; cluster_offset <= last;
1424         cluster_offset += s->cluster_size) {
1425         p = &s->refcount_block[cluster_offset >> s->cluster_bits];
1426         refcount = be16_to_cpu(*p);
1427         refcount++;
1428         *p = cpu_to_be16(refcount);
1429     }
1430 }
1431
1432 static int qcow_create(const char *filename, int64_t total_size,
1433                       const char *backing_file, int flags)
1434 {
1435     int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
1436     QCowHeader header;
1437     uint64_t tmp, offset;
1438     QCowCreateState s1, *s = &s1;
1439
1440     memset(s, 0, sizeof(*s));
1441
1442     fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1443     if (fd < 0)
1444         return -1;
1445     memset(&header, 0, sizeof(header));
1446     header.magic = cpu_to_be32(QCOW_MAGIC);
1447     header.version = cpu_to_be32(QCOW_VERSION);
1448     header.size = cpu_to_be64(total_size * 512);
1449     header_size = sizeof(header);
1450     backing_filename_len = 0;
1451     if (backing_file) {
1452         header.backing_file_offset = cpu_to_be64(header_size);
1453         backing_filename_len = strlen(backing_file);
1454         header.backing_file_size = cpu_to_be32(backing_filename_len);
1455         header_size += backing_filename_len;
1456     }
1457     s->cluster_bits = 12;  /* 4 KB clusters */
1458     s->cluster_size = 1 << s->cluster_bits;
1459     header.cluster_bits = cpu_to_be32(s->cluster_bits);
1460     header_size = (header_size + 7) & ~7;
1461     if (flags & BLOCK_FLAG_ENCRYPT) {
1462         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1463     } else {
1464         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1465     }
1466     l2_bits = s->cluster_bits - 3;
1467     shift = s->cluster_bits + l2_bits;
1468     l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
1469     offset = align_offset(header_size, s->cluster_size);
1470     s->l1_table_offset = offset;
1471     header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
1472     header.l1_size = cpu_to_be32(l1_size);
1473     offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
1474
1475     s->refcount_table = qemu_mallocz(s->cluster_size);
1476     if (!s->refcount_table)
1477         goto fail;
1478     s->refcount_block = qemu_mallocz(s->cluster_size);
1479     if (!s->refcount_block)
1480         goto fail;
1481
1482     s->refcount_table_offset = offset;
1483     header.refcount_table_offset = cpu_to_be64(offset);
1484     header.refcount_table_clusters = cpu_to_be32(1);
1485     offset += s->cluster_size;
1486
1487     s->refcount_table[0] = cpu_to_be64(offset);
1488     s->refcount_block_offset = offset;
1489     offset += s->cluster_size;
1490
1491     /* update refcounts */
1492     create_refcount_update(s, 0, header_size);
1493     create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
1494     create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
1495     create_refcount_update(s, s->refcount_block_offset, s->cluster_size);
1496
1497     /* write all the data */
1498     write(fd, &header, sizeof(header));
1499     if (backing_file) {
1500         write(fd, backing_file, backing_filename_len);
1501     }
1502     lseek(fd, s->l1_table_offset, SEEK_SET);
1503     tmp = 0;
1504     for(i = 0;i < l1_size; i++) {
1505         write(fd, &tmp, sizeof(tmp));
1506     }
1507     lseek(fd, s->refcount_table_offset, SEEK_SET);
1508     write(fd, s->refcount_table, s->cluster_size);
1509
1510     lseek(fd, s->refcount_block_offset, SEEK_SET);
1511     write(fd, s->refcount_block, s->cluster_size);
1512
1513     qemu_free(s->refcount_table);
1514     qemu_free(s->refcount_block);
1515     close(fd);
1516     return 0;
1517  fail:
1518     qemu_free(s->refcount_table);
1519     qemu_free(s->refcount_block);
1520     close(fd);
1521     return -ENOMEM;
1522 }
1523
1524 static int qcow_make_empty(BlockDriverState *bs)
1525 {
1526 #if 0
1527     /* XXX: not correct */
1528     BDRVQcowState *s = bs->opaque;
1529     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1530     int ret;
1531
1532     memset(s->l1_table, 0, l1_length);
1533     if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1534         return -1;
1535     ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1536     if (ret < 0)
1537         return ret;
1538
1539     l2_cache_reset(bs);
1540 #endif
1541     return 0;
1542 }
1543
1544 /* XXX: put compressed sectors first, then all the cluster aligned
1545    tables to avoid losing bytes in alignment */
1546 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1547                                  const uint8_t *buf, int nb_sectors)
1548 {
1549     BDRVQcowState *s = bs->opaque;
1550     z_stream strm;
1551     int ret, out_len;
1552     uint8_t *out_buf;
1553     uint64_t cluster_offset;
1554
1555     if (nb_sectors == 0) {
1556         /* align end of file to a sector boundary to ease reading with
1557            sector based I/Os */
1558         cluster_offset = bdrv_getlength(s->hd);
1559         cluster_offset = (cluster_offset + 511) & ~511;
1560         bdrv_truncate(s->hd, cluster_offset);
1561         return 0;
1562     }
1563
1564     if (nb_sectors != s->cluster_sectors)
1565         return -EINVAL;
1566
1567     out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1568     if (!out_buf)
1569         return -ENOMEM;
1570
1571     /* best compression, small window, no zlib header */
1572     memset(&strm, 0, sizeof(strm));
1573     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1574                        Z_DEFLATED, -12,
1575                        9, Z_DEFAULT_STRATEGY);
1576     if (ret != 0) {
1577         qemu_free(out_buf);
1578         return -1;
1579     }
1580
1581     strm.avail_in = s->cluster_size;
1582     strm.next_in = (uint8_t *)buf;
1583     strm.avail_out = s->cluster_size;
1584     strm.next_out = out_buf;
1585
1586     ret = deflate(&strm, Z_FINISH);
1587     if (ret != Z_STREAM_END && ret != Z_OK) {
1588         qemu_free(out_buf);
1589         deflateEnd(&strm);
1590         return -1;
1591     }
1592     out_len = strm.next_out - out_buf;
1593
1594     deflateEnd(&strm);
1595
1596     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1597         /* could not compress: write normal cluster */
1598         qcow_write(bs, sector_num, buf, s->cluster_sectors);
1599     } else {
1600         cluster_offset = alloc_compressed_cluster_offset(bs, sector_num << 9,
1601                                               out_len);
1602         if (!cluster_offset)
1603             return -1;
1604         cluster_offset &= s->cluster_offset_mask;
1605         if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1606             qemu_free(out_buf);
1607             return -1;
1608         }
1609     }
1610
1611     qemu_free(out_buf);
1612     return 0;
1613 }
1614
1615 static void qcow_flush(BlockDriverState *bs)
1616 {
1617     BDRVQcowState *s = bs->opaque;
1618     bdrv_flush(s->hd);
1619 }
1620
1621 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1622 {
1623     BDRVQcowState *s = bs->opaque;
1624     bdi->cluster_size = s->cluster_size;
1625     bdi->vm_state_offset = (int64_t)s->l1_vm_state_index <<
1626         (s->cluster_bits + s->l2_bits);
1627     return 0;
1628 }
1629
1630 /*********************************************************/
1631 /* snapshot support */
1632
1633 /* update the refcounts of snapshots and the copied flag */
1634 static int update_snapshot_refcount(BlockDriverState *bs,
1635                                     int64_t l1_table_offset,
1636                                     int l1_size,
1637                                     int addend)
1638 {
1639     BDRVQcowState *s = bs->opaque;
1640     uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;
1641     int64_t old_offset, old_l2_offset;
1642     int l2_size, i, j, l1_modified, l2_modified, nb_csectors, refcount;
1643
1644     l2_cache_reset(bs);
1645
1646     l2_table = NULL;
1647     l1_table = NULL;
1648     l1_size2 = l1_size * sizeof(uint64_t);
1649     l1_allocated = 0;
1650     if (l1_table_offset != s->l1_table_offset) {
1651         l1_table = qemu_malloc(l1_size2);
1652         if (!l1_table)
1653             goto fail;
1654         l1_allocated = 1;
1655         if (bdrv_pread(s->hd, l1_table_offset,
1656                        l1_table, l1_size2) != l1_size2)
1657             goto fail;
1658         for(i = 0;i < l1_size; i++)
1659             be64_to_cpus(&l1_table[i]);
1660     } else {
1661         assert(l1_size == s->l1_size);
1662         l1_table = s->l1_table;
1663         l1_allocated = 0;
1664     }
1665
1666     l2_size = s->l2_size * sizeof(uint64_t);
1667     l2_table = qemu_malloc(l2_size);
1668     if (!l2_table)
1669         goto fail;
1670     l1_modified = 0;
1671     for(i = 0; i < l1_size; i++) {
1672         l2_offset = l1_table[i];
1673         if (l2_offset) {
1674             old_l2_offset = l2_offset;
1675             l2_offset &= ~QCOW_OFLAG_COPIED;
1676             l2_modified = 0;
1677             if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
1678                 goto fail;
1679             for(j = 0; j < s->l2_size; j++) {
1680                 offset = be64_to_cpu(l2_table[j]);
1681                 if (offset != 0) {
1682                     old_offset = offset;
1683                     offset &= ~QCOW_OFLAG_COPIED;
1684                     if (offset & QCOW_OFLAG_COMPRESSED) {
1685                         nb_csectors = ((offset >> s->csize_shift) &
1686                                        s->csize_mask) + 1;
1687                         if (addend != 0)
1688                             update_refcount(bs, (offset & s->cluster_offset_mask) & ~511,
1689                                             nb_csectors * 512, addend);
1690                         /* compressed clusters are never modified */
1691                         refcount = 2;
1692                     } else {
1693                         if (addend != 0) {
1694                             refcount = update_cluster_refcount(bs, offset >> s->cluster_bits, addend);
1695                         } else {
1696                             refcount = get_refcount(bs, offset >> s->cluster_bits);
1697                         }
1698                     }
1699
1700                     if (refcount == 1) {
1701                         offset |= QCOW_OFLAG_COPIED;
1702                     }
1703                     if (offset != old_offset) {
1704                         l2_table[j] = cpu_to_be64(offset);
1705                         l2_modified = 1;
1706                     }
1707                 }
1708             }
1709             if (l2_modified) {
1710                 if (bdrv_pwrite(s->hd,
1711                                 l2_offset, l2_table, l2_size) != l2_size)
1712                     goto fail;
1713             }
1714
1715             if (addend != 0) {
1716                 refcount = update_cluster_refcount(bs, l2_offset >> s->cluster_bits, addend);
1717             } else {
1718                 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1719             }
1720             if (refcount == 1) {
1721                 l2_offset |= QCOW_OFLAG_COPIED;
1722             }
1723             if (l2_offset != old_l2_offset) {
1724                 l1_table[i] = l2_offset;
1725                 l1_modified = 1;
1726             }
1727         }
1728     }
1729     if (l1_modified) {
1730         for(i = 0; i < l1_size; i++)
1731             cpu_to_be64s(&l1_table[i]);
1732         if (bdrv_pwrite(s->hd, l1_table_offset, l1_table,
1733                         l1_size2) != l1_size2)
1734             goto fail;
1735         for(i = 0; i < l1_size; i++)
1736             be64_to_cpus(&l1_table[i]);
1737     }
1738     if (l1_allocated)
1739         qemu_free(l1_table);
1740     qemu_free(l2_table);
1741     return 0;
1742  fail:
1743     if (l1_allocated)
1744         qemu_free(l1_table);
1745     qemu_free(l2_table);
1746     return -EIO;
1747 }
1748
1749 static void qcow_free_snapshots(BlockDriverState *bs)
1750 {
1751     BDRVQcowState *s = bs->opaque;
1752     int i;
1753
1754     for(i = 0; i < s->nb_snapshots; i++) {
1755         qemu_free(s->snapshots[i].name);
1756         qemu_free(s->snapshots[i].id_str);
1757     }
1758     qemu_free(s->snapshots);
1759     s->snapshots = NULL;
1760     s->nb_snapshots = 0;
1761 }
1762
1763 static int qcow_read_snapshots(BlockDriverState *bs)
1764 {
1765     BDRVQcowState *s = bs->opaque;
1766     QCowSnapshotHeader h;
1767     QCowSnapshot *sn;
1768     int i, id_str_size, name_size;
1769     int64_t offset;
1770     uint32_t extra_data_size;
1771
1772     offset = s->snapshots_offset;
1773     s->snapshots = qemu_mallocz(s->nb_snapshots * sizeof(QCowSnapshot));
1774     if (!s->snapshots)
1775         goto fail;
1776     for(i = 0; i < s->nb_snapshots; i++) {
1777         offset = align_offset(offset, 8);
1778         if (bdrv_pread(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1779             goto fail;
1780         offset += sizeof(h);
1781         sn = s->snapshots + i;
1782         sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
1783         sn->l1_size = be32_to_cpu(h.l1_size);
1784         sn->vm_state_size = be32_to_cpu(h.vm_state_size);
1785         sn->date_sec = be32_to_cpu(h.date_sec);
1786         sn->date_nsec = be32_to_cpu(h.date_nsec);
1787         sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
1788         extra_data_size = be32_to_cpu(h.extra_data_size);
1789
1790         id_str_size = be16_to_cpu(h.id_str_size);
1791         name_size = be16_to_cpu(h.name_size);
1792
1793         offset += extra_data_size;
1794
1795         sn->id_str = qemu_malloc(id_str_size + 1);
1796         if (!sn->id_str)
1797             goto fail;
1798         if (bdrv_pread(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1799             goto fail;
1800         offset += id_str_size;
1801         sn->id_str[id_str_size] = '\0';
1802
1803         sn->name = qemu_malloc(name_size + 1);
1804         if (!sn->name)
1805             goto fail;
1806         if (bdrv_pread(s->hd, offset, sn->name, name_size) != name_size)
1807             goto fail;
1808         offset += name_size;
1809         sn->name[name_size] = '\0';
1810     }
1811     s->snapshots_size = offset - s->snapshots_offset;
1812     return 0;
1813  fail:
1814     qcow_free_snapshots(bs);
1815     return -1;
1816 }
1817
1818 /* add at the end of the file a new list of snapshots */
1819 static int qcow_write_snapshots(BlockDriverState *bs)
1820 {
1821     BDRVQcowState *s = bs->opaque;
1822     QCowSnapshot *sn;
1823     QCowSnapshotHeader h;
1824     int i, name_size, id_str_size, snapshots_size;
1825     uint64_t data64;
1826     uint32_t data32;
1827     int64_t offset, snapshots_offset;
1828
1829     /* compute the size of the snapshots */
1830     offset = 0;
1831     for(i = 0; i < s->nb_snapshots; i++) {
1832         sn = s->snapshots + i;
1833         offset = align_offset(offset, 8);
1834         offset += sizeof(h);
1835         offset += strlen(sn->id_str);
1836         offset += strlen(sn->name);
1837     }
1838     snapshots_size = offset;
1839
1840     snapshots_offset = alloc_clusters(bs, snapshots_size);
1841     offset = snapshots_offset;
1842
1843     for(i = 0; i < s->nb_snapshots; i++) {
1844         sn = s->snapshots + i;
1845         memset(&h, 0, sizeof(h));
1846         h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);
1847         h.l1_size = cpu_to_be32(sn->l1_size);
1848         h.vm_state_size = cpu_to_be32(sn->vm_state_size);
1849         h.date_sec = cpu_to_be32(sn->date_sec);
1850         h.date_nsec = cpu_to_be32(sn->date_nsec);
1851         h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);
1852
1853         id_str_size = strlen(sn->id_str);
1854         name_size = strlen(sn->name);
1855         h.id_str_size = cpu_to_be16(id_str_size);
1856         h.name_size = cpu_to_be16(name_size);
1857         offset = align_offset(offset, 8);
1858         if (bdrv_pwrite(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1859             goto fail;
1860         offset += sizeof(h);
1861         if (bdrv_pwrite(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1862             goto fail;
1863         offset += id_str_size;
1864         if (bdrv_pwrite(s->hd, offset, sn->name, name_size) != name_size)
1865             goto fail;
1866         offset += name_size;
1867     }
1868
1869     /* update the various header fields */
1870     data64 = cpu_to_be64(snapshots_offset);
1871     if (bdrv_pwrite(s->hd, offsetof(QCowHeader, snapshots_offset),
1872                     &data64, sizeof(data64)) != sizeof(data64))
1873         goto fail;
1874     data32 = cpu_to_be32(s->nb_snapshots);
1875     if (bdrv_pwrite(s->hd, offsetof(QCowHeader, nb_snapshots),
1876                     &data32, sizeof(data32)) != sizeof(data32))
1877         goto fail;
1878
1879     /* free the old snapshot table */
1880     free_clusters(bs, s->snapshots_offset, s->snapshots_size);
1881     s->snapshots_offset = snapshots_offset;
1882     s->snapshots_size = snapshots_size;
1883     return 0;
1884  fail:
1885     return -1;
1886 }
1887
1888 static void find_new_snapshot_id(BlockDriverState *bs,
1889                                  char *id_str, int id_str_size)
1890 {
1891     BDRVQcowState *s = bs->opaque;
1892     QCowSnapshot *sn;
1893     int i, id, id_max = 0;
1894
1895     for(i = 0; i < s->nb_snapshots; i++) {
1896         sn = s->snapshots + i;
1897         id = strtoul(sn->id_str, NULL, 10);
1898         if (id > id_max)
1899             id_max = id;
1900     }
1901     snprintf(id_str, id_str_size, "%d", id_max + 1);
1902 }
1903
1904 static int find_snapshot_by_id(BlockDriverState *bs, const char *id_str)
1905 {
1906     BDRVQcowState *s = bs->opaque;
1907     int i;
1908
1909     for(i = 0; i < s->nb_snapshots; i++) {
1910         if (!strcmp(s->snapshots[i].id_str, id_str))
1911             return i;
1912     }
1913     return -1;
1914 }
1915
1916 static int find_snapshot_by_id_or_name(BlockDriverState *bs, const char *name)
1917 {
1918     BDRVQcowState *s = bs->opaque;
1919     int i, ret;
1920
1921     ret = find_snapshot_by_id(bs, name);
1922     if (ret >= 0)
1923         return ret;
1924     for(i = 0; i < s->nb_snapshots; i++) {
1925         if (!strcmp(s->snapshots[i].name, name))
1926             return i;
1927     }
1928     return -1;
1929 }
1930
1931 /* if no id is provided, a new one is constructed */
1932 static int qcow_snapshot_create(BlockDriverState *bs,
1933                                 QEMUSnapshotInfo *sn_info)
1934 {
1935     BDRVQcowState *s = bs->opaque;
1936     QCowSnapshot *snapshots1, sn1, *sn = &sn1;
1937     int i, ret;
1938     uint64_t *l1_table = NULL;
1939
1940     memset(sn, 0, sizeof(*sn));
1941
1942     if (sn_info->id_str[0] == '\0') {
1943         /* compute a new id */
1944         find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));
1945     }
1946
1947     /* check that the ID is unique */
1948     if (find_snapshot_by_id(bs, sn_info->id_str) >= 0)
1949         return -ENOENT;
1950
1951     sn->id_str = qemu_strdup(sn_info->id_str);
1952     if (!sn->id_str)
1953         goto fail;
1954     sn->name = qemu_strdup(sn_info->name);
1955     if (!sn->name)
1956         goto fail;
1957     sn->vm_state_size = sn_info->vm_state_size;
1958     sn->date_sec = sn_info->date_sec;
1959     sn->date_nsec = sn_info->date_nsec;
1960     sn->vm_clock_nsec = sn_info->vm_clock_nsec;
1961
1962     ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);
1963     if (ret < 0)
1964         goto fail;
1965
1966     /* create the L1 table of the snapshot */
1967     sn->l1_table_offset = alloc_clusters(bs, s->l1_size * sizeof(uint64_t));
1968     sn->l1_size = s->l1_size;
1969
1970     l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
1971     if (!l1_table)
1972         goto fail;
1973     for(i = 0; i < s->l1_size; i++) {
1974         l1_table[i] = cpu_to_be64(s->l1_table[i]);
1975     }
1976     if (bdrv_pwrite(s->hd, sn->l1_table_offset,
1977                     l1_table, s->l1_size * sizeof(uint64_t)) !=
1978         (s->l1_size * sizeof(uint64_t)))
1979         goto fail;
1980     qemu_free(l1_table);
1981     l1_table = NULL;
1982
1983     snapshots1 = qemu_malloc((s->nb_snapshots + 1) * sizeof(QCowSnapshot));
1984     if (!snapshots1)
1985         goto fail;
1986     memcpy(snapshots1, s->snapshots, s->nb_snapshots * sizeof(QCowSnapshot));
1987     s->snapshots = snapshots1;
1988     s->snapshots[s->nb_snapshots++] = *sn;
1989
1990     if (qcow_write_snapshots(bs) < 0)
1991         goto fail;
1992 #ifdef DEBUG_ALLOC
1993     check_refcounts(bs);
1994 #endif
1995     return 0;
1996  fail:
1997     qemu_free(sn->name);
1998     qemu_free(l1_table);
1999     return -1;
2000 }
2001
2002 /* copy the snapshot 'snapshot_name' into the current disk image */
2003 static int qcow_snapshot_goto(BlockDriverState *bs,
2004                               const char *snapshot_id)
2005 {
2006     BDRVQcowState *s = bs->opaque;
2007     QCowSnapshot *sn;
2008     int i, snapshot_index, l1_size2;
2009
2010     snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2011     if (snapshot_index < 0)
2012         return -ENOENT;
2013     sn = &s->snapshots[snapshot_index];
2014
2015     if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, -1) < 0)
2016         goto fail;
2017
2018     if (grow_l1_table(bs, sn->l1_size) < 0)
2019         goto fail;
2020
2021     s->l1_size = sn->l1_size;
2022     l1_size2 = s->l1_size * sizeof(uint64_t);
2023     /* copy the snapshot l1 table to the current l1 table */
2024     if (bdrv_pread(s->hd, sn->l1_table_offset,
2025                    s->l1_table, l1_size2) != l1_size2)
2026         goto fail;
2027     if (bdrv_pwrite(s->hd, s->l1_table_offset,
2028                     s->l1_table, l1_size2) != l1_size2)
2029         goto fail;
2030     for(i = 0;i < s->l1_size; i++) {
2031         be64_to_cpus(&s->l1_table[i]);
2032     }
2033
2034     if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1) < 0)
2035         goto fail;
2036
2037 #ifdef DEBUG_ALLOC
2038     check_refcounts(bs);
2039 #endif
2040     return 0;
2041  fail:
2042     return -EIO;
2043 }
2044
2045 static int qcow_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2046 {
2047     BDRVQcowState *s = bs->opaque;
2048     QCowSnapshot *sn;
2049     int snapshot_index, ret;
2050
2051     snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2052     if (snapshot_index < 0)
2053         return -ENOENT;
2054     sn = &s->snapshots[snapshot_index];
2055
2056     ret = update_snapshot_refcount(bs, sn->l1_table_offset, sn->l1_size, -1);
2057     if (ret < 0)
2058         return ret;
2059     /* must update the copied flag on the current cluster offsets */
2060     ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
2061     if (ret < 0)
2062         return ret;
2063     free_clusters(bs, sn->l1_table_offset, sn->l1_size * sizeof(uint64_t));
2064
2065     qemu_free(sn->id_str);
2066     qemu_free(sn->name);
2067     memmove(sn, sn + 1, (s->nb_snapshots - snapshot_index - 1) * sizeof(*sn));
2068     s->nb_snapshots--;
2069     ret = qcow_write_snapshots(bs);
2070     if (ret < 0) {
2071         /* XXX: restore snapshot if error ? */
2072         return ret;
2073     }
2074 #ifdef DEBUG_ALLOC
2075     check_refcounts(bs);
2076 #endif
2077     return 0;
2078 }
2079
2080 static int qcow_snapshot_list(BlockDriverState *bs,
2081                               QEMUSnapshotInfo **psn_tab)
2082 {
2083     BDRVQcowState *s = bs->opaque;
2084     QEMUSnapshotInfo *sn_tab, *sn_info;
2085     QCowSnapshot *sn;
2086     int i;
2087
2088     sn_tab = qemu_mallocz(s->nb_snapshots * sizeof(QEMUSnapshotInfo));
2089     if (!sn_tab)
2090         goto fail;
2091     for(i = 0; i < s->nb_snapshots; i++) {
2092         sn_info = sn_tab + i;
2093         sn = s->snapshots + i;
2094         pstrcpy(sn_info->id_str, sizeof(sn_info->id_str),
2095                 sn->id_str);
2096         pstrcpy(sn_info->name, sizeof(sn_info->name),
2097                 sn->name);
2098         sn_info->vm_state_size = sn->vm_state_size;
2099         sn_info->date_sec = sn->date_sec;
2100         sn_info->date_nsec = sn->date_nsec;
2101         sn_info->vm_clock_nsec = sn->vm_clock_nsec;
2102     }
2103     *psn_tab = sn_tab;
2104     return s->nb_snapshots;
2105  fail:
2106     qemu_free(sn_tab);
2107     *psn_tab = NULL;
2108     return -ENOMEM;
2109 }
2110
2111 /*********************************************************/
2112 /* refcount handling */
2113
2114 static int refcount_init(BlockDriverState *bs)
2115 {
2116     BDRVQcowState *s = bs->opaque;
2117     int ret, refcount_table_size2, i;
2118
2119     s->refcount_block_cache = qemu_malloc(s->cluster_size);
2120     if (!s->refcount_block_cache)
2121         goto fail;
2122     refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
2123     s->refcount_table = qemu_malloc(refcount_table_size2);
2124     if (!s->refcount_table)
2125         goto fail;
2126     if (s->refcount_table_size > 0) {
2127         ret = bdrv_pread(s->hd, s->refcount_table_offset,
2128                          s->refcount_table, refcount_table_size2);
2129         if (ret != refcount_table_size2)
2130             goto fail;
2131         for(i = 0; i < s->refcount_table_size; i++)
2132             be64_to_cpus(&s->refcount_table[i]);
2133     }
2134     return 0;
2135  fail:
2136     return -ENOMEM;
2137 }
2138
2139 static void refcount_close(BlockDriverState *bs)
2140 {
2141     BDRVQcowState *s = bs->opaque;
2142     qemu_free(s->refcount_block_cache);
2143     qemu_free(s->refcount_table);
2144 }
2145
2146
2147 static int load_refcount_block(BlockDriverState *bs,
2148                                int64_t refcount_block_offset)
2149 {
2150     BDRVQcowState *s = bs->opaque;
2151     int ret;
2152     ret = bdrv_pread(s->hd, refcount_block_offset, s->refcount_block_cache,
2153                      s->cluster_size);
2154     if (ret != s->cluster_size)
2155         return -EIO;
2156     s->refcount_block_cache_offset = refcount_block_offset;
2157     return 0;
2158 }
2159
2160 static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
2161 {
2162     BDRVQcowState *s = bs->opaque;
2163     int refcount_table_index, block_index;
2164     int64_t refcount_block_offset;
2165
2166     refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2167     if (refcount_table_index >= s->refcount_table_size)
2168         return 0;
2169     refcount_block_offset = s->refcount_table[refcount_table_index];
2170     if (!refcount_block_offset)
2171         return 0;
2172     if (refcount_block_offset != s->refcount_block_cache_offset) {
2173         /* better than nothing: return allocated if read error */
2174         if (load_refcount_block(bs, refcount_block_offset) < 0)
2175             return 1;
2176     }
2177     block_index = cluster_index &
2178         ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2179     return be16_to_cpu(s->refcount_block_cache[block_index]);
2180 }
2181
2182 /* return < 0 if error */
2183 static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)
2184 {
2185     BDRVQcowState *s = bs->opaque;
2186     int i, nb_clusters;
2187
2188     nb_clusters = size_to_clusters(s, size);
2189 retry:
2190     for(i = 0; i < nb_clusters; i++) {
2191         int64_t i = s->free_cluster_index++;
2192         if (get_refcount(bs, i) != 0)
2193             goto retry;
2194     }
2195 #ifdef DEBUG_ALLOC2
2196     printf("alloc_clusters: size=%lld -> %lld\n",
2197             size,
2198             (s->free_cluster_index - nb_clusters) << s->cluster_bits);
2199 #endif
2200     return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
2201 }
2202
2203 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size)
2204 {
2205     int64_t offset;
2206
2207     offset = alloc_clusters_noref(bs, size);
2208     update_refcount(bs, offset, size, 1);
2209     return offset;
2210 }
2211
2212 /* only used to allocate compressed sectors. We try to allocate
2213    contiguous sectors. size must be <= cluster_size */
2214 static int64_t alloc_bytes(BlockDriverState *bs, int size)
2215 {
2216     BDRVQcowState *s = bs->opaque;
2217     int64_t offset, cluster_offset;
2218     int free_in_cluster;
2219
2220     assert(size > 0 && size <= s->cluster_size);
2221     if (s->free_byte_offset == 0) {
2222         s->free_byte_offset = alloc_clusters(bs, s->cluster_size);
2223     }
2224  redo:
2225     free_in_cluster = s->cluster_size -
2226         (s->free_byte_offset & (s->cluster_size - 1));
2227     if (size <= free_in_cluster) {
2228         /* enough space in current cluster */
2229         offset = s->free_byte_offset;
2230         s->free_byte_offset += size;
2231         free_in_cluster -= size;
2232         if (free_in_cluster == 0)
2233             s->free_byte_offset = 0;
2234         if ((offset & (s->cluster_size - 1)) != 0)
2235             update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2236     } else {
2237         offset = alloc_clusters(bs, s->cluster_size);
2238         cluster_offset = s->free_byte_offset & ~(s->cluster_size - 1);
2239         if ((cluster_offset + s->cluster_size) == offset) {
2240             /* we are lucky: contiguous data */
2241             offset = s->free_byte_offset;
2242             update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2243             s->free_byte_offset += size;
2244         } else {
2245             s->free_byte_offset = offset;
2246             goto redo;
2247         }
2248     }
2249     return offset;
2250 }
2251
2252 static void free_clusters(BlockDriverState *bs,
2253                           int64_t offset, int64_t size)
2254 {
2255     update_refcount(bs, offset, size, -1);
2256 }
2257
2258 static int grow_refcount_table(BlockDriverState *bs, int min_size)
2259 {
2260     BDRVQcowState *s = bs->opaque;
2261     int new_table_size, new_table_size2, refcount_table_clusters, i, ret;
2262     uint64_t *new_table;
2263     int64_t table_offset;
2264     uint8_t data[12];
2265     int old_table_size;
2266     int64_t old_table_offset;
2267
2268     if (min_size <= s->refcount_table_size)
2269         return 0;
2270     /* compute new table size */
2271     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2272     for(;;) {
2273         if (refcount_table_clusters == 0) {
2274             refcount_table_clusters = 1;
2275         } else {
2276             refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
2277         }
2278         new_table_size = refcount_table_clusters << (s->cluster_bits - 3);
2279         if (min_size <= new_table_size)
2280             break;
2281     }
2282 #ifdef DEBUG_ALLOC2
2283     printf("grow_refcount_table from %d to %d\n",
2284            s->refcount_table_size,
2285            new_table_size);
2286 #endif
2287     new_table_size2 = new_table_size * sizeof(uint64_t);
2288     new_table = qemu_mallocz(new_table_size2);
2289     if (!new_table)
2290         return -ENOMEM;
2291     memcpy(new_table, s->refcount_table,
2292            s->refcount_table_size * sizeof(uint64_t));
2293     for(i = 0; i < s->refcount_table_size; i++)
2294         cpu_to_be64s(&new_table[i]);
2295     /* Note: we cannot update the refcount now to avoid recursion */
2296     table_offset = alloc_clusters_noref(bs, new_table_size2);
2297     ret = bdrv_pwrite(s->hd, table_offset, new_table, new_table_size2);
2298     if (ret != new_table_size2)
2299         goto fail;
2300     for(i = 0; i < s->refcount_table_size; i++)
2301         be64_to_cpus(&new_table[i]);
2302
2303     cpu_to_be64w((uint64_t*)data, table_offset);
2304     cpu_to_be32w((uint32_t*)(data + 8), refcount_table_clusters);
2305     if (bdrv_pwrite(s->hd, offsetof(QCowHeader, refcount_table_offset),
2306                     data, sizeof(data)) != sizeof(data))
2307         goto fail;
2308     qemu_free(s->refcount_table);
2309     old_table_offset = s->refcount_table_offset;
2310     old_table_size = s->refcount_table_size;
2311     s->refcount_table = new_table;
2312     s->refcount_table_size = new_table_size;
2313     s->refcount_table_offset = table_offset;
2314
2315     update_refcount(bs, table_offset, new_table_size2, 1);
2316     free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));
2317     return 0;
2318  fail:
2319     free_clusters(bs, table_offset, new_table_size2);
2320     qemu_free(new_table);
2321     return -EIO;
2322 }
2323
2324 /* addend must be 1 or -1 */
2325 /* XXX: cache several refcount block clusters ? */
2326 static int update_cluster_refcount(BlockDriverState *bs,
2327                                    int64_t cluster_index,
2328                                    int addend)
2329 {
2330     BDRVQcowState *s = bs->opaque;
2331     int64_t offset, refcount_block_offset;
2332     int ret, refcount_table_index, block_index, refcount;
2333     uint64_t data64;
2334
2335     refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2336     if (refcount_table_index >= s->refcount_table_size) {
2337         if (addend < 0)
2338             return -EINVAL;
2339         ret = grow_refcount_table(bs, refcount_table_index + 1);
2340         if (ret < 0)
2341             return ret;
2342     }
2343     refcount_block_offset = s->refcount_table[refcount_table_index];
2344     if (!refcount_block_offset) {
2345         if (addend < 0)
2346             return -EINVAL;
2347         /* create a new refcount block */
2348         /* Note: we cannot update the refcount now to avoid recursion */
2349         offset = alloc_clusters_noref(bs, s->cluster_size);
2350         memset(s->refcount_block_cache, 0, s->cluster_size);
2351         ret = bdrv_pwrite(s->hd, offset, s->refcount_block_cache, s->cluster_size);
2352         if (ret != s->cluster_size)
2353             return -EINVAL;
2354         s->refcount_table[refcount_table_index] = offset;
2355         data64 = cpu_to_be64(offset);
2356         ret = bdrv_pwrite(s->hd, s->refcount_table_offset +
2357                           refcount_table_index * sizeof(uint64_t),
2358                           &data64, sizeof(data64));
2359         if (ret != sizeof(data64))
2360             return -EINVAL;
2361
2362         refcount_block_offset = offset;
2363         s->refcount_block_cache_offset = offset;
2364         update_refcount(bs, offset, s->cluster_size, 1);
2365     } else {
2366         if (refcount_block_offset != s->refcount_block_cache_offset) {
2367             if (load_refcount_block(bs, refcount_block_offset) < 0)
2368                 return -EIO;
2369         }
2370     }
2371     /* we can update the count and save it */
2372     block_index = cluster_index &
2373         ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2374     refcount = be16_to_cpu(s->refcount_block_cache[block_index]);
2375     refcount += addend;
2376     if (refcount < 0 || refcount > 0xffff)
2377         return -EINVAL;
2378     if (refcount == 0 && cluster_index < s->free_cluster_index) {
2379         s->free_cluster_index = cluster_index;
2380     }
2381     s->refcount_block_cache[block_index] = cpu_to_be16(refcount);
2382     if (bdrv_pwrite(s->hd,
2383                     refcount_block_offset + (block_index << REFCOUNT_SHIFT),
2384                     &s->refcount_block_cache[block_index], 2) != 2)
2385         return -EIO;
2386     return refcount;
2387 }
2388
2389 static void update_refcount(BlockDriverState *bs,
2390                             int64_t offset, int64_t length,
2391                             int addend)
2392 {
2393     BDRVQcowState *s = bs->opaque;
2394     int64_t start, last, cluster_offset;
2395
2396 #ifdef DEBUG_ALLOC2
2397     printf("update_refcount: offset=%lld size=%lld addend=%d\n",
2398            offset, length, addend);
2399 #endif
2400     if (length <= 0)
2401         return;
2402     start = offset & ~(s->cluster_size - 1);
2403     last = (offset + length - 1) & ~(s->cluster_size - 1);
2404     for(cluster_offset = start; cluster_offset <= last;
2405         cluster_offset += s->cluster_size) {
2406         update_cluster_refcount(bs, cluster_offset >> s->cluster_bits, addend);
2407     }
2408 }
2409
2410 #ifdef DEBUG_ALLOC
2411 static void inc_refcounts(BlockDriverState *bs,
2412                           uint16_t *refcount_table,
2413                           int refcount_table_size,
2414                           int64_t offset, int64_t size)
2415 {
2416     BDRVQcowState *s = bs->opaque;
2417     int64_t start, last, cluster_offset;
2418     int k;
2419
2420     if (size <= 0)
2421         return;
2422
2423     start = offset & ~(s->cluster_size - 1);
2424     last = (offset + size - 1) & ~(s->cluster_size - 1);
2425     for(cluster_offset = start; cluster_offset <= last;
2426         cluster_offset += s->cluster_size) {
2427         k = cluster_offset >> s->cluster_bits;
2428         if (k < 0 || k >= refcount_table_size) {
2429             printf("ERROR: invalid cluster offset=0x%llx\n", cluster_offset);
2430         } else {
2431             if (++refcount_table[k] == 0) {
2432                 printf("ERROR: overflow cluster offset=0x%llx\n", cluster_offset);
2433             }
2434         }
2435     }
2436 }
2437
2438 static int check_refcounts_l1(BlockDriverState *bs,
2439                               uint16_t *refcount_table,
2440                               int refcount_table_size,
2441                               int64_t l1_table_offset, int l1_size,
2442                               int check_copied)
2443 {
2444     BDRVQcowState *s = bs->opaque;
2445     uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2;
2446     int l2_size, i, j, nb_csectors, refcount;
2447
2448     l2_table = NULL;
2449     l1_size2 = l1_size * sizeof(uint64_t);
2450
2451     inc_refcounts(bs, refcount_table, refcount_table_size,
2452                   l1_table_offset, l1_size2);
2453
2454     l1_table = qemu_malloc(l1_size2);
2455     if (!l1_table)
2456         goto fail;
2457     if (bdrv_pread(s->hd, l1_table_offset,
2458                    l1_table, l1_size2) != l1_size2)
2459         goto fail;
2460     for(i = 0;i < l1_size; i++)
2461         be64_to_cpus(&l1_table[i]);
2462
2463     l2_size = s->l2_size * sizeof(uint64_t);
2464     l2_table = qemu_malloc(l2_size);
2465     if (!l2_table)
2466         goto fail;
2467     for(i = 0; i < l1_size; i++) {
2468         l2_offset = l1_table[i];
2469         if (l2_offset) {
2470             if (check_copied) {
2471                 refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
2472                 if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
2473                     printf("ERROR OFLAG_COPIED: l2_offset=%llx refcount=%d\n",
2474                            l2_offset, refcount);
2475                 }
2476             }
2477             l2_offset &= ~QCOW_OFLAG_COPIED;
2478             if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
2479                 goto fail;
2480             for(j = 0; j < s->l2_size; j++) {
2481                 offset = be64_to_cpu(l2_table[j]);
2482                 if (offset != 0) {
2483                     if (offset & QCOW_OFLAG_COMPRESSED) {
2484                         if (offset & QCOW_OFLAG_COPIED) {
2485                             printf("ERROR: cluster %lld: copied flag must never be set for compressed clusters\n",
2486                                    offset >> s->cluster_bits);
2487                             offset &= ~QCOW_OFLAG_COPIED;
2488                         }
2489                         nb_csectors = ((offset >> s->csize_shift) &
2490                                        s->csize_mask) + 1;
2491                         offset &= s->cluster_offset_mask;
2492                         inc_refcounts(bs, refcount_table,
2493                                       refcount_table_size,
2494                                       offset & ~511, nb_csectors * 512);
2495                     } else {
2496                         if (check_copied) {
2497                             refcount = get_refcount(bs, (offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
2498                             if ((refcount == 1) != ((offset & QCOW_OFLAG_COPIED) != 0)) {
2499                                 printf("ERROR OFLAG_COPIED: offset=%llx refcount=%d\n",
2500                                        offset, refcount);
2501                             }
2502                         }
2503                         offset &= ~QCOW_OFLAG_COPIED;
2504                         inc_refcounts(bs, refcount_table,
2505                                       refcount_table_size,
2506                                       offset, s->cluster_size);
2507                     }
2508                 }
2509             }
2510             inc_refcounts(bs, refcount_table,
2511                           refcount_table_size,
2512                           l2_offset,
2513                           s->cluster_size);
2514         }
2515     }
2516     qemu_free(l1_table);
2517     qemu_free(l2_table);
2518     return 0;
2519  fail:
2520     printf("ERROR: I/O error in check_refcounts_l1\n");
2521     qemu_free(l1_table);
2522     qemu_free(l2_table);
2523     return -EIO;
2524 }
2525
2526 static void check_refcounts(BlockDriverState *bs)
2527 {
2528     BDRVQcowState *s = bs->opaque;
2529     int64_t size;
2530     int nb_clusters, refcount1, refcount2, i;
2531     QCowSnapshot *sn;
2532     uint16_t *refcount_table;
2533
2534     size = bdrv_getlength(s->hd);
2535     nb_clusters = size_to_clusters(s, size);
2536     refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));
2537
2538     /* header */
2539     inc_refcounts(bs, refcount_table, nb_clusters,
2540                   0, s->cluster_size);
2541
2542     check_refcounts_l1(bs, refcount_table, nb_clusters,
2543                        s->l1_table_offset, s->l1_size, 1);
2544
2545     /* snapshots */
2546     for(i = 0; i < s->nb_snapshots; i++) {
2547         sn = s->snapshots + i;
2548         check_refcounts_l1(bs, refcount_table, nb_clusters,
2549                            sn->l1_table_offset, sn->l1_size, 0);
2550     }
2551     inc_refcounts(bs, refcount_table, nb_clusters,
2552                   s->snapshots_offset, s->snapshots_size);
2553
2554     /* refcount data */
2555     inc_refcounts(bs, refcount_table, nb_clusters,
2556                   s->refcount_table_offset,
2557                   s->refcount_table_size * sizeof(uint64_t));
2558     for(i = 0; i < s->refcount_table_size; i++) {
2559         int64_t offset;
2560         offset = s->refcount_table[i];
2561         if (offset != 0) {
2562             inc_refcounts(bs, refcount_table, nb_clusters,
2563                           offset, s->cluster_size);
2564         }
2565     }
2566
2567     /* compare ref counts */
2568     for(i = 0; i < nb_clusters; i++) {
2569         refcount1 = get_refcount(bs, i);
2570         refcount2 = refcount_table[i];
2571         if (refcount1 != refcount2)
2572             printf("ERROR cluster %d refcount=%d reference=%d\n",
2573                    i, refcount1, refcount2);
2574     }
2575
2576     qemu_free(refcount_table);
2577 }
2578
2579 #if 0
2580 static void dump_refcounts(BlockDriverState *bs)
2581 {
2582     BDRVQcowState *s = bs->opaque;
2583     int64_t nb_clusters, k, k1, size;
2584     int refcount;
2585
2586     size = bdrv_getlength(s->hd);
2587     nb_clusters = size_to_clusters(s, size);
2588     for(k = 0; k < nb_clusters;) {
2589         k1 = k;
2590         refcount = get_refcount(bs, k);
2591         k++;
2592         while (k < nb_clusters && get_refcount(bs, k) == refcount)
2593             k++;
2594         printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
2595     }
2596 }
2597 #endif
2598 #endif
2599
2600 BlockDriver bdrv_qcow2 = {
2601     "qcow2",
2602     sizeof(BDRVQcowState),
2603     qcow_probe,
2604     qcow_open,
2605     NULL,
2606     NULL,
2607     qcow_close,
2608     qcow_create,
2609     qcow_flush,
2610     qcow_is_allocated,
2611     qcow_set_key,
2612     qcow_make_empty,
2613
2614     .bdrv_aio_read = qcow_aio_read,
2615     .bdrv_aio_write = qcow_aio_write,
2616     .bdrv_aio_cancel = qcow_aio_cancel,
2617     .aiocb_size = sizeof(QCowAIOCB),
2618     .bdrv_write_compressed = qcow_write_compressed,
2619
2620     .bdrv_snapshot_create = qcow_snapshot_create,
2621     .bdrv_snapshot_goto = qcow_snapshot_goto,
2622     .bdrv_snapshot_delete = qcow_snapshot_delete,
2623     .bdrv_snapshot_list = qcow_snapshot_list,
2624     .bdrv_get_info = qcow_get_info,
2625 };