Move block drivers into their own directory
[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 "module.h"
27 #include <zlib.h>
28 #include "aes.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 two concurrent writes happen to the same unallocated cluster
996          * each write allocates separate cluster and writes data concurrently.
997          * The first one to complete updates l2 table with pointer to its
998          * cluster the second one has to do RMW (which is done above by
999          * copy_sectors()), update l2 table with its cluster pointer and free
1000          * old cluster. This is what this loop does */
1001         if(l2_table[l2_index + i] != 0)
1002             old_cluster[j++] = l2_table[l2_index + i];
1003
1004         l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
1005                     (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
1006      }
1007
1008     if (bdrv_pwrite(s->hd, l2_offset + l2_index * sizeof(uint64_t),
1009                 l2_table + l2_index, m->nb_clusters * sizeof(uint64_t)) !=
1010             m->nb_clusters * sizeof(uint64_t))
1011         goto err;
1012
1013     for (i = 0; i < j; i++)
1014         free_any_clusters(bs, be64_to_cpu(old_cluster[i]) & ~QCOW_OFLAG_COPIED,
1015                           1);
1016
1017     ret = 0;
1018 err:
1019     qemu_free(old_cluster);
1020     return ret;
1021  }
1022
1023 /*
1024  * alloc_cluster_offset
1025  *
1026  * For a given offset of the disk image, return cluster offset in
1027  * qcow2 file.
1028  *
1029  * If the offset is not found, allocate a new cluster.
1030  *
1031  * Return the cluster offset if successful,
1032  * Return 0, otherwise.
1033  *
1034  */
1035
1036 static uint64_t alloc_cluster_offset(BlockDriverState *bs,
1037                                      uint64_t offset,
1038                                      int n_start, int n_end,
1039                                      int *num, QCowL2Meta *m)
1040 {
1041     BDRVQcowState *s = bs->opaque;
1042     int l2_index, ret;
1043     uint64_t l2_offset, *l2_table, cluster_offset;
1044     int nb_clusters, i = 0;
1045
1046     ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
1047     if (ret == 0)
1048         return 0;
1049
1050     nb_clusters = size_to_clusters(s, n_end << 9);
1051
1052     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1053
1054     cluster_offset = be64_to_cpu(l2_table[l2_index]);
1055
1056     /* We keep all QCOW_OFLAG_COPIED clusters */
1057
1058     if (cluster_offset & QCOW_OFLAG_COPIED) {
1059         nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
1060                 &l2_table[l2_index], 0, 0);
1061
1062         cluster_offset &= ~QCOW_OFLAG_COPIED;
1063         m->nb_clusters = 0;
1064
1065         goto out;
1066     }
1067
1068     /* for the moment, multiple compressed clusters are not managed */
1069
1070     if (cluster_offset & QCOW_OFLAG_COMPRESSED)
1071         nb_clusters = 1;
1072
1073     /* how many available clusters ? */
1074
1075     while (i < nb_clusters) {
1076         i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
1077                 &l2_table[l2_index], i, 0);
1078
1079         if(be64_to_cpu(l2_table[l2_index + i]))
1080             break;
1081
1082         i += count_contiguous_free_clusters(nb_clusters - i,
1083                 &l2_table[l2_index + i]);
1084
1085         cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
1086
1087         if ((cluster_offset & QCOW_OFLAG_COPIED) ||
1088                 (cluster_offset & QCOW_OFLAG_COMPRESSED))
1089             break;
1090     }
1091     nb_clusters = i;
1092
1093     /* allocate a new cluster */
1094
1095     cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);
1096
1097     /* save info needed for meta data update */
1098     m->offset = offset;
1099     m->n_start = n_start;
1100     m->nb_clusters = nb_clusters;
1101
1102 out:
1103     m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
1104
1105     *num = m->nb_available - n_start;
1106
1107     return cluster_offset;
1108 }
1109
1110 static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
1111                              int nb_sectors, int *pnum)
1112 {
1113     uint64_t cluster_offset;
1114
1115     *pnum = nb_sectors;
1116     cluster_offset = get_cluster_offset(bs, sector_num << 9, pnum);
1117
1118     return (cluster_offset != 0);
1119 }
1120
1121 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1122                              const uint8_t *buf, int buf_size)
1123 {
1124     z_stream strm1, *strm = &strm1;
1125     int ret, out_len;
1126
1127     memset(strm, 0, sizeof(*strm));
1128
1129     strm->next_in = (uint8_t *)buf;
1130     strm->avail_in = buf_size;
1131     strm->next_out = out_buf;
1132     strm->avail_out = out_buf_size;
1133
1134     ret = inflateInit2(strm, -12);
1135     if (ret != Z_OK)
1136         return -1;
1137     ret = inflate(strm, Z_FINISH);
1138     out_len = strm->next_out - out_buf;
1139     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1140         out_len != out_buf_size) {
1141         inflateEnd(strm);
1142         return -1;
1143     }
1144     inflateEnd(strm);
1145     return 0;
1146 }
1147
1148 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
1149 {
1150     int ret, csize, nb_csectors, sector_offset;
1151     uint64_t coffset;
1152
1153     coffset = cluster_offset & s->cluster_offset_mask;
1154     if (s->cluster_cache_offset != coffset) {
1155         nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1156         sector_offset = coffset & 511;
1157         csize = nb_csectors * 512 - sector_offset;
1158         ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
1159         if (ret < 0) {
1160             return -1;
1161         }
1162         if (decompress_buffer(s->cluster_cache, s->cluster_size,
1163                               s->cluster_data + sector_offset, csize) < 0) {
1164             return -1;
1165         }
1166         s->cluster_cache_offset = coffset;
1167     }
1168     return 0;
1169 }
1170
1171 /* handle reading after the end of the backing file */
1172 static int backing_read1(BlockDriverState *bs,
1173                          int64_t sector_num, uint8_t *buf, int nb_sectors)
1174 {
1175     int n1;
1176     if ((sector_num + nb_sectors) <= bs->total_sectors)
1177         return nb_sectors;
1178     if (sector_num >= bs->total_sectors)
1179         n1 = 0;
1180     else
1181         n1 = bs->total_sectors - sector_num;
1182     memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
1183     return n1;
1184 }
1185
1186 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
1187                      uint8_t *buf, int nb_sectors)
1188 {
1189     BDRVQcowState *s = bs->opaque;
1190     int ret, index_in_cluster, n, n1;
1191     uint64_t cluster_offset;
1192
1193     while (nb_sectors > 0) {
1194         n = nb_sectors;
1195         cluster_offset = get_cluster_offset(bs, sector_num << 9, &n);
1196         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1197         if (!cluster_offset) {
1198             if (bs->backing_hd) {
1199                 /* read from the base image */
1200                 n1 = backing_read1(bs->backing_hd, sector_num, buf, n);
1201                 if (n1 > 0) {
1202                     ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
1203                     if (ret < 0)
1204                         return -1;
1205                 }
1206             } else {
1207                 memset(buf, 0, 512 * n);
1208             }
1209         } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
1210             if (decompress_cluster(s, cluster_offset) < 0)
1211                 return -1;
1212             memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
1213         } else {
1214             ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1215             if (ret != n * 512)
1216                 return -1;
1217             if (s->crypt_method) {
1218                 encrypt_sectors(s, sector_num, buf, buf, n, 0,
1219                                 &s->aes_decrypt_key);
1220             }
1221         }
1222         nb_sectors -= n;
1223         sector_num += n;
1224         buf += n * 512;
1225     }
1226     return 0;
1227 }
1228
1229 static int qcow_write(BlockDriverState *bs, int64_t sector_num,
1230                      const uint8_t *buf, int nb_sectors)
1231 {
1232     BDRVQcowState *s = bs->opaque;
1233     int ret, index_in_cluster, n;
1234     uint64_t cluster_offset;
1235     int n_end;
1236     QCowL2Meta l2meta;
1237
1238     while (nb_sectors > 0) {
1239         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1240         n_end = index_in_cluster + nb_sectors;
1241         if (s->crypt_method &&
1242             n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1243             n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1244         cluster_offset = alloc_cluster_offset(bs, sector_num << 9,
1245                                               index_in_cluster,
1246                                               n_end, &n, &l2meta);
1247         if (!cluster_offset)
1248             return -1;
1249         if (s->crypt_method) {
1250             encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
1251                             &s->aes_encrypt_key);
1252             ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512,
1253                               s->cluster_data, n * 512);
1254         } else {
1255             ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1256         }
1257         if (ret != n * 512 || alloc_cluster_link_l2(bs, cluster_offset, &l2meta) < 0) {
1258             free_any_clusters(bs, cluster_offset, l2meta.nb_clusters);
1259             return -1;
1260         }
1261         nb_sectors -= n;
1262         sector_num += n;
1263         buf += n * 512;
1264     }
1265     s->cluster_cache_offset = -1; /* disable compressed cache */
1266     return 0;
1267 }
1268
1269 typedef struct QCowAIOCB {
1270     BlockDriverAIOCB common;
1271     int64_t sector_num;
1272     QEMUIOVector *qiov;
1273     uint8_t *buf;
1274     void *orig_buf;
1275     int nb_sectors;
1276     int n;
1277     uint64_t cluster_offset;
1278     uint8_t *cluster_data;
1279     BlockDriverAIOCB *hd_aiocb;
1280     struct iovec hd_iov;
1281     QEMUIOVector hd_qiov;
1282     QEMUBH *bh;
1283     QCowL2Meta l2meta;
1284 } QCowAIOCB;
1285
1286 static void qcow_aio_read_cb(void *opaque, int ret);
1287 static void qcow_aio_read_bh(void *opaque)
1288 {
1289     QCowAIOCB *acb = opaque;
1290     qemu_bh_delete(acb->bh);
1291     acb->bh = NULL;
1292     qcow_aio_read_cb(opaque, 0);
1293 }
1294
1295 static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
1296 {
1297     if (acb->bh)
1298         return -EIO;
1299
1300     acb->bh = qemu_bh_new(cb, acb);
1301     if (!acb->bh)
1302         return -EIO;
1303
1304     qemu_bh_schedule(acb->bh);
1305
1306     return 0;
1307 }
1308
1309 static void qcow_aio_read_cb(void *opaque, int ret)
1310 {
1311     QCowAIOCB *acb = opaque;
1312     BlockDriverState *bs = acb->common.bs;
1313     BDRVQcowState *s = bs->opaque;
1314     int index_in_cluster, n1;
1315
1316     acb->hd_aiocb = NULL;
1317     if (ret < 0)
1318         goto done;
1319
1320     /* post process the read buffer */
1321     if (!acb->cluster_offset) {
1322         /* nothing to do */
1323     } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1324         /* nothing to do */
1325     } else {
1326         if (s->crypt_method) {
1327             encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
1328                             acb->n, 0,
1329                             &s->aes_decrypt_key);
1330         }
1331     }
1332
1333     acb->nb_sectors -= acb->n;
1334     acb->sector_num += acb->n;
1335     acb->buf += acb->n * 512;
1336
1337     if (acb->nb_sectors == 0) {
1338         /* request completed */
1339         ret = 0;
1340         goto done;
1341     }
1342
1343     /* prepare next AIO request */
1344     acb->n = acb->nb_sectors;
1345     acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
1346     index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1347
1348     if (!acb->cluster_offset) {
1349         if (bs->backing_hd) {
1350             /* read from the base image */
1351             n1 = backing_read1(bs->backing_hd, acb->sector_num,
1352                                acb->buf, acb->n);
1353             if (n1 > 0) {
1354                 acb->hd_iov.iov_base = (void *)acb->buf;
1355                 acb->hd_iov.iov_len = acb->n * 512;
1356                 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1357                 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
1358                                     &acb->hd_qiov, acb->n,
1359                                     qcow_aio_read_cb, acb);
1360                 if (acb->hd_aiocb == NULL)
1361                     goto done;
1362             } else {
1363                 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1364                 if (ret < 0)
1365                     goto done;
1366             }
1367         } else {
1368             /* Note: in this case, no need to wait */
1369             memset(acb->buf, 0, 512 * acb->n);
1370             ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1371             if (ret < 0)
1372                 goto done;
1373         }
1374     } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1375         /* add AIO support for compressed blocks ? */
1376         if (decompress_cluster(s, acb->cluster_offset) < 0)
1377             goto done;
1378         memcpy(acb->buf,
1379                s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
1380         ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1381         if (ret < 0)
1382             goto done;
1383     } else {
1384         if ((acb->cluster_offset & 511) != 0) {
1385             ret = -EIO;
1386             goto done;
1387         }
1388
1389         acb->hd_iov.iov_base = (void *)acb->buf;
1390         acb->hd_iov.iov_len = acb->n * 512;
1391         qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1392         acb->hd_aiocb = bdrv_aio_readv(s->hd,
1393                             (acb->cluster_offset >> 9) + index_in_cluster,
1394                             &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
1395         if (acb->hd_aiocb == NULL)
1396             goto done;
1397     }
1398
1399     return;
1400 done:
1401     if (acb->qiov->niov > 1) {
1402         qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
1403         qemu_vfree(acb->orig_buf);
1404     }
1405     acb->common.cb(acb->common.opaque, ret);
1406     qemu_aio_release(acb);
1407 }
1408
1409 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
1410         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1411         BlockDriverCompletionFunc *cb, void *opaque, int is_write)
1412 {
1413     QCowAIOCB *acb;
1414
1415     acb = qemu_aio_get(bs, cb, opaque);
1416     if (!acb)
1417         return NULL;
1418     acb->hd_aiocb = NULL;
1419     acb->sector_num = sector_num;
1420     acb->qiov = qiov;
1421     if (qiov->niov > 1) {
1422         acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
1423         if (is_write)
1424             qemu_iovec_to_buffer(qiov, acb->buf);
1425     } else {
1426         acb->buf = (uint8_t *)qiov->iov->iov_base;
1427     }
1428     acb->nb_sectors = nb_sectors;
1429     acb->n = 0;
1430     acb->cluster_offset = 0;
1431     acb->l2meta.nb_clusters = 0;
1432     return acb;
1433 }
1434
1435 static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
1436         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1437         BlockDriverCompletionFunc *cb, void *opaque)
1438 {
1439     QCowAIOCB *acb;
1440
1441     acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1442     if (!acb)
1443         return NULL;
1444
1445     qcow_aio_read_cb(acb, 0);
1446     return &acb->common;
1447 }
1448
1449 static void qcow_aio_write_cb(void *opaque, int ret)
1450 {
1451     QCowAIOCB *acb = opaque;
1452     BlockDriverState *bs = acb->common.bs;
1453     BDRVQcowState *s = bs->opaque;
1454     int index_in_cluster;
1455     const uint8_t *src_buf;
1456     int n_end;
1457
1458     acb->hd_aiocb = NULL;
1459
1460     if (ret < 0)
1461         goto done;
1462
1463     if (alloc_cluster_link_l2(bs, acb->cluster_offset, &acb->l2meta) < 0) {
1464         free_any_clusters(bs, acb->cluster_offset, acb->l2meta.nb_clusters);
1465         goto done;
1466     }
1467
1468     acb->nb_sectors -= acb->n;
1469     acb->sector_num += acb->n;
1470     acb->buf += acb->n * 512;
1471
1472     if (acb->nb_sectors == 0) {
1473         /* request completed */
1474         ret = 0;
1475         goto done;
1476     }
1477
1478     index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1479     n_end = index_in_cluster + acb->nb_sectors;
1480     if (s->crypt_method &&
1481         n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1482         n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1483
1484     acb->cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,
1485                                           index_in_cluster,
1486                                           n_end, &acb->n, &acb->l2meta);
1487     if (!acb->cluster_offset || (acb->cluster_offset & 511) != 0) {
1488         ret = -EIO;
1489         goto done;
1490     }
1491     if (s->crypt_method) {
1492         if (!acb->cluster_data) {
1493             acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
1494                                              s->cluster_size);
1495         }
1496         encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
1497                         acb->n, 1, &s->aes_encrypt_key);
1498         src_buf = acb->cluster_data;
1499     } else {
1500         src_buf = acb->buf;
1501     }
1502     acb->hd_iov.iov_base = (void *)src_buf;
1503     acb->hd_iov.iov_len = acb->n * 512;
1504     qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1505     acb->hd_aiocb = bdrv_aio_writev(s->hd,
1506                                     (acb->cluster_offset >> 9) + index_in_cluster,
1507                                     &acb->hd_qiov, acb->n,
1508                                     qcow_aio_write_cb, acb);
1509     if (acb->hd_aiocb == NULL)
1510         goto done;
1511
1512     return;
1513
1514 done:
1515     if (acb->qiov->niov > 1)
1516         qemu_vfree(acb->orig_buf);
1517     acb->common.cb(acb->common.opaque, ret);
1518     qemu_aio_release(acb);
1519 }
1520
1521 static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
1522         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1523         BlockDriverCompletionFunc *cb, void *opaque)
1524 {
1525     BDRVQcowState *s = bs->opaque;
1526     QCowAIOCB *acb;
1527
1528     s->cluster_cache_offset = -1; /* disable compressed cache */
1529
1530     acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1531     if (!acb)
1532         return NULL;
1533
1534     qcow_aio_write_cb(acb, 0);
1535     return &acb->common;
1536 }
1537
1538 static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
1539 {
1540     QCowAIOCB *acb = (QCowAIOCB *)blockacb;
1541     if (acb->hd_aiocb)
1542         bdrv_aio_cancel(acb->hd_aiocb);
1543     qemu_aio_release(acb);
1544 }
1545
1546 static void qcow_close(BlockDriverState *bs)
1547 {
1548     BDRVQcowState *s = bs->opaque;
1549     qemu_free(s->l1_table);
1550     qemu_free(s->l2_cache);
1551     qemu_free(s->cluster_cache);
1552     qemu_free(s->cluster_data);
1553     refcount_close(bs);
1554     bdrv_delete(s->hd);
1555 }
1556
1557 /* XXX: use std qcow open function ? */
1558 typedef struct QCowCreateState {
1559     int cluster_size;
1560     int cluster_bits;
1561     uint16_t *refcount_block;
1562     uint64_t *refcount_table;
1563     int64_t l1_table_offset;
1564     int64_t refcount_table_offset;
1565     int64_t refcount_block_offset;
1566 } QCowCreateState;
1567
1568 static void create_refcount_update(QCowCreateState *s,
1569                                    int64_t offset, int64_t size)
1570 {
1571     int refcount;
1572     int64_t start, last, cluster_offset;
1573     uint16_t *p;
1574
1575     start = offset & ~(s->cluster_size - 1);
1576     last = (offset + size - 1)  & ~(s->cluster_size - 1);
1577     for(cluster_offset = start; cluster_offset <= last;
1578         cluster_offset += s->cluster_size) {
1579         p = &s->refcount_block[cluster_offset >> s->cluster_bits];
1580         refcount = be16_to_cpu(*p);
1581         refcount++;
1582         *p = cpu_to_be16(refcount);
1583     }
1584 }
1585
1586 static int qcow_create2(const char *filename, int64_t total_size,
1587                         const char *backing_file, const char *backing_format,
1588                         int flags)
1589 {
1590
1591     int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
1592     int ref_clusters, backing_format_len = 0;
1593     QCowHeader header;
1594     uint64_t tmp, offset;
1595     QCowCreateState s1, *s = &s1;
1596     QCowExtension ext_bf = {0, 0};
1597
1598
1599     memset(s, 0, sizeof(*s));
1600
1601     fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1602     if (fd < 0)
1603         return -1;
1604     memset(&header, 0, sizeof(header));
1605     header.magic = cpu_to_be32(QCOW_MAGIC);
1606     header.version = cpu_to_be32(QCOW_VERSION);
1607     header.size = cpu_to_be64(total_size * 512);
1608     header_size = sizeof(header);
1609     backing_filename_len = 0;
1610     if (backing_file) {
1611         if (backing_format) {
1612             ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
1613             backing_format_len = strlen(backing_format);
1614             ext_bf.len = (backing_format_len + 7) & ~7;
1615             header_size += ((sizeof(ext_bf) + ext_bf.len + 7) & ~7);
1616         }
1617         header.backing_file_offset = cpu_to_be64(header_size);
1618         backing_filename_len = strlen(backing_file);
1619         header.backing_file_size = cpu_to_be32(backing_filename_len);
1620         header_size += backing_filename_len;
1621     }
1622     s->cluster_bits = 12;  /* 4 KB clusters */
1623     s->cluster_size = 1 << s->cluster_bits;
1624     header.cluster_bits = cpu_to_be32(s->cluster_bits);
1625     header_size = (header_size + 7) & ~7;
1626     if (flags & BLOCK_FLAG_ENCRYPT) {
1627         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1628     } else {
1629         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1630     }
1631     l2_bits = s->cluster_bits - 3;
1632     shift = s->cluster_bits + l2_bits;
1633     l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
1634     offset = align_offset(header_size, s->cluster_size);
1635     s->l1_table_offset = offset;
1636     header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
1637     header.l1_size = cpu_to_be32(l1_size);
1638     offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
1639
1640     s->refcount_table = qemu_mallocz(s->cluster_size);
1641
1642     s->refcount_table_offset = offset;
1643     header.refcount_table_offset = cpu_to_be64(offset);
1644     header.refcount_table_clusters = cpu_to_be32(1);
1645     offset += s->cluster_size;
1646     s->refcount_block_offset = offset;
1647
1648     /* count how many refcount blocks needed */
1649     tmp = offset >> s->cluster_bits;
1650     ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
1651     for (i=0; i < ref_clusters; i++) {
1652         s->refcount_table[i] = cpu_to_be64(offset);
1653         offset += s->cluster_size;
1654     }
1655
1656     s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
1657
1658     /* update refcounts */
1659     create_refcount_update(s, 0, header_size);
1660     create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
1661     create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
1662     create_refcount_update(s, s->refcount_block_offset, ref_clusters * s->cluster_size);
1663
1664     /* write all the data */
1665     write(fd, &header, sizeof(header));
1666     if (backing_file) {
1667         if (backing_format_len) {
1668             char zero[16];
1669             int d = ext_bf.len - backing_format_len;
1670
1671             memset(zero, 0, sizeof(zero));
1672             cpu_to_be32s(&ext_bf.magic);
1673             cpu_to_be32s(&ext_bf.len);
1674             write(fd, &ext_bf, sizeof(ext_bf));
1675             write(fd, backing_format, backing_format_len);
1676             if (d>0) {
1677                 write(fd, zero, d);
1678             }
1679         }
1680         write(fd, backing_file, backing_filename_len);
1681     }
1682     lseek(fd, s->l1_table_offset, SEEK_SET);
1683     tmp = 0;
1684     for(i = 0;i < l1_size; i++) {
1685         write(fd, &tmp, sizeof(tmp));
1686     }
1687     lseek(fd, s->refcount_table_offset, SEEK_SET);
1688     write(fd, s->refcount_table, s->cluster_size);
1689
1690     lseek(fd, s->refcount_block_offset, SEEK_SET);
1691     write(fd, s->refcount_block, ref_clusters * s->cluster_size);
1692
1693     qemu_free(s->refcount_table);
1694     qemu_free(s->refcount_block);
1695     close(fd);
1696     return 0;
1697 }
1698
1699 static int qcow_create(const char *filename, int64_t total_size,
1700                        const char *backing_file, int flags)
1701 {
1702     return qcow_create2(filename, total_size, backing_file, NULL, flags);
1703 }
1704
1705 static int qcow_make_empty(BlockDriverState *bs)
1706 {
1707 #if 0
1708     /* XXX: not correct */
1709     BDRVQcowState *s = bs->opaque;
1710     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1711     int ret;
1712
1713     memset(s->l1_table, 0, l1_length);
1714     if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1715         return -1;
1716     ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1717     if (ret < 0)
1718         return ret;
1719
1720     l2_cache_reset(bs);
1721 #endif
1722     return 0;
1723 }
1724
1725 /* XXX: put compressed sectors first, then all the cluster aligned
1726    tables to avoid losing bytes in alignment */
1727 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1728                                  const uint8_t *buf, int nb_sectors)
1729 {
1730     BDRVQcowState *s = bs->opaque;
1731     z_stream strm;
1732     int ret, out_len;
1733     uint8_t *out_buf;
1734     uint64_t cluster_offset;
1735
1736     if (nb_sectors == 0) {
1737         /* align end of file to a sector boundary to ease reading with
1738            sector based I/Os */
1739         cluster_offset = bdrv_getlength(s->hd);
1740         cluster_offset = (cluster_offset + 511) & ~511;
1741         bdrv_truncate(s->hd, cluster_offset);
1742         return 0;
1743     }
1744
1745     if (nb_sectors != s->cluster_sectors)
1746         return -EINVAL;
1747
1748     out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1749
1750     /* best compression, small window, no zlib header */
1751     memset(&strm, 0, sizeof(strm));
1752     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1753                        Z_DEFLATED, -12,
1754                        9, Z_DEFAULT_STRATEGY);
1755     if (ret != 0) {
1756         qemu_free(out_buf);
1757         return -1;
1758     }
1759
1760     strm.avail_in = s->cluster_size;
1761     strm.next_in = (uint8_t *)buf;
1762     strm.avail_out = s->cluster_size;
1763     strm.next_out = out_buf;
1764
1765     ret = deflate(&strm, Z_FINISH);
1766     if (ret != Z_STREAM_END && ret != Z_OK) {
1767         qemu_free(out_buf);
1768         deflateEnd(&strm);
1769         return -1;
1770     }
1771     out_len = strm.next_out - out_buf;
1772
1773     deflateEnd(&strm);
1774
1775     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1776         /* could not compress: write normal cluster */
1777         qcow_write(bs, sector_num, buf, s->cluster_sectors);
1778     } else {
1779         cluster_offset = alloc_compressed_cluster_offset(bs, sector_num << 9,
1780                                               out_len);
1781         if (!cluster_offset)
1782             return -1;
1783         cluster_offset &= s->cluster_offset_mask;
1784         if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1785             qemu_free(out_buf);
1786             return -1;
1787         }
1788     }
1789
1790     qemu_free(out_buf);
1791     return 0;
1792 }
1793
1794 static void qcow_flush(BlockDriverState *bs)
1795 {
1796     BDRVQcowState *s = bs->opaque;
1797     bdrv_flush(s->hd);
1798 }
1799
1800 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1801 {
1802     BDRVQcowState *s = bs->opaque;
1803     bdi->cluster_size = s->cluster_size;
1804     bdi->vm_state_offset = (int64_t)s->l1_vm_state_index <<
1805         (s->cluster_bits + s->l2_bits);
1806     return 0;
1807 }
1808
1809 /*********************************************************/
1810 /* snapshot support */
1811
1812 /* update the refcounts of snapshots and the copied flag */
1813 static int update_snapshot_refcount(BlockDriverState *bs,
1814                                     int64_t l1_table_offset,
1815                                     int l1_size,
1816                                     int addend)
1817 {
1818     BDRVQcowState *s = bs->opaque;
1819     uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;
1820     int64_t old_offset, old_l2_offset;
1821     int l2_size, i, j, l1_modified, l2_modified, nb_csectors, refcount;
1822
1823     l2_cache_reset(bs);
1824
1825     l2_table = NULL;
1826     l1_table = NULL;
1827     l1_size2 = l1_size * sizeof(uint64_t);
1828     l1_allocated = 0;
1829     if (l1_table_offset != s->l1_table_offset) {
1830         l1_table = qemu_malloc(l1_size2);
1831         l1_allocated = 1;
1832         if (bdrv_pread(s->hd, l1_table_offset,
1833                        l1_table, l1_size2) != l1_size2)
1834             goto fail;
1835         for(i = 0;i < l1_size; i++)
1836             be64_to_cpus(&l1_table[i]);
1837     } else {
1838         assert(l1_size == s->l1_size);
1839         l1_table = s->l1_table;
1840         l1_allocated = 0;
1841     }
1842
1843     l2_size = s->l2_size * sizeof(uint64_t);
1844     l2_table = qemu_malloc(l2_size);
1845     l1_modified = 0;
1846     for(i = 0; i < l1_size; i++) {
1847         l2_offset = l1_table[i];
1848         if (l2_offset) {
1849             old_l2_offset = l2_offset;
1850             l2_offset &= ~QCOW_OFLAG_COPIED;
1851             l2_modified = 0;
1852             if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
1853                 goto fail;
1854             for(j = 0; j < s->l2_size; j++) {
1855                 offset = be64_to_cpu(l2_table[j]);
1856                 if (offset != 0) {
1857                     old_offset = offset;
1858                     offset &= ~QCOW_OFLAG_COPIED;
1859                     if (offset & QCOW_OFLAG_COMPRESSED) {
1860                         nb_csectors = ((offset >> s->csize_shift) &
1861                                        s->csize_mask) + 1;
1862                         if (addend != 0)
1863                             update_refcount(bs, (offset & s->cluster_offset_mask) & ~511,
1864                                             nb_csectors * 512, addend);
1865                         /* compressed clusters are never modified */
1866                         refcount = 2;
1867                     } else {
1868                         if (addend != 0) {
1869                             refcount = update_cluster_refcount(bs, offset >> s->cluster_bits, addend);
1870                         } else {
1871                             refcount = get_refcount(bs, offset >> s->cluster_bits);
1872                         }
1873                     }
1874
1875                     if (refcount == 1) {
1876                         offset |= QCOW_OFLAG_COPIED;
1877                     }
1878                     if (offset != old_offset) {
1879                         l2_table[j] = cpu_to_be64(offset);
1880                         l2_modified = 1;
1881                     }
1882                 }
1883             }
1884             if (l2_modified) {
1885                 if (bdrv_pwrite(s->hd,
1886                                 l2_offset, l2_table, l2_size) != l2_size)
1887                     goto fail;
1888             }
1889
1890             if (addend != 0) {
1891                 refcount = update_cluster_refcount(bs, l2_offset >> s->cluster_bits, addend);
1892             } else {
1893                 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1894             }
1895             if (refcount == 1) {
1896                 l2_offset |= QCOW_OFLAG_COPIED;
1897             }
1898             if (l2_offset != old_l2_offset) {
1899                 l1_table[i] = l2_offset;
1900                 l1_modified = 1;
1901             }
1902         }
1903     }
1904     if (l1_modified) {
1905         for(i = 0; i < l1_size; i++)
1906             cpu_to_be64s(&l1_table[i]);
1907         if (bdrv_pwrite(s->hd, l1_table_offset, l1_table,
1908                         l1_size2) != l1_size2)
1909             goto fail;
1910         for(i = 0; i < l1_size; i++)
1911             be64_to_cpus(&l1_table[i]);
1912     }
1913     if (l1_allocated)
1914         qemu_free(l1_table);
1915     qemu_free(l2_table);
1916     return 0;
1917  fail:
1918     if (l1_allocated)
1919         qemu_free(l1_table);
1920     qemu_free(l2_table);
1921     return -EIO;
1922 }
1923
1924 static void qcow_free_snapshots(BlockDriverState *bs)
1925 {
1926     BDRVQcowState *s = bs->opaque;
1927     int i;
1928
1929     for(i = 0; i < s->nb_snapshots; i++) {
1930         qemu_free(s->snapshots[i].name);
1931         qemu_free(s->snapshots[i].id_str);
1932     }
1933     qemu_free(s->snapshots);
1934     s->snapshots = NULL;
1935     s->nb_snapshots = 0;
1936 }
1937
1938 static int qcow_read_snapshots(BlockDriverState *bs)
1939 {
1940     BDRVQcowState *s = bs->opaque;
1941     QCowSnapshotHeader h;
1942     QCowSnapshot *sn;
1943     int i, id_str_size, name_size;
1944     int64_t offset;
1945     uint32_t extra_data_size;
1946
1947     if (!s->nb_snapshots) {
1948         s->snapshots = NULL;
1949         s->snapshots_size = 0;
1950         return 0;
1951     }
1952
1953     offset = s->snapshots_offset;
1954     s->snapshots = qemu_mallocz(s->nb_snapshots * sizeof(QCowSnapshot));
1955     for(i = 0; i < s->nb_snapshots; i++) {
1956         offset = align_offset(offset, 8);
1957         if (bdrv_pread(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1958             goto fail;
1959         offset += sizeof(h);
1960         sn = s->snapshots + i;
1961         sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
1962         sn->l1_size = be32_to_cpu(h.l1_size);
1963         sn->vm_state_size = be32_to_cpu(h.vm_state_size);
1964         sn->date_sec = be32_to_cpu(h.date_sec);
1965         sn->date_nsec = be32_to_cpu(h.date_nsec);
1966         sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
1967         extra_data_size = be32_to_cpu(h.extra_data_size);
1968
1969         id_str_size = be16_to_cpu(h.id_str_size);
1970         name_size = be16_to_cpu(h.name_size);
1971
1972         offset += extra_data_size;
1973
1974         sn->id_str = qemu_malloc(id_str_size + 1);
1975         if (bdrv_pread(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1976             goto fail;
1977         offset += id_str_size;
1978         sn->id_str[id_str_size] = '\0';
1979
1980         sn->name = qemu_malloc(name_size + 1);
1981         if (bdrv_pread(s->hd, offset, sn->name, name_size) != name_size)
1982             goto fail;
1983         offset += name_size;
1984         sn->name[name_size] = '\0';
1985     }
1986     s->snapshots_size = offset - s->snapshots_offset;
1987     return 0;
1988  fail:
1989     qcow_free_snapshots(bs);
1990     return -1;
1991 }
1992
1993 /* add at the end of the file a new list of snapshots */
1994 static int qcow_write_snapshots(BlockDriverState *bs)
1995 {
1996     BDRVQcowState *s = bs->opaque;
1997     QCowSnapshot *sn;
1998     QCowSnapshotHeader h;
1999     int i, name_size, id_str_size, snapshots_size;
2000     uint64_t data64;
2001     uint32_t data32;
2002     int64_t offset, snapshots_offset;
2003
2004     /* compute the size of the snapshots */
2005     offset = 0;
2006     for(i = 0; i < s->nb_snapshots; i++) {
2007         sn = s->snapshots + i;
2008         offset = align_offset(offset, 8);
2009         offset += sizeof(h);
2010         offset += strlen(sn->id_str);
2011         offset += strlen(sn->name);
2012     }
2013     snapshots_size = offset;
2014
2015     snapshots_offset = alloc_clusters(bs, snapshots_size);
2016     offset = snapshots_offset;
2017
2018     for(i = 0; i < s->nb_snapshots; i++) {
2019         sn = s->snapshots + i;
2020         memset(&h, 0, sizeof(h));
2021         h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);
2022         h.l1_size = cpu_to_be32(sn->l1_size);
2023         h.vm_state_size = cpu_to_be32(sn->vm_state_size);
2024         h.date_sec = cpu_to_be32(sn->date_sec);
2025         h.date_nsec = cpu_to_be32(sn->date_nsec);
2026         h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);
2027
2028         id_str_size = strlen(sn->id_str);
2029         name_size = strlen(sn->name);
2030         h.id_str_size = cpu_to_be16(id_str_size);
2031         h.name_size = cpu_to_be16(name_size);
2032         offset = align_offset(offset, 8);
2033         if (bdrv_pwrite(s->hd, offset, &h, sizeof(h)) != sizeof(h))
2034             goto fail;
2035         offset += sizeof(h);
2036         if (bdrv_pwrite(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
2037             goto fail;
2038         offset += id_str_size;
2039         if (bdrv_pwrite(s->hd, offset, sn->name, name_size) != name_size)
2040             goto fail;
2041         offset += name_size;
2042     }
2043
2044     /* update the various header fields */
2045     data64 = cpu_to_be64(snapshots_offset);
2046     if (bdrv_pwrite(s->hd, offsetof(QCowHeader, snapshots_offset),
2047                     &data64, sizeof(data64)) != sizeof(data64))
2048         goto fail;
2049     data32 = cpu_to_be32(s->nb_snapshots);
2050     if (bdrv_pwrite(s->hd, offsetof(QCowHeader, nb_snapshots),
2051                     &data32, sizeof(data32)) != sizeof(data32))
2052         goto fail;
2053
2054     /* free the old snapshot table */
2055     free_clusters(bs, s->snapshots_offset, s->snapshots_size);
2056     s->snapshots_offset = snapshots_offset;
2057     s->snapshots_size = snapshots_size;
2058     return 0;
2059  fail:
2060     return -1;
2061 }
2062
2063 static void find_new_snapshot_id(BlockDriverState *bs,
2064                                  char *id_str, int id_str_size)
2065 {
2066     BDRVQcowState *s = bs->opaque;
2067     QCowSnapshot *sn;
2068     int i, id, id_max = 0;
2069
2070     for(i = 0; i < s->nb_snapshots; i++) {
2071         sn = s->snapshots + i;
2072         id = strtoul(sn->id_str, NULL, 10);
2073         if (id > id_max)
2074             id_max = id;
2075     }
2076     snprintf(id_str, id_str_size, "%d", id_max + 1);
2077 }
2078
2079 static int find_snapshot_by_id(BlockDriverState *bs, const char *id_str)
2080 {
2081     BDRVQcowState *s = bs->opaque;
2082     int i;
2083
2084     for(i = 0; i < s->nb_snapshots; i++) {
2085         if (!strcmp(s->snapshots[i].id_str, id_str))
2086             return i;
2087     }
2088     return -1;
2089 }
2090
2091 static int find_snapshot_by_id_or_name(BlockDriverState *bs, const char *name)
2092 {
2093     BDRVQcowState *s = bs->opaque;
2094     int i, ret;
2095
2096     ret = find_snapshot_by_id(bs, name);
2097     if (ret >= 0)
2098         return ret;
2099     for(i = 0; i < s->nb_snapshots; i++) {
2100         if (!strcmp(s->snapshots[i].name, name))
2101             return i;
2102     }
2103     return -1;
2104 }
2105
2106 /* if no id is provided, a new one is constructed */
2107 static int qcow_snapshot_create(BlockDriverState *bs,
2108                                 QEMUSnapshotInfo *sn_info)
2109 {
2110     BDRVQcowState *s = bs->opaque;
2111     QCowSnapshot *snapshots1, sn1, *sn = &sn1;
2112     int i, ret;
2113     uint64_t *l1_table = NULL;
2114
2115     memset(sn, 0, sizeof(*sn));
2116
2117     if (sn_info->id_str[0] == '\0') {
2118         /* compute a new id */
2119         find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));
2120     }
2121
2122     /* check that the ID is unique */
2123     if (find_snapshot_by_id(bs, sn_info->id_str) >= 0)
2124         return -ENOENT;
2125
2126     sn->id_str = qemu_strdup(sn_info->id_str);
2127     if (!sn->id_str)
2128         goto fail;
2129     sn->name = qemu_strdup(sn_info->name);
2130     if (!sn->name)
2131         goto fail;
2132     sn->vm_state_size = sn_info->vm_state_size;
2133     sn->date_sec = sn_info->date_sec;
2134     sn->date_nsec = sn_info->date_nsec;
2135     sn->vm_clock_nsec = sn_info->vm_clock_nsec;
2136
2137     ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);
2138     if (ret < 0)
2139         goto fail;
2140
2141     /* create the L1 table of the snapshot */
2142     sn->l1_table_offset = alloc_clusters(bs, s->l1_size * sizeof(uint64_t));
2143     sn->l1_size = s->l1_size;
2144
2145     l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
2146     for(i = 0; i < s->l1_size; i++) {
2147         l1_table[i] = cpu_to_be64(s->l1_table[i]);
2148     }
2149     if (bdrv_pwrite(s->hd, sn->l1_table_offset,
2150                     l1_table, s->l1_size * sizeof(uint64_t)) !=
2151         (s->l1_size * sizeof(uint64_t)))
2152         goto fail;
2153     qemu_free(l1_table);
2154     l1_table = NULL;
2155
2156     snapshots1 = qemu_malloc((s->nb_snapshots + 1) * sizeof(QCowSnapshot));
2157     if (s->snapshots) {
2158         memcpy(snapshots1, s->snapshots, s->nb_snapshots * sizeof(QCowSnapshot));
2159         qemu_free(s->snapshots);
2160     }
2161     s->snapshots = snapshots1;
2162     s->snapshots[s->nb_snapshots++] = *sn;
2163
2164     if (qcow_write_snapshots(bs) < 0)
2165         goto fail;
2166 #ifdef DEBUG_ALLOC
2167     check_refcounts(bs);
2168 #endif
2169     return 0;
2170  fail:
2171     qemu_free(sn->name);
2172     qemu_free(l1_table);
2173     return -1;
2174 }
2175
2176 /* copy the snapshot 'snapshot_name' into the current disk image */
2177 static int qcow_snapshot_goto(BlockDriverState *bs,
2178                               const char *snapshot_id)
2179 {
2180     BDRVQcowState *s = bs->opaque;
2181     QCowSnapshot *sn;
2182     int i, snapshot_index, l1_size2;
2183
2184     snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2185     if (snapshot_index < 0)
2186         return -ENOENT;
2187     sn = &s->snapshots[snapshot_index];
2188
2189     if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, -1) < 0)
2190         goto fail;
2191
2192     if (grow_l1_table(bs, sn->l1_size) < 0)
2193         goto fail;
2194
2195     s->l1_size = sn->l1_size;
2196     l1_size2 = s->l1_size * sizeof(uint64_t);
2197     /* copy the snapshot l1 table to the current l1 table */
2198     if (bdrv_pread(s->hd, sn->l1_table_offset,
2199                    s->l1_table, l1_size2) != l1_size2)
2200         goto fail;
2201     if (bdrv_pwrite(s->hd, s->l1_table_offset,
2202                     s->l1_table, l1_size2) != l1_size2)
2203         goto fail;
2204     for(i = 0;i < s->l1_size; i++) {
2205         be64_to_cpus(&s->l1_table[i]);
2206     }
2207
2208     if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1) < 0)
2209         goto fail;
2210
2211 #ifdef DEBUG_ALLOC
2212     check_refcounts(bs);
2213 #endif
2214     return 0;
2215  fail:
2216     return -EIO;
2217 }
2218
2219 static int qcow_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2220 {
2221     BDRVQcowState *s = bs->opaque;
2222     QCowSnapshot *sn;
2223     int snapshot_index, ret;
2224
2225     snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2226     if (snapshot_index < 0)
2227         return -ENOENT;
2228     sn = &s->snapshots[snapshot_index];
2229
2230     ret = update_snapshot_refcount(bs, sn->l1_table_offset, sn->l1_size, -1);
2231     if (ret < 0)
2232         return ret;
2233     /* must update the copied flag on the current cluster offsets */
2234     ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
2235     if (ret < 0)
2236         return ret;
2237     free_clusters(bs, sn->l1_table_offset, sn->l1_size * sizeof(uint64_t));
2238
2239     qemu_free(sn->id_str);
2240     qemu_free(sn->name);
2241     memmove(sn, sn + 1, (s->nb_snapshots - snapshot_index - 1) * sizeof(*sn));
2242     s->nb_snapshots--;
2243     ret = qcow_write_snapshots(bs);
2244     if (ret < 0) {
2245         /* XXX: restore snapshot if error ? */
2246         return ret;
2247     }
2248 #ifdef DEBUG_ALLOC
2249     check_refcounts(bs);
2250 #endif
2251     return 0;
2252 }
2253
2254 static int qcow_snapshot_list(BlockDriverState *bs,
2255                               QEMUSnapshotInfo **psn_tab)
2256 {
2257     BDRVQcowState *s = bs->opaque;
2258     QEMUSnapshotInfo *sn_tab, *sn_info;
2259     QCowSnapshot *sn;
2260     int i;
2261
2262     sn_tab = qemu_mallocz(s->nb_snapshots * sizeof(QEMUSnapshotInfo));
2263     for(i = 0; i < s->nb_snapshots; i++) {
2264         sn_info = sn_tab + i;
2265         sn = s->snapshots + i;
2266         pstrcpy(sn_info->id_str, sizeof(sn_info->id_str),
2267                 sn->id_str);
2268         pstrcpy(sn_info->name, sizeof(sn_info->name),
2269                 sn->name);
2270         sn_info->vm_state_size = sn->vm_state_size;
2271         sn_info->date_sec = sn->date_sec;
2272         sn_info->date_nsec = sn->date_nsec;
2273         sn_info->vm_clock_nsec = sn->vm_clock_nsec;
2274     }
2275     *psn_tab = sn_tab;
2276     return s->nb_snapshots;
2277 }
2278
2279 /*********************************************************/
2280 /* refcount handling */
2281
2282 static int refcount_init(BlockDriverState *bs)
2283 {
2284     BDRVQcowState *s = bs->opaque;
2285     int ret, refcount_table_size2, i;
2286
2287     s->refcount_block_cache = qemu_malloc(s->cluster_size);
2288     refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
2289     s->refcount_table = qemu_malloc(refcount_table_size2);
2290     if (s->refcount_table_size > 0) {
2291         ret = bdrv_pread(s->hd, s->refcount_table_offset,
2292                          s->refcount_table, refcount_table_size2);
2293         if (ret != refcount_table_size2)
2294             goto fail;
2295         for(i = 0; i < s->refcount_table_size; i++)
2296             be64_to_cpus(&s->refcount_table[i]);
2297     }
2298     return 0;
2299  fail:
2300     return -ENOMEM;
2301 }
2302
2303 static void refcount_close(BlockDriverState *bs)
2304 {
2305     BDRVQcowState *s = bs->opaque;
2306     qemu_free(s->refcount_block_cache);
2307     qemu_free(s->refcount_table);
2308 }
2309
2310
2311 static int load_refcount_block(BlockDriverState *bs,
2312                                int64_t refcount_block_offset)
2313 {
2314     BDRVQcowState *s = bs->opaque;
2315     int ret;
2316     ret = bdrv_pread(s->hd, refcount_block_offset, s->refcount_block_cache,
2317                      s->cluster_size);
2318     if (ret != s->cluster_size)
2319         return -EIO;
2320     s->refcount_block_cache_offset = refcount_block_offset;
2321     return 0;
2322 }
2323
2324 static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
2325 {
2326     BDRVQcowState *s = bs->opaque;
2327     int refcount_table_index, block_index;
2328     int64_t refcount_block_offset;
2329
2330     refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2331     if (refcount_table_index >= s->refcount_table_size)
2332         return 0;
2333     refcount_block_offset = s->refcount_table[refcount_table_index];
2334     if (!refcount_block_offset)
2335         return 0;
2336     if (refcount_block_offset != s->refcount_block_cache_offset) {
2337         /* better than nothing: return allocated if read error */
2338         if (load_refcount_block(bs, refcount_block_offset) < 0)
2339             return 1;
2340     }
2341     block_index = cluster_index &
2342         ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2343     return be16_to_cpu(s->refcount_block_cache[block_index]);
2344 }
2345
2346 /* return < 0 if error */
2347 static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)
2348 {
2349     BDRVQcowState *s = bs->opaque;
2350     int i, nb_clusters;
2351
2352     nb_clusters = size_to_clusters(s, size);
2353 retry:
2354     for(i = 0; i < nb_clusters; i++) {
2355         int64_t i = s->free_cluster_index++;
2356         if (get_refcount(bs, i) != 0)
2357             goto retry;
2358     }
2359 #ifdef DEBUG_ALLOC2
2360     printf("alloc_clusters: size=%lld -> %lld\n",
2361             size,
2362             (s->free_cluster_index - nb_clusters) << s->cluster_bits);
2363 #endif
2364     return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
2365 }
2366
2367 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size)
2368 {
2369     int64_t offset;
2370
2371     offset = alloc_clusters_noref(bs, size);
2372     update_refcount(bs, offset, size, 1);
2373     return offset;
2374 }
2375
2376 /* only used to allocate compressed sectors. We try to allocate
2377    contiguous sectors. size must be <= cluster_size */
2378 static int64_t alloc_bytes(BlockDriverState *bs, int size)
2379 {
2380     BDRVQcowState *s = bs->opaque;
2381     int64_t offset, cluster_offset;
2382     int free_in_cluster;
2383
2384     assert(size > 0 && size <= s->cluster_size);
2385     if (s->free_byte_offset == 0) {
2386         s->free_byte_offset = alloc_clusters(bs, s->cluster_size);
2387     }
2388  redo:
2389     free_in_cluster = s->cluster_size -
2390         (s->free_byte_offset & (s->cluster_size - 1));
2391     if (size <= free_in_cluster) {
2392         /* enough space in current cluster */
2393         offset = s->free_byte_offset;
2394         s->free_byte_offset += size;
2395         free_in_cluster -= size;
2396         if (free_in_cluster == 0)
2397             s->free_byte_offset = 0;
2398         if ((offset & (s->cluster_size - 1)) != 0)
2399             update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2400     } else {
2401         offset = alloc_clusters(bs, s->cluster_size);
2402         cluster_offset = s->free_byte_offset & ~(s->cluster_size - 1);
2403         if ((cluster_offset + s->cluster_size) == offset) {
2404             /* we are lucky: contiguous data */
2405             offset = s->free_byte_offset;
2406             update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2407             s->free_byte_offset += size;
2408         } else {
2409             s->free_byte_offset = offset;
2410             goto redo;
2411         }
2412     }
2413     return offset;
2414 }
2415
2416 static void free_clusters(BlockDriverState *bs,
2417                           int64_t offset, int64_t size)
2418 {
2419     update_refcount(bs, offset, size, -1);
2420 }
2421
2422 static int grow_refcount_table(BlockDriverState *bs, int min_size)
2423 {
2424     BDRVQcowState *s = bs->opaque;
2425     int new_table_size, new_table_size2, refcount_table_clusters, i, ret;
2426     uint64_t *new_table;
2427     int64_t table_offset;
2428     uint8_t data[12];
2429     int old_table_size;
2430     int64_t old_table_offset;
2431
2432     if (min_size <= s->refcount_table_size)
2433         return 0;
2434     /* compute new table size */
2435     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2436     for(;;) {
2437         if (refcount_table_clusters == 0) {
2438             refcount_table_clusters = 1;
2439         } else {
2440             refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
2441         }
2442         new_table_size = refcount_table_clusters << (s->cluster_bits - 3);
2443         if (min_size <= new_table_size)
2444             break;
2445     }
2446 #ifdef DEBUG_ALLOC2
2447     printf("grow_refcount_table from %d to %d\n",
2448            s->refcount_table_size,
2449            new_table_size);
2450 #endif
2451     new_table_size2 = new_table_size * sizeof(uint64_t);
2452     new_table = qemu_mallocz(new_table_size2);
2453     memcpy(new_table, s->refcount_table,
2454            s->refcount_table_size * sizeof(uint64_t));
2455     for(i = 0; i < s->refcount_table_size; i++)
2456         cpu_to_be64s(&new_table[i]);
2457     /* Note: we cannot update the refcount now to avoid recursion */
2458     table_offset = alloc_clusters_noref(bs, new_table_size2);
2459     ret = bdrv_pwrite(s->hd, table_offset, new_table, new_table_size2);
2460     if (ret != new_table_size2)
2461         goto fail;
2462     for(i = 0; i < s->refcount_table_size; i++)
2463         be64_to_cpus(&new_table[i]);
2464
2465     cpu_to_be64w((uint64_t*)data, table_offset);
2466     cpu_to_be32w((uint32_t*)(data + 8), refcount_table_clusters);
2467     if (bdrv_pwrite(s->hd, offsetof(QCowHeader, refcount_table_offset),
2468                     data, sizeof(data)) != sizeof(data))
2469         goto fail;
2470     qemu_free(s->refcount_table);
2471     old_table_offset = s->refcount_table_offset;
2472     old_table_size = s->refcount_table_size;
2473     s->refcount_table = new_table;
2474     s->refcount_table_size = new_table_size;
2475     s->refcount_table_offset = table_offset;
2476
2477     update_refcount(bs, table_offset, new_table_size2, 1);
2478     free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));
2479     return 0;
2480  fail:
2481     free_clusters(bs, table_offset, new_table_size2);
2482     qemu_free(new_table);
2483     return -EIO;
2484 }
2485
2486 /* addend must be 1 or -1 */
2487 /* XXX: cache several refcount block clusters ? */
2488 static int update_cluster_refcount(BlockDriverState *bs,
2489                                    int64_t cluster_index,
2490                                    int addend)
2491 {
2492     BDRVQcowState *s = bs->opaque;
2493     int64_t offset, refcount_block_offset;
2494     int ret, refcount_table_index, block_index, refcount;
2495     uint64_t data64;
2496
2497     refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2498     if (refcount_table_index >= s->refcount_table_size) {
2499         if (addend < 0)
2500             return -EINVAL;
2501         ret = grow_refcount_table(bs, refcount_table_index + 1);
2502         if (ret < 0)
2503             return ret;
2504     }
2505     refcount_block_offset = s->refcount_table[refcount_table_index];
2506     if (!refcount_block_offset) {
2507         if (addend < 0)
2508             return -EINVAL;
2509         /* create a new refcount block */
2510         /* Note: we cannot update the refcount now to avoid recursion */
2511         offset = alloc_clusters_noref(bs, s->cluster_size);
2512         memset(s->refcount_block_cache, 0, s->cluster_size);
2513         ret = bdrv_pwrite(s->hd, offset, s->refcount_block_cache, s->cluster_size);
2514         if (ret != s->cluster_size)
2515             return -EINVAL;
2516         s->refcount_table[refcount_table_index] = offset;
2517         data64 = cpu_to_be64(offset);
2518         ret = bdrv_pwrite(s->hd, s->refcount_table_offset +
2519                           refcount_table_index * sizeof(uint64_t),
2520                           &data64, sizeof(data64));
2521         if (ret != sizeof(data64))
2522             return -EINVAL;
2523
2524         refcount_block_offset = offset;
2525         s->refcount_block_cache_offset = offset;
2526         update_refcount(bs, offset, s->cluster_size, 1);
2527     } else {
2528         if (refcount_block_offset != s->refcount_block_cache_offset) {
2529             if (load_refcount_block(bs, refcount_block_offset) < 0)
2530                 return -EIO;
2531         }
2532     }
2533     /* we can update the count and save it */
2534     block_index = cluster_index &
2535         ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2536     refcount = be16_to_cpu(s->refcount_block_cache[block_index]);
2537     refcount += addend;
2538     if (refcount < 0 || refcount > 0xffff)
2539         return -EINVAL;
2540     if (refcount == 0 && cluster_index < s->free_cluster_index) {
2541         s->free_cluster_index = cluster_index;
2542     }
2543     s->refcount_block_cache[block_index] = cpu_to_be16(refcount);
2544     if (bdrv_pwrite(s->hd,
2545                     refcount_block_offset + (block_index << REFCOUNT_SHIFT),
2546                     &s->refcount_block_cache[block_index], 2) != 2)
2547         return -EIO;
2548     return refcount;
2549 }
2550
2551 static void update_refcount(BlockDriverState *bs,
2552                             int64_t offset, int64_t length,
2553                             int addend)
2554 {
2555     BDRVQcowState *s = bs->opaque;
2556     int64_t start, last, cluster_offset;
2557
2558 #ifdef DEBUG_ALLOC2
2559     printf("update_refcount: offset=%lld size=%lld addend=%d\n",
2560            offset, length, addend);
2561 #endif
2562     if (length <= 0)
2563         return;
2564     start = offset & ~(s->cluster_size - 1);
2565     last = (offset + length - 1) & ~(s->cluster_size - 1);
2566     for(cluster_offset = start; cluster_offset <= last;
2567         cluster_offset += s->cluster_size) {
2568         update_cluster_refcount(bs, cluster_offset >> s->cluster_bits, addend);
2569     }
2570 }
2571
2572 /*
2573  * Increases the refcount for a range of clusters in a given refcount table.
2574  * This is used to construct a temporary refcount table out of L1 and L2 tables
2575  * which can be compared the the refcount table saved in the image.
2576  *
2577  * Returns the number of errors in the image that were found
2578  */
2579 static int inc_refcounts(BlockDriverState *bs,
2580                           uint16_t *refcount_table,
2581                           int refcount_table_size,
2582                           int64_t offset, int64_t size)
2583 {
2584     BDRVQcowState *s = bs->opaque;
2585     int64_t start, last, cluster_offset;
2586     int k;
2587     int errors = 0;
2588
2589     if (size <= 0)
2590         return 0;
2591
2592     start = offset & ~(s->cluster_size - 1);
2593     last = (offset + size - 1) & ~(s->cluster_size - 1);
2594     for(cluster_offset = start; cluster_offset <= last;
2595         cluster_offset += s->cluster_size) {
2596         k = cluster_offset >> s->cluster_bits;
2597         if (k < 0 || k >= refcount_table_size) {
2598             fprintf(stderr, "ERROR: invalid cluster offset=0x%" PRIx64 "\n",
2599                 cluster_offset);
2600             errors++;
2601         } else {
2602             if (++refcount_table[k] == 0) {
2603                 fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64
2604                     "\n", cluster_offset);
2605                 errors++;
2606             }
2607         }
2608     }
2609
2610     return errors;
2611 }
2612
2613 /*
2614  * Increases the refcount in the given refcount table for the all clusters
2615  * referenced in the L2 table. While doing so, performs some checks on L2
2616  * entries.
2617  *
2618  * Returns the number of errors found by the checks or -errno if an internal
2619  * error occurred.
2620  */
2621 static int check_refcounts_l2(BlockDriverState *bs,
2622     uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,
2623     int check_copied)
2624 {
2625     BDRVQcowState *s = bs->opaque;
2626     uint64_t *l2_table, offset;
2627     int i, l2_size, nb_csectors, refcount;
2628     int errors = 0;
2629
2630     /* Read L2 table from disk */
2631     l2_size = s->l2_size * sizeof(uint64_t);
2632     l2_table = qemu_malloc(l2_size);
2633
2634     if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
2635         goto fail;
2636
2637     /* Do the actual checks */
2638     for(i = 0; i < s->l2_size; i++) {
2639         offset = be64_to_cpu(l2_table[i]);
2640         if (offset != 0) {
2641             if (offset & QCOW_OFLAG_COMPRESSED) {
2642                 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
2643                 if (offset & QCOW_OFLAG_COPIED) {
2644                     fprintf(stderr, "ERROR: cluster %" PRId64 ": "
2645                         "copied flag must never be set for compressed "
2646                         "clusters\n", offset >> s->cluster_bits);
2647                     offset &= ~QCOW_OFLAG_COPIED;
2648                     errors++;
2649                 }
2650
2651                 /* Mark cluster as used */
2652                 nb_csectors = ((offset >> s->csize_shift) &
2653                                s->csize_mask) + 1;
2654                 offset &= s->cluster_offset_mask;
2655                 errors += inc_refcounts(bs, refcount_table,
2656                               refcount_table_size,
2657                               offset & ~511, nb_csectors * 512);
2658             } else {
2659                 /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
2660                 if (check_copied) {
2661                     uint64_t entry = offset;
2662                     offset &= ~QCOW_OFLAG_COPIED;
2663                     refcount = get_refcount(bs, offset >> s->cluster_bits);
2664                     if ((refcount == 1) != ((entry & QCOW_OFLAG_COPIED) != 0)) {
2665                         fprintf(stderr, "ERROR OFLAG_COPIED: offset=%"
2666                             PRIx64 " refcount=%d\n", entry, refcount);
2667                         errors++;
2668                     }
2669                 }
2670
2671                 /* Mark cluster as used */
2672                 offset &= ~QCOW_OFLAG_COPIED;
2673                 errors += inc_refcounts(bs, refcount_table,
2674                               refcount_table_size,
2675                               offset, s->cluster_size);
2676
2677                 /* Correct offsets are cluster aligned */
2678                 if (offset & (s->cluster_size - 1)) {
2679                     fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "
2680                         "properly aligned; L2 entry corrupted.\n", offset);
2681                     errors++;
2682                 }
2683             }
2684         }
2685     }
2686
2687     qemu_free(l2_table);
2688     return errors;
2689
2690 fail:
2691     fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
2692     qemu_free(l2_table);
2693     return -EIO;
2694 }
2695
2696 /*
2697  * Increases the refcount for the L1 table, its L2 tables and all referenced
2698  * clusters in the given refcount table. While doing so, performs some checks
2699  * on L1 and L2 entries.
2700  *
2701  * Returns the number of errors found by the checks or -errno if an internal
2702  * error occurred.
2703  */
2704 static int check_refcounts_l1(BlockDriverState *bs,
2705                               uint16_t *refcount_table,
2706                               int refcount_table_size,
2707                               int64_t l1_table_offset, int l1_size,
2708                               int check_copied)
2709 {
2710     BDRVQcowState *s = bs->opaque;
2711     uint64_t *l1_table, l2_offset, l1_size2;
2712     int i, refcount, ret;
2713     int errors = 0;
2714
2715     l1_size2 = l1_size * sizeof(uint64_t);
2716
2717     /* Mark L1 table as used */
2718     errors += inc_refcounts(bs, refcount_table, refcount_table_size,
2719                   l1_table_offset, l1_size2);
2720
2721     /* Read L1 table entries from disk */
2722     l1_table = qemu_malloc(l1_size2);
2723     if (bdrv_pread(s->hd, l1_table_offset,
2724                    l1_table, l1_size2) != l1_size2)
2725         goto fail;
2726     for(i = 0;i < l1_size; i++)
2727         be64_to_cpus(&l1_table[i]);
2728
2729     /* Do the actual checks */
2730     for(i = 0; i < l1_size; i++) {
2731         l2_offset = l1_table[i];
2732         if (l2_offset) {
2733             /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
2734             if (check_copied) {
2735                 refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED)
2736                     >> s->cluster_bits);
2737                 if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
2738                     fprintf(stderr, "ERROR OFLAG_COPIED: l2_offset=%" PRIx64
2739                         " refcount=%d\n", l2_offset, refcount);
2740                     errors++;
2741                 }
2742             }
2743
2744             /* Mark L2 table as used */
2745             l2_offset &= ~QCOW_OFLAG_COPIED;
2746             errors += inc_refcounts(bs, refcount_table,
2747                           refcount_table_size,
2748                           l2_offset,
2749                           s->cluster_size);
2750
2751             /* L2 tables are cluster aligned */
2752             if (l2_offset & (s->cluster_size - 1)) {
2753                 fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "
2754                     "cluster aligned; L1 entry corrupted\n", l2_offset);
2755                 errors++;
2756             }
2757
2758             /* Process and check L2 entries */
2759             ret = check_refcounts_l2(bs, refcount_table, refcount_table_size,
2760                 l2_offset, check_copied);
2761             if (ret < 0) {
2762                 goto fail;
2763             }
2764             errors += ret;
2765         }
2766     }
2767     qemu_free(l1_table);
2768     return errors;
2769
2770 fail:
2771     fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
2772     qemu_free(l1_table);
2773     return -EIO;
2774 }
2775
2776 /*
2777  * Checks an image for refcount consistency.
2778  *
2779  * Returns 0 if no errors are found, the number of errors in case the image is
2780  * detected as corrupted, and -errno when an internal error occured.
2781  */
2782 static int check_refcounts(BlockDriverState *bs)
2783 {
2784     BDRVQcowState *s = bs->opaque;
2785     int64_t size;
2786     int nb_clusters, refcount1, refcount2, i;
2787     QCowSnapshot *sn;
2788     uint16_t *refcount_table;
2789     int ret, errors = 0;
2790
2791     size = bdrv_getlength(s->hd);
2792     nb_clusters = size_to_clusters(s, size);
2793     refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));
2794
2795     /* header */
2796     errors += inc_refcounts(bs, refcount_table, nb_clusters,
2797                   0, s->cluster_size);
2798
2799     /* current L1 table */
2800     ret = check_refcounts_l1(bs, refcount_table, nb_clusters,
2801                        s->l1_table_offset, s->l1_size, 1);
2802     if (ret < 0) {
2803         return ret;
2804     }
2805     errors += ret;
2806
2807     /* snapshots */
2808     for(i = 0; i < s->nb_snapshots; i++) {
2809         sn = s->snapshots + i;
2810         check_refcounts_l1(bs, refcount_table, nb_clusters,
2811                            sn->l1_table_offset, sn->l1_size, 0);
2812     }
2813     errors += inc_refcounts(bs, refcount_table, nb_clusters,
2814                   s->snapshots_offset, s->snapshots_size);
2815
2816     /* refcount data */
2817     errors += inc_refcounts(bs, refcount_table, nb_clusters,
2818                   s->refcount_table_offset,
2819                   s->refcount_table_size * sizeof(uint64_t));
2820     for(i = 0; i < s->refcount_table_size; i++) {
2821         int64_t offset;
2822         offset = s->refcount_table[i];
2823         if (offset != 0) {
2824             errors += inc_refcounts(bs, refcount_table, nb_clusters,
2825                           offset, s->cluster_size);
2826         }
2827     }
2828
2829     /* compare ref counts */
2830     for(i = 0; i < nb_clusters; i++) {
2831         refcount1 = get_refcount(bs, i);
2832         refcount2 = refcount_table[i];
2833         if (refcount1 != refcount2) {
2834             fprintf(stderr, "ERROR cluster %d refcount=%d reference=%d\n",
2835                    i, refcount1, refcount2);
2836             errors++;
2837         }
2838     }
2839
2840     qemu_free(refcount_table);
2841
2842     return errors;
2843 }
2844
2845 static int qcow_check(BlockDriverState *bs)
2846 {
2847     return check_refcounts(bs);
2848 }
2849
2850 #if 0
2851 static void dump_refcounts(BlockDriverState *bs)
2852 {
2853     BDRVQcowState *s = bs->opaque;
2854     int64_t nb_clusters, k, k1, size;
2855     int refcount;
2856
2857     size = bdrv_getlength(s->hd);
2858     nb_clusters = size_to_clusters(s, size);
2859     for(k = 0; k < nb_clusters;) {
2860         k1 = k;
2861         refcount = get_refcount(bs, k);
2862         k++;
2863         while (k < nb_clusters && get_refcount(bs, k) == refcount)
2864             k++;
2865         printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
2866     }
2867 }
2868 #endif
2869
2870 static int qcow_put_buffer(BlockDriverState *bs, const uint8_t *buf,
2871                            int64_t pos, int size)
2872 {
2873     int growable = bs->growable;
2874
2875     bs->growable = 1;
2876     bdrv_pwrite(bs, pos, buf, size);
2877     bs->growable = growable;
2878
2879     return size;
2880 }
2881
2882 static int qcow_get_buffer(BlockDriverState *bs, uint8_t *buf,
2883                            int64_t pos, int size)
2884 {
2885     int growable = bs->growable;
2886     int ret;
2887
2888     bs->growable = 1;
2889     ret = bdrv_pread(bs, pos, buf, size);
2890     bs->growable = growable;
2891
2892     return ret;
2893 }
2894
2895 static BlockDriver bdrv_qcow2 = {
2896     .format_name        = "qcow2",
2897     .instance_size      = sizeof(BDRVQcowState),
2898     .bdrv_probe         = qcow_probe,
2899     .bdrv_open          = qcow_open,
2900     .bdrv_close         = qcow_close,
2901     .bdrv_create        = qcow_create,
2902     .bdrv_flush         = qcow_flush,
2903     .bdrv_is_allocated  = qcow_is_allocated,
2904     .bdrv_set_key       = qcow_set_key,
2905     .bdrv_make_empty    = qcow_make_empty,
2906
2907     .bdrv_aio_readv     = qcow_aio_readv,
2908     .bdrv_aio_writev    = qcow_aio_writev,
2909     .bdrv_aio_cancel    = qcow_aio_cancel,
2910     .aiocb_size         = sizeof(QCowAIOCB),
2911     .bdrv_write_compressed = qcow_write_compressed,
2912
2913     .bdrv_snapshot_create = qcow_snapshot_create,
2914     .bdrv_snapshot_goto = qcow_snapshot_goto,
2915     .bdrv_snapshot_delete = qcow_snapshot_delete,
2916     .bdrv_snapshot_list = qcow_snapshot_list,
2917     .bdrv_get_info      = qcow_get_info,
2918
2919     .bdrv_put_buffer    = qcow_put_buffer,
2920     .bdrv_get_buffer    = qcow_get_buffer,
2921
2922     .bdrv_create2 = qcow_create2,
2923     .bdrv_check = qcow_check,
2924 };
2925
2926 static void bdrv_qcow2_init(void)
2927 {
2928     bdrv_register(&bdrv_qcow2);
2929 }
2930
2931 block_init(bdrv_qcow2_init);