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