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