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