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