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