Statistics
| Branch: | Revision:

root / block-qcow2.c @ 94909d9f

History | View | Annotate | Download (88.9 kB)

1 585f8587 bellard
/*
2 585f8587 bellard
 * Block driver for the QCOW version 2 format
3 5fafdf24 ths
 *
4 585f8587 bellard
 * Copyright (c) 2004-2006 Fabrice Bellard
5 5fafdf24 ths
 *
6 585f8587 bellard
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 585f8587 bellard
 * of this software and associated documentation files (the "Software"), to deal
8 585f8587 bellard
 * in the Software without restriction, including without limitation the rights
9 585f8587 bellard
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 585f8587 bellard
 * copies of the Software, and to permit persons to whom the Software is
11 585f8587 bellard
 * furnished to do so, subject to the following conditions:
12 585f8587 bellard
 *
13 585f8587 bellard
 * The above copyright notice and this permission notice shall be included in
14 585f8587 bellard
 * all copies or substantial portions of the Software.
15 585f8587 bellard
 *
16 585f8587 bellard
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 585f8587 bellard
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 585f8587 bellard
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 585f8587 bellard
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 585f8587 bellard
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 585f8587 bellard
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 585f8587 bellard
 * THE SOFTWARE.
23 585f8587 bellard
 */
24 faf07963 pbrook
#include "qemu-common.h"
25 585f8587 bellard
#include "block_int.h"
26 585f8587 bellard
#include <zlib.h>
27 585f8587 bellard
#include "aes.h"
28 585f8587 bellard
#include <assert.h>
29 585f8587 bellard
30 585f8587 bellard
/*
31 585f8587 bellard
  Differences with QCOW:
32 585f8587 bellard

33 585f8587 bellard
  - Support for multiple incremental snapshots.
34 585f8587 bellard
  - Memory management by reference counts.
35 585f8587 bellard
  - Clusters which have a reference count of one have the bit
36 585f8587 bellard
    QCOW_OFLAG_COPIED to optimize write performance.
37 5fafdf24 ths
  - Size of compressed clusters is stored in sectors to reduce bit usage
38 585f8587 bellard
    in the cluster offsets.
39 585f8587 bellard
  - Support for storing additional data (such as the VM state) in the
40 3b46e624 ths
    snapshots.
41 585f8587 bellard
  - If a backing store is used, the cluster size is not constrained
42 585f8587 bellard
    (could be backported to QCOW).
43 585f8587 bellard
  - L2 tables have always a size of one cluster.
44 585f8587 bellard
*/
45 585f8587 bellard
46 585f8587 bellard
//#define DEBUG_ALLOC
47 585f8587 bellard
//#define DEBUG_ALLOC2
48 9b80ddf3 aliguori
//#define DEBUG_EXT
49 5fafdf24 ths
50 585f8587 bellard
#define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
51 585f8587 bellard
#define QCOW_VERSION 2
52 585f8587 bellard
53 585f8587 bellard
#define QCOW_CRYPT_NONE 0
54 585f8587 bellard
#define QCOW_CRYPT_AES  1
55 585f8587 bellard
56 095a9c58 aliguori
#define QCOW_MAX_CRYPT_CLUSTERS 32
57 095a9c58 aliguori
58 585f8587 bellard
/* indicate that the refcount of the referenced cluster is exactly one. */
59 585f8587 bellard
#define QCOW_OFLAG_COPIED     (1LL << 63)
60 585f8587 bellard
/* indicate that the cluster is compressed (they never have the copied flag) */
61 585f8587 bellard
#define QCOW_OFLAG_COMPRESSED (1LL << 62)
62 585f8587 bellard
63 585f8587 bellard
#define REFCOUNT_SHIFT 1 /* refcount size is 2 bytes */
64 585f8587 bellard
65 585f8587 bellard
typedef struct QCowHeader {
66 585f8587 bellard
    uint32_t magic;
67 585f8587 bellard
    uint32_t version;
68 585f8587 bellard
    uint64_t backing_file_offset;
69 585f8587 bellard
    uint32_t backing_file_size;
70 585f8587 bellard
    uint32_t cluster_bits;
71 585f8587 bellard
    uint64_t size; /* in bytes */
72 585f8587 bellard
    uint32_t crypt_method;
73 585f8587 bellard
    uint32_t l1_size; /* XXX: save number of clusters instead ? */
74 585f8587 bellard
    uint64_t l1_table_offset;
75 585f8587 bellard
    uint64_t refcount_table_offset;
76 585f8587 bellard
    uint32_t refcount_table_clusters;
77 585f8587 bellard
    uint32_t nb_snapshots;
78 585f8587 bellard
    uint64_t snapshots_offset;
79 585f8587 bellard
} QCowHeader;
80 585f8587 bellard
81 9b80ddf3 aliguori
82 9b80ddf3 aliguori
typedef struct {
83 9b80ddf3 aliguori
    uint32_t magic;
84 9b80ddf3 aliguori
    uint32_t len;
85 9b80ddf3 aliguori
} QCowExtension;
86 9b80ddf3 aliguori
#define  QCOW_EXT_MAGIC_END 0
87 f965509c aliguori
#define  QCOW_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
88 9b80ddf3 aliguori
89 9b80ddf3 aliguori
90 585f8587 bellard
typedef struct __attribute__((packed)) QCowSnapshotHeader {
91 585f8587 bellard
    /* header is 8 byte aligned */
92 585f8587 bellard
    uint64_t l1_table_offset;
93 585f8587 bellard
94 585f8587 bellard
    uint32_t l1_size;
95 585f8587 bellard
    uint16_t id_str_size;
96 585f8587 bellard
    uint16_t name_size;
97 585f8587 bellard
98 585f8587 bellard
    uint32_t date_sec;
99 585f8587 bellard
    uint32_t date_nsec;
100 585f8587 bellard
101 585f8587 bellard
    uint64_t vm_clock_nsec;
102 585f8587 bellard
103 585f8587 bellard
    uint32_t vm_state_size;
104 585f8587 bellard
    uint32_t extra_data_size; /* for extension */
105 585f8587 bellard
    /* extra data follows */
106 585f8587 bellard
    /* id_str follows */
107 585f8587 bellard
    /* name follows  */
108 585f8587 bellard
} QCowSnapshotHeader;
109 585f8587 bellard
110 585f8587 bellard
#define L2_CACHE_SIZE 16
111 585f8587 bellard
112 585f8587 bellard
typedef struct QCowSnapshot {
113 585f8587 bellard
    uint64_t l1_table_offset;
114 585f8587 bellard
    uint32_t l1_size;
115 585f8587 bellard
    char *id_str;
116 585f8587 bellard
    char *name;
117 585f8587 bellard
    uint32_t vm_state_size;
118 585f8587 bellard
    uint32_t date_sec;
119 585f8587 bellard
    uint32_t date_nsec;
120 585f8587 bellard
    uint64_t vm_clock_nsec;
121 585f8587 bellard
} QCowSnapshot;
122 585f8587 bellard
123 585f8587 bellard
typedef struct BDRVQcowState {
124 585f8587 bellard
    BlockDriverState *hd;
125 585f8587 bellard
    int cluster_bits;
126 585f8587 bellard
    int cluster_size;
127 585f8587 bellard
    int cluster_sectors;
128 585f8587 bellard
    int l2_bits;
129 585f8587 bellard
    int l2_size;
130 585f8587 bellard
    int l1_size;
131 585f8587 bellard
    int l1_vm_state_index;
132 585f8587 bellard
    int csize_shift;
133 585f8587 bellard
    int csize_mask;
134 585f8587 bellard
    uint64_t cluster_offset_mask;
135 585f8587 bellard
    uint64_t l1_table_offset;
136 585f8587 bellard
    uint64_t *l1_table;
137 585f8587 bellard
    uint64_t *l2_cache;
138 585f8587 bellard
    uint64_t l2_cache_offsets[L2_CACHE_SIZE];
139 585f8587 bellard
    uint32_t l2_cache_counts[L2_CACHE_SIZE];
140 585f8587 bellard
    uint8_t *cluster_cache;
141 585f8587 bellard
    uint8_t *cluster_data;
142 585f8587 bellard
    uint64_t cluster_cache_offset;
143 585f8587 bellard
144 585f8587 bellard
    uint64_t *refcount_table;
145 585f8587 bellard
    uint64_t refcount_table_offset;
146 585f8587 bellard
    uint32_t refcount_table_size;
147 585f8587 bellard
    uint64_t refcount_block_cache_offset;
148 585f8587 bellard
    uint16_t *refcount_block_cache;
149 585f8587 bellard
    int64_t free_cluster_index;
150 585f8587 bellard
    int64_t free_byte_offset;
151 585f8587 bellard
152 585f8587 bellard
    uint32_t crypt_method; /* current crypt method, 0 if no key yet */
153 585f8587 bellard
    uint32_t crypt_method_header;
154 585f8587 bellard
    AES_KEY aes_encrypt_key;
155 585f8587 bellard
    AES_KEY aes_decrypt_key;
156 585f8587 bellard
    uint64_t snapshots_offset;
157 585f8587 bellard
    int snapshots_size;
158 585f8587 bellard
    int nb_snapshots;
159 585f8587 bellard
    QCowSnapshot *snapshots;
160 585f8587 bellard
} BDRVQcowState;
161 585f8587 bellard
162 585f8587 bellard
static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset);
163 5fafdf24 ths
static int qcow_read(BlockDriverState *bs, int64_t sector_num,
164 585f8587 bellard
                     uint8_t *buf, int nb_sectors);
165 585f8587 bellard
static int qcow_read_snapshots(BlockDriverState *bs);
166 585f8587 bellard
static void qcow_free_snapshots(BlockDriverState *bs);
167 585f8587 bellard
static int refcount_init(BlockDriverState *bs);
168 585f8587 bellard
static void refcount_close(BlockDriverState *bs);
169 585f8587 bellard
static int get_refcount(BlockDriverState *bs, int64_t cluster_index);
170 5fafdf24 ths
static int update_cluster_refcount(BlockDriverState *bs,
171 585f8587 bellard
                                   int64_t cluster_index,
172 585f8587 bellard
                                   int addend);
173 5fafdf24 ths
static void update_refcount(BlockDriverState *bs,
174 5fafdf24 ths
                            int64_t offset, int64_t length,
175 585f8587 bellard
                            int addend);
176 585f8587 bellard
static int64_t alloc_clusters(BlockDriverState *bs, int64_t size);
177 585f8587 bellard
static int64_t alloc_bytes(BlockDriverState *bs, int size);
178 5fafdf24 ths
static void free_clusters(BlockDriverState *bs,
179 585f8587 bellard
                          int64_t offset, int64_t size);
180 e97fc193 aliguori
static int check_refcounts(BlockDriverState *bs);
181 585f8587 bellard
182 585f8587 bellard
static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
183 585f8587 bellard
{
184 585f8587 bellard
    const QCowHeader *cow_header = (const void *)buf;
185 3b46e624 ths
186 585f8587 bellard
    if (buf_size >= sizeof(QCowHeader) &&
187 585f8587 bellard
        be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
188 5fafdf24 ths
        be32_to_cpu(cow_header->version) == QCOW_VERSION)
189 585f8587 bellard
        return 100;
190 585f8587 bellard
    else
191 585f8587 bellard
        return 0;
192 585f8587 bellard
}
193 585f8587 bellard
194 9b80ddf3 aliguori
195 9b80ddf3 aliguori
/* 
196 9b80ddf3 aliguori
 * read qcow2 extension and fill bs
197 9b80ddf3 aliguori
 * start reading from start_offset
198 9b80ddf3 aliguori
 * finish reading upon magic of value 0 or when end_offset reached
199 9b80ddf3 aliguori
 * unknown magic is skipped (future extension this version knows nothing about)
200 9b80ddf3 aliguori
 * return 0 upon success, non-0 otherwise
201 9b80ddf3 aliguori
 */
202 9b80ddf3 aliguori
static int qcow_read_extensions(BlockDriverState *bs, uint64_t start_offset,
203 9b80ddf3 aliguori
                                uint64_t end_offset)
204 9b80ddf3 aliguori
{
205 9b80ddf3 aliguori
    BDRVQcowState *s = bs->opaque;
206 9b80ddf3 aliguori
    QCowExtension ext;
207 9b80ddf3 aliguori
    uint64_t offset;
208 9b80ddf3 aliguori
209 9b80ddf3 aliguori
#ifdef DEBUG_EXT
210 9b80ddf3 aliguori
    printf("qcow_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
211 9b80ddf3 aliguori
#endif
212 9b80ddf3 aliguori
    offset = start_offset;
213 9b80ddf3 aliguori
    while (offset < end_offset) {
214 9b80ddf3 aliguori
215 9b80ddf3 aliguori
#ifdef DEBUG_EXT
216 9b80ddf3 aliguori
        /* Sanity check */
217 9b80ddf3 aliguori
        if (offset > s->cluster_size)
218 9b80ddf3 aliguori
            printf("qcow_handle_extension: suspicious offset %lu\n", offset);
219 9b80ddf3 aliguori
220 9b80ddf3 aliguori
        printf("attemting to read extended header in offset %lu\n", offset);
221 9b80ddf3 aliguori
#endif
222 9b80ddf3 aliguori
223 9b80ddf3 aliguori
        if (bdrv_pread(s->hd, offset, &ext, sizeof(ext)) != sizeof(ext)) {
224 4c978075 aliguori
            fprintf(stderr, "qcow_handle_extension: ERROR: pread fail from offset %llu\n",
225 4c978075 aliguori
                    (unsigned long long)offset);
226 9b80ddf3 aliguori
            return 1;
227 9b80ddf3 aliguori
        }
228 9b80ddf3 aliguori
        be32_to_cpus(&ext.magic);
229 9b80ddf3 aliguori
        be32_to_cpus(&ext.len);
230 9b80ddf3 aliguori
        offset += sizeof(ext);
231 9b80ddf3 aliguori
#ifdef DEBUG_EXT
232 9b80ddf3 aliguori
        printf("ext.magic = 0x%x\n", ext.magic);
233 9b80ddf3 aliguori
#endif
234 9b80ddf3 aliguori
        switch (ext.magic) {
235 9b80ddf3 aliguori
        case QCOW_EXT_MAGIC_END:
236 9b80ddf3 aliguori
            return 0;
237 f965509c aliguori
238 f965509c aliguori
        case QCOW_EXT_MAGIC_BACKING_FORMAT:
239 f965509c aliguori
            if (ext.len >= sizeof(bs->backing_format)) {
240 f965509c aliguori
                fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
241 4c978075 aliguori
                        " (>=%zu)\n",
242 f965509c aliguori
                        ext.len, sizeof(bs->backing_format));
243 f965509c aliguori
                return 2;
244 f965509c aliguori
            }
245 f965509c aliguori
            if (bdrv_pread(s->hd, offset , bs->backing_format,
246 f965509c aliguori
                           ext.len) != ext.len)
247 f965509c aliguori
                return 3;
248 f965509c aliguori
            bs->backing_format[ext.len] = '\0';
249 f965509c aliguori
#ifdef DEBUG_EXT
250 f965509c aliguori
            printf("Qcow2: Got format extension %s\n", bs->backing_format);
251 f965509c aliguori
#endif
252 f965509c aliguori
            offset += ((ext.len + 7) & ~7);
253 f965509c aliguori
            break;
254 f965509c aliguori
255 9b80ddf3 aliguori
        default:
256 9b80ddf3 aliguori
            /* unknown magic -- just skip it */
257 9b80ddf3 aliguori
            offset += ((ext.len + 7) & ~7);
258 9b80ddf3 aliguori
            break;
259 9b80ddf3 aliguori
        }
260 9b80ddf3 aliguori
    }
261 9b80ddf3 aliguori
262 9b80ddf3 aliguori
    return 0;
263 9b80ddf3 aliguori
}
264 9b80ddf3 aliguori
265 9b80ddf3 aliguori
266 585f8587 bellard
static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
267 585f8587 bellard
{
268 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
269 585f8587 bellard
    int len, i, shift, ret;
270 585f8587 bellard
    QCowHeader header;
271 9b80ddf3 aliguori
    uint64_t ext_end;
272 585f8587 bellard
273 4dc822d7 aliguori
    /* Performance is terrible right now with cache=writethrough due mainly
274 4dc822d7 aliguori
     * to reference count updates.  If the user does not explicitly specify
275 4dc822d7 aliguori
     * a caching type, force to writeback caching.
276 4dc822d7 aliguori
     */
277 4dc822d7 aliguori
    if ((flags & BDRV_O_CACHE_DEF)) {
278 4dc822d7 aliguori
        flags |= BDRV_O_CACHE_WB;
279 4dc822d7 aliguori
        flags &= ~BDRV_O_CACHE_DEF;
280 4dc822d7 aliguori
    }
281 b5eff355 aurel32
    ret = bdrv_file_open(&s->hd, filename, flags);
282 585f8587 bellard
    if (ret < 0)
283 585f8587 bellard
        return ret;
284 585f8587 bellard
    if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
285 585f8587 bellard
        goto fail;
286 585f8587 bellard
    be32_to_cpus(&header.magic);
287 585f8587 bellard
    be32_to_cpus(&header.version);
288 585f8587 bellard
    be64_to_cpus(&header.backing_file_offset);
289 585f8587 bellard
    be32_to_cpus(&header.backing_file_size);
290 585f8587 bellard
    be64_to_cpus(&header.size);
291 585f8587 bellard
    be32_to_cpus(&header.cluster_bits);
292 585f8587 bellard
    be32_to_cpus(&header.crypt_method);
293 585f8587 bellard
    be64_to_cpus(&header.l1_table_offset);
294 585f8587 bellard
    be32_to_cpus(&header.l1_size);
295 585f8587 bellard
    be64_to_cpus(&header.refcount_table_offset);
296 585f8587 bellard
    be32_to_cpus(&header.refcount_table_clusters);
297 585f8587 bellard
    be64_to_cpus(&header.snapshots_offset);
298 585f8587 bellard
    be32_to_cpus(&header.nb_snapshots);
299 3b46e624 ths
300 585f8587 bellard
    if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
301 585f8587 bellard
        goto fail;
302 5fafdf24 ths
    if (header.size <= 1 ||
303 5fafdf24 ths
        header.cluster_bits < 9 ||
304 585f8587 bellard
        header.cluster_bits > 16)
305 585f8587 bellard
        goto fail;
306 585f8587 bellard
    if (header.crypt_method > QCOW_CRYPT_AES)
307 585f8587 bellard
        goto fail;
308 585f8587 bellard
    s->crypt_method_header = header.crypt_method;
309 585f8587 bellard
    if (s->crypt_method_header)
310 585f8587 bellard
        bs->encrypted = 1;
311 585f8587 bellard
    s->cluster_bits = header.cluster_bits;
312 585f8587 bellard
    s->cluster_size = 1 << s->cluster_bits;
313 585f8587 bellard
    s->cluster_sectors = 1 << (s->cluster_bits - 9);
314 585f8587 bellard
    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
315 585f8587 bellard
    s->l2_size = 1 << s->l2_bits;
316 585f8587 bellard
    bs->total_sectors = header.size / 512;
317 585f8587 bellard
    s->csize_shift = (62 - (s->cluster_bits - 8));
318 585f8587 bellard
    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
319 585f8587 bellard
    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
320 585f8587 bellard
    s->refcount_table_offset = header.refcount_table_offset;
321 5fafdf24 ths
    s->refcount_table_size =
322 585f8587 bellard
        header.refcount_table_clusters << (s->cluster_bits - 3);
323 585f8587 bellard
324 585f8587 bellard
    s->snapshots_offset = header.snapshots_offset;
325 585f8587 bellard
    s->nb_snapshots = header.nb_snapshots;
326 585f8587 bellard
327 585f8587 bellard
    /* read the level 1 table */
328 585f8587 bellard
    s->l1_size = header.l1_size;
329 585f8587 bellard
    shift = s->cluster_bits + s->l2_bits;
330 585f8587 bellard
    s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
331 585f8587 bellard
    /* the L1 table must contain at least enough entries to put
332 585f8587 bellard
       header.size bytes */
333 585f8587 bellard
    if (s->l1_size < s->l1_vm_state_index)
334 585f8587 bellard
        goto fail;
335 585f8587 bellard
    s->l1_table_offset = header.l1_table_offset;
336 585f8587 bellard
    s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
337 5fafdf24 ths
    if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
338 585f8587 bellard
        s->l1_size * sizeof(uint64_t))
339 585f8587 bellard
        goto fail;
340 585f8587 bellard
    for(i = 0;i < s->l1_size; i++) {
341 585f8587 bellard
        be64_to_cpus(&s->l1_table[i]);
342 585f8587 bellard
    }
343 585f8587 bellard
    /* alloc L2 cache */
344 585f8587 bellard
    s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
345 585f8587 bellard
    s->cluster_cache = qemu_malloc(s->cluster_size);
346 585f8587 bellard
    /* one more sector for decompressed data alignment */
347 095a9c58 aliguori
    s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
348 095a9c58 aliguori
                                  + 512);
349 585f8587 bellard
    s->cluster_cache_offset = -1;
350 3b46e624 ths
351 585f8587 bellard
    if (refcount_init(bs) < 0)
352 585f8587 bellard
        goto fail;
353 585f8587 bellard
354 9b80ddf3 aliguori
    /* read qcow2 extensions */
355 9b80ddf3 aliguori
    if (header.backing_file_offset)
356 9b80ddf3 aliguori
        ext_end = header.backing_file_offset;
357 9b80ddf3 aliguori
    else
358 9b80ddf3 aliguori
        ext_end = s->cluster_size;
359 9b80ddf3 aliguori
    if (qcow_read_extensions(bs, sizeof(header), ext_end))
360 9b80ddf3 aliguori
        goto fail;
361 9b80ddf3 aliguori
362 585f8587 bellard
    /* read the backing file name */
363 585f8587 bellard
    if (header.backing_file_offset != 0) {
364 585f8587 bellard
        len = header.backing_file_size;
365 585f8587 bellard
        if (len > 1023)
366 585f8587 bellard
            len = 1023;
367 585f8587 bellard
        if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
368 585f8587 bellard
            goto fail;
369 585f8587 bellard
        bs->backing_file[len] = '\0';
370 585f8587 bellard
    }
371 585f8587 bellard
    if (qcow_read_snapshots(bs) < 0)
372 585f8587 bellard
        goto fail;
373 585f8587 bellard
374 585f8587 bellard
#ifdef DEBUG_ALLOC
375 585f8587 bellard
    check_refcounts(bs);
376 585f8587 bellard
#endif
377 585f8587 bellard
    return 0;
378 585f8587 bellard
379 585f8587 bellard
 fail:
380 585f8587 bellard
    qcow_free_snapshots(bs);
381 585f8587 bellard
    refcount_close(bs);
382 585f8587 bellard
    qemu_free(s->l1_table);
383 585f8587 bellard
    qemu_free(s->l2_cache);
384 585f8587 bellard
    qemu_free(s->cluster_cache);
385 585f8587 bellard
    qemu_free(s->cluster_data);
386 585f8587 bellard
    bdrv_delete(s->hd);
387 585f8587 bellard
    return -1;
388 585f8587 bellard
}
389 585f8587 bellard
390 585f8587 bellard
static int qcow_set_key(BlockDriverState *bs, const char *key)
391 585f8587 bellard
{
392 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
393 585f8587 bellard
    uint8_t keybuf[16];
394 585f8587 bellard
    int len, i;
395 3b46e624 ths
396 585f8587 bellard
    memset(keybuf, 0, 16);
397 585f8587 bellard
    len = strlen(key);
398 585f8587 bellard
    if (len > 16)
399 585f8587 bellard
        len = 16;
400 585f8587 bellard
    /* XXX: we could compress the chars to 7 bits to increase
401 585f8587 bellard
       entropy */
402 585f8587 bellard
    for(i = 0;i < len;i++) {
403 585f8587 bellard
        keybuf[i] = key[i];
404 585f8587 bellard
    }
405 585f8587 bellard
    s->crypt_method = s->crypt_method_header;
406 585f8587 bellard
407 585f8587 bellard
    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
408 585f8587 bellard
        return -1;
409 585f8587 bellard
    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
410 585f8587 bellard
        return -1;
411 585f8587 bellard
#if 0
412 585f8587 bellard
    /* test */
413 585f8587 bellard
    {
414 585f8587 bellard
        uint8_t in[16];
415 585f8587 bellard
        uint8_t out[16];
416 585f8587 bellard
        uint8_t tmp[16];
417 585f8587 bellard
        for(i=0;i<16;i++)
418 585f8587 bellard
            in[i] = i;
419 585f8587 bellard
        AES_encrypt(in, tmp, &s->aes_encrypt_key);
420 585f8587 bellard
        AES_decrypt(tmp, out, &s->aes_decrypt_key);
421 585f8587 bellard
        for(i = 0; i < 16; i++)
422 585f8587 bellard
            printf(" %02x", tmp[i]);
423 585f8587 bellard
        printf("\n");
424 585f8587 bellard
        for(i = 0; i < 16; i++)
425 585f8587 bellard
            printf(" %02x", out[i]);
426 585f8587 bellard
        printf("\n");
427 585f8587 bellard
    }
428 585f8587 bellard
#endif
429 585f8587 bellard
    return 0;
430 585f8587 bellard
}
431 585f8587 bellard
432 585f8587 bellard
/* The crypt function is compatible with the linux cryptoloop
433 585f8587 bellard
   algorithm for < 4 GB images. NOTE: out_buf == in_buf is
434 585f8587 bellard
   supported */
435 585f8587 bellard
static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
436 585f8587 bellard
                            uint8_t *out_buf, const uint8_t *in_buf,
437 585f8587 bellard
                            int nb_sectors, int enc,
438 585f8587 bellard
                            const AES_KEY *key)
439 585f8587 bellard
{
440 585f8587 bellard
    union {
441 585f8587 bellard
        uint64_t ll[2];
442 585f8587 bellard
        uint8_t b[16];
443 585f8587 bellard
    } ivec;
444 585f8587 bellard
    int i;
445 585f8587 bellard
446 585f8587 bellard
    for(i = 0; i < nb_sectors; i++) {
447 585f8587 bellard
        ivec.ll[0] = cpu_to_le64(sector_num);
448 585f8587 bellard
        ivec.ll[1] = 0;
449 5fafdf24 ths
        AES_cbc_encrypt(in_buf, out_buf, 512, key,
450 585f8587 bellard
                        ivec.b, enc);
451 585f8587 bellard
        sector_num++;
452 585f8587 bellard
        in_buf += 512;
453 585f8587 bellard
        out_buf += 512;
454 585f8587 bellard
    }
455 585f8587 bellard
}
456 585f8587 bellard
457 585f8587 bellard
static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,
458 585f8587 bellard
                        uint64_t cluster_offset, int n_start, int n_end)
459 585f8587 bellard
{
460 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
461 585f8587 bellard
    int n, ret;
462 585f8587 bellard
463 585f8587 bellard
    n = n_end - n_start;
464 585f8587 bellard
    if (n <= 0)
465 585f8587 bellard
        return 0;
466 585f8587 bellard
    ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);
467 585f8587 bellard
    if (ret < 0)
468 585f8587 bellard
        return ret;
469 585f8587 bellard
    if (s->crypt_method) {
470 5fafdf24 ths
        encrypt_sectors(s, start_sect + n_start,
471 5fafdf24 ths
                        s->cluster_data,
472 585f8587 bellard
                        s->cluster_data, n, 1,
473 585f8587 bellard
                        &s->aes_encrypt_key);
474 585f8587 bellard
    }
475 5fafdf24 ths
    ret = bdrv_write(s->hd, (cluster_offset >> 9) + n_start,
476 585f8587 bellard
                     s->cluster_data, n);
477 585f8587 bellard
    if (ret < 0)
478 585f8587 bellard
        return ret;
479 585f8587 bellard
    return 0;
480 585f8587 bellard
}
481 585f8587 bellard
482 585f8587 bellard
static void l2_cache_reset(BlockDriverState *bs)
483 585f8587 bellard
{
484 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
485 585f8587 bellard
486 585f8587 bellard
    memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
487 585f8587 bellard
    memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
488 585f8587 bellard
    memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
489 585f8587 bellard
}
490 585f8587 bellard
491 585f8587 bellard
static inline int l2_cache_new_entry(BlockDriverState *bs)
492 585f8587 bellard
{
493 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
494 585f8587 bellard
    uint32_t min_count;
495 585f8587 bellard
    int min_index, i;
496 585f8587 bellard
497 585f8587 bellard
    /* find a new entry in the least used one */
498 585f8587 bellard
    min_index = 0;
499 585f8587 bellard
    min_count = 0xffffffff;
500 585f8587 bellard
    for(i = 0; i < L2_CACHE_SIZE; i++) {
501 585f8587 bellard
        if (s->l2_cache_counts[i] < min_count) {
502 585f8587 bellard
            min_count = s->l2_cache_counts[i];
503 585f8587 bellard
            min_index = i;
504 585f8587 bellard
        }
505 585f8587 bellard
    }
506 585f8587 bellard
    return min_index;
507 585f8587 bellard
}
508 585f8587 bellard
509 585f8587 bellard
static int64_t align_offset(int64_t offset, int n)
510 585f8587 bellard
{
511 585f8587 bellard
    offset = (offset + n - 1) & ~(n - 1);
512 585f8587 bellard
    return offset;
513 585f8587 bellard
}
514 585f8587 bellard
515 585f8587 bellard
static int grow_l1_table(BlockDriverState *bs, int min_size)
516 585f8587 bellard
{
517 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
518 585f8587 bellard
    int new_l1_size, new_l1_size2, ret, i;
519 585f8587 bellard
    uint64_t *new_l1_table;
520 585f8587 bellard
    uint64_t new_l1_table_offset;
521 643e5399 aliguori
    uint8_t data[12];
522 585f8587 bellard
523 585f8587 bellard
    new_l1_size = s->l1_size;
524 585f8587 bellard
    if (min_size <= new_l1_size)
525 585f8587 bellard
        return 0;
526 585f8587 bellard
    while (min_size > new_l1_size) {
527 585f8587 bellard
        new_l1_size = (new_l1_size * 3 + 1) / 2;
528 585f8587 bellard
    }
529 585f8587 bellard
#ifdef DEBUG_ALLOC2
530 585f8587 bellard
    printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
531 585f8587 bellard
#endif
532 585f8587 bellard
533 585f8587 bellard
    new_l1_size2 = sizeof(uint64_t) * new_l1_size;
534 585f8587 bellard
    new_l1_table = qemu_mallocz(new_l1_size2);
535 585f8587 bellard
    memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
536 585f8587 bellard
537 585f8587 bellard
    /* write new table (align to cluster) */
538 585f8587 bellard
    new_l1_table_offset = alloc_clusters(bs, new_l1_size2);
539 3b46e624 ths
540 585f8587 bellard
    for(i = 0; i < s->l1_size; i++)
541 585f8587 bellard
        new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
542 585f8587 bellard
    ret = bdrv_pwrite(s->hd, new_l1_table_offset, new_l1_table, new_l1_size2);
543 585f8587 bellard
    if (ret != new_l1_size2)
544 585f8587 bellard
        goto fail;
545 585f8587 bellard
    for(i = 0; i < s->l1_size; i++)
546 585f8587 bellard
        new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
547 3b46e624 ths
548 585f8587 bellard
    /* set new table */
549 643e5399 aliguori
    cpu_to_be32w((uint32_t*)data, new_l1_size);
550 643e5399 aliguori
    cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);
551 643e5399 aliguori
    if (bdrv_pwrite(s->hd, offsetof(QCowHeader, l1_size), data,
552 643e5399 aliguori
                sizeof(data)) != sizeof(data))
553 585f8587 bellard
        goto fail;
554 585f8587 bellard
    qemu_free(s->l1_table);
555 585f8587 bellard
    free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
556 585f8587 bellard
    s->l1_table_offset = new_l1_table_offset;
557 585f8587 bellard
    s->l1_table = new_l1_table;
558 585f8587 bellard
    s->l1_size = new_l1_size;
559 585f8587 bellard
    return 0;
560 585f8587 bellard
 fail:
561 585f8587 bellard
    qemu_free(s->l1_table);
562 585f8587 bellard
    return -EIO;
563 585f8587 bellard
}
564 585f8587 bellard
565 108534b9 aliguori
/*
566 108534b9 aliguori
 * seek_l2_table
567 585f8587 bellard
 *
568 108534b9 aliguori
 * seek l2_offset in the l2_cache table
569 108534b9 aliguori
 * if not found, return NULL,
570 108534b9 aliguori
 * if found,
571 108534b9 aliguori
 *   increments the l2 cache hit count of the entry,
572 108534b9 aliguori
 *   if counter overflow, divide by two all counters
573 108534b9 aliguori
 *   return the pointer to the l2 cache entry
574 585f8587 bellard
 *
575 108534b9 aliguori
 */
576 108534b9 aliguori
577 108534b9 aliguori
static uint64_t *seek_l2_table(BDRVQcowState *s, uint64_t l2_offset)
578 108534b9 aliguori
{
579 108534b9 aliguori
    int i, j;
580 108534b9 aliguori
581 108534b9 aliguori
    for(i = 0; i < L2_CACHE_SIZE; i++) {
582 108534b9 aliguori
        if (l2_offset == s->l2_cache_offsets[i]) {
583 108534b9 aliguori
            /* increment the hit count */
584 108534b9 aliguori
            if (++s->l2_cache_counts[i] == 0xffffffff) {
585 108534b9 aliguori
                for(j = 0; j < L2_CACHE_SIZE; j++) {
586 108534b9 aliguori
                    s->l2_cache_counts[j] >>= 1;
587 108534b9 aliguori
                }
588 108534b9 aliguori
            }
589 108534b9 aliguori
            return s->l2_cache + (i << s->l2_bits);
590 108534b9 aliguori
        }
591 108534b9 aliguori
    }
592 108534b9 aliguori
    return NULL;
593 108534b9 aliguori
}
594 108534b9 aliguori
595 108534b9 aliguori
/*
596 108534b9 aliguori
 * l2_load
597 108534b9 aliguori
 *
598 108534b9 aliguori
 * Loads a L2 table into memory. If the table is in the cache, the cache
599 108534b9 aliguori
 * is used; otherwise the L2 table is loaded from the image file.
600 108534b9 aliguori
 *
601 108534b9 aliguori
 * Returns a pointer to the L2 table on success, or NULL if the read from
602 108534b9 aliguori
 * the image file failed.
603 108534b9 aliguori
 */
604 108534b9 aliguori
605 108534b9 aliguori
static uint64_t *l2_load(BlockDriverState *bs, uint64_t l2_offset)
606 108534b9 aliguori
{
607 108534b9 aliguori
    BDRVQcowState *s = bs->opaque;
608 108534b9 aliguori
    int min_index;
609 108534b9 aliguori
    uint64_t *l2_table;
610 108534b9 aliguori
611 108534b9 aliguori
    /* seek if the table for the given offset is in the cache */
612 108534b9 aliguori
613 108534b9 aliguori
    l2_table = seek_l2_table(s, l2_offset);
614 108534b9 aliguori
    if (l2_table != NULL)
615 108534b9 aliguori
        return l2_table;
616 108534b9 aliguori
617 108534b9 aliguori
    /* not found: load a new entry in the least used one */
618 108534b9 aliguori
619 108534b9 aliguori
    min_index = l2_cache_new_entry(bs);
620 108534b9 aliguori
    l2_table = s->l2_cache + (min_index << s->l2_bits);
621 108534b9 aliguori
    if (bdrv_pread(s->hd, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
622 108534b9 aliguori
        s->l2_size * sizeof(uint64_t))
623 108534b9 aliguori
        return NULL;
624 108534b9 aliguori
    s->l2_cache_offsets[min_index] = l2_offset;
625 108534b9 aliguori
    s->l2_cache_counts[min_index] = 1;
626 108534b9 aliguori
627 108534b9 aliguori
    return l2_table;
628 108534b9 aliguori
}
629 108534b9 aliguori
630 108534b9 aliguori
/*
631 108534b9 aliguori
 * l2_allocate
632 585f8587 bellard
 *
633 108534b9 aliguori
 * Allocate a new l2 entry in the file. If l1_index points to an already
634 108534b9 aliguori
 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
635 108534b9 aliguori
 * table) copy the contents of the old L2 table into the newly allocated one.
636 108534b9 aliguori
 * Otherwise the new table is initialized with zeros.
637 585f8587 bellard
 *
638 585f8587 bellard
 */
639 108534b9 aliguori
640 108534b9 aliguori
static uint64_t *l2_allocate(BlockDriverState *bs, int l1_index)
641 108534b9 aliguori
{
642 108534b9 aliguori
    BDRVQcowState *s = bs->opaque;
643 108534b9 aliguori
    int min_index;
644 108534b9 aliguori
    uint64_t old_l2_offset, tmp;
645 108534b9 aliguori
    uint64_t *l2_table, l2_offset;
646 108534b9 aliguori
647 108534b9 aliguori
    old_l2_offset = s->l1_table[l1_index];
648 108534b9 aliguori
649 108534b9 aliguori
    /* allocate a new l2 entry */
650 108534b9 aliguori
651 108534b9 aliguori
    l2_offset = alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
652 108534b9 aliguori
653 108534b9 aliguori
    /* update the L1 entry */
654 108534b9 aliguori
655 108534b9 aliguori
    s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
656 108534b9 aliguori
657 108534b9 aliguori
    tmp = cpu_to_be64(l2_offset | QCOW_OFLAG_COPIED);
658 108534b9 aliguori
    if (bdrv_pwrite(s->hd, s->l1_table_offset + l1_index * sizeof(tmp),
659 108534b9 aliguori
                    &tmp, sizeof(tmp)) != sizeof(tmp))
660 108534b9 aliguori
        return NULL;
661 108534b9 aliguori
662 108534b9 aliguori
    /* allocate a new entry in the l2 cache */
663 108534b9 aliguori
664 108534b9 aliguori
    min_index = l2_cache_new_entry(bs);
665 108534b9 aliguori
    l2_table = s->l2_cache + (min_index << s->l2_bits);
666 108534b9 aliguori
667 108534b9 aliguori
    if (old_l2_offset == 0) {
668 108534b9 aliguori
        /* if there was no old l2 table, clear the new table */
669 108534b9 aliguori
        memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
670 108534b9 aliguori
    } else {
671 108534b9 aliguori
        /* if there was an old l2 table, read it from the disk */
672 108534b9 aliguori
        if (bdrv_pread(s->hd, old_l2_offset,
673 108534b9 aliguori
                       l2_table, s->l2_size * sizeof(uint64_t)) !=
674 108534b9 aliguori
            s->l2_size * sizeof(uint64_t))
675 108534b9 aliguori
            return NULL;
676 108534b9 aliguori
    }
677 108534b9 aliguori
    /* write the l2 table to the file */
678 108534b9 aliguori
    if (bdrv_pwrite(s->hd, l2_offset,
679 108534b9 aliguori
                    l2_table, s->l2_size * sizeof(uint64_t)) !=
680 108534b9 aliguori
        s->l2_size * sizeof(uint64_t))
681 108534b9 aliguori
        return NULL;
682 108534b9 aliguori
683 108534b9 aliguori
    /* update the l2 cache entry */
684 108534b9 aliguori
685 108534b9 aliguori
    s->l2_cache_offsets[min_index] = l2_offset;
686 108534b9 aliguori
    s->l2_cache_counts[min_index] = 1;
687 108534b9 aliguori
688 108534b9 aliguori
    return l2_table;
689 108534b9 aliguori
}
690 108534b9 aliguori
691 6db6c638 aliguori
static int size_to_clusters(BDRVQcowState *s, int64_t size)
692 6db6c638 aliguori
{
693 6db6c638 aliguori
    return (size + (s->cluster_size - 1)) >> s->cluster_bits;
694 6db6c638 aliguori
}
695 6db6c638 aliguori
696 6db6c638 aliguori
static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
697 ff4b91c2 aliguori
        uint64_t *l2_table, uint64_t start, uint64_t mask)
698 6db6c638 aliguori
{
699 6db6c638 aliguori
    int i;
700 6db6c638 aliguori
    uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask;
701 6db6c638 aliguori
702 ab5ccbd6 aliguori
    if (!offset)
703 ab5ccbd6 aliguori
        return 0;
704 ab5ccbd6 aliguori
705 ff4b91c2 aliguori
    for (i = start; i < start + nb_clusters; i++)
706 6db6c638 aliguori
        if (offset + i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask))
707 6db6c638 aliguori
            break;
708 6db6c638 aliguori
709 ff4b91c2 aliguori
        return (i - start);
710 6db6c638 aliguori
}
711 6db6c638 aliguori
712 6db6c638 aliguori
static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
713 6db6c638 aliguori
{
714 6db6c638 aliguori
    int i = 0;
715 6db6c638 aliguori
716 6db6c638 aliguori
    while(nb_clusters-- && l2_table[i] == 0)
717 6db6c638 aliguori
        i++;
718 6db6c638 aliguori
719 6db6c638 aliguori
    return i;
720 6db6c638 aliguori
}
721 6db6c638 aliguori
722 05203524 aliguori
/*
723 05203524 aliguori
 * get_cluster_offset
724 05203524 aliguori
 *
725 05203524 aliguori
 * For a given offset of the disk image, return cluster offset in
726 05203524 aliguori
 * qcow2 file.
727 05203524 aliguori
 *
728 095a9c58 aliguori
 * on entry, *num is the number of contiguous clusters we'd like to
729 095a9c58 aliguori
 * access following offset.
730 095a9c58 aliguori
 *
731 095a9c58 aliguori
 * on exit, *num is the number of contiguous clusters we can read.
732 095a9c58 aliguori
 *
733 05203524 aliguori
 * Return 1, if the offset is found
734 05203524 aliguori
 * Return 0, otherwise.
735 05203524 aliguori
 *
736 05203524 aliguori
 */
737 05203524 aliguori
738 095a9c58 aliguori
static uint64_t get_cluster_offset(BlockDriverState *bs,
739 095a9c58 aliguori
                                   uint64_t offset, int *num)
740 05203524 aliguori
{
741 05203524 aliguori
    BDRVQcowState *s = bs->opaque;
742 05203524 aliguori
    int l1_index, l2_index;
743 6db6c638 aliguori
    uint64_t l2_offset, *l2_table, cluster_offset;
744 6db6c638 aliguori
    int l1_bits, c;
745 6db6c638 aliguori
    int index_in_cluster, nb_available, nb_needed, nb_clusters;
746 095a9c58 aliguori
747 095a9c58 aliguori
    index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
748 095a9c58 aliguori
    nb_needed = *num + index_in_cluster;
749 095a9c58 aliguori
750 095a9c58 aliguori
    l1_bits = s->l2_bits + s->cluster_bits;
751 095a9c58 aliguori
752 095a9c58 aliguori
    /* compute how many bytes there are between the offset and
753 6db6c638 aliguori
     * the end of the l1 entry
754 095a9c58 aliguori
     */
755 095a9c58 aliguori
756 095a9c58 aliguori
    nb_available = (1 << l1_bits) - (offset & ((1 << l1_bits) - 1));
757 095a9c58 aliguori
758 095a9c58 aliguori
    /* compute the number of available sectors */
759 095a9c58 aliguori
760 095a9c58 aliguori
    nb_available = (nb_available >> 9) + index_in_cluster;
761 095a9c58 aliguori
762 f8de1660 aliguori
    if (nb_needed > nb_available) {
763 f8de1660 aliguori
        nb_needed = nb_available;
764 f8de1660 aliguori
    }
765 f8de1660 aliguori
766 095a9c58 aliguori
    cluster_offset = 0;
767 05203524 aliguori
768 05203524 aliguori
    /* seek the the l2 offset in the l1 table */
769 05203524 aliguori
770 095a9c58 aliguori
    l1_index = offset >> l1_bits;
771 05203524 aliguori
    if (l1_index >= s->l1_size)
772 095a9c58 aliguori
        goto out;
773 05203524 aliguori
774 05203524 aliguori
    l2_offset = s->l1_table[l1_index];
775 05203524 aliguori
776 05203524 aliguori
    /* seek the l2 table of the given l2 offset */
777 05203524 aliguori
778 05203524 aliguori
    if (!l2_offset)
779 095a9c58 aliguori
        goto out;
780 05203524 aliguori
781 05203524 aliguori
    /* load the l2 table in memory */
782 05203524 aliguori
783 05203524 aliguori
    l2_offset &= ~QCOW_OFLAG_COPIED;
784 05203524 aliguori
    l2_table = l2_load(bs, l2_offset);
785 05203524 aliguori
    if (l2_table == NULL)
786 768706a5 aliguori
        return 0;
787 05203524 aliguori
788 05203524 aliguori
    /* find the cluster offset for the given disk offset */
789 05203524 aliguori
790 05203524 aliguori
    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
791 05203524 aliguori
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
792 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, nb_needed << 9);
793 095a9c58 aliguori
794 095a9c58 aliguori
    if (!cluster_offset) {
795 6db6c638 aliguori
        /* how many empty clusters ? */
796 6db6c638 aliguori
        c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
797 095a9c58 aliguori
    } else {
798 6db6c638 aliguori
        /* how many allocated clusters ? */
799 6db6c638 aliguori
        c = count_contiguous_clusters(nb_clusters, s->cluster_size,
800 ff4b91c2 aliguori
                &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);
801 6db6c638 aliguori
    }
802 095a9c58 aliguori
803 6db6c638 aliguori
   nb_available = (c * s->cluster_sectors);
804 095a9c58 aliguori
out:
805 095a9c58 aliguori
    if (nb_available > nb_needed)
806 095a9c58 aliguori
        nb_available = nb_needed;
807 095a9c58 aliguori
808 095a9c58 aliguori
    *num = nb_available - index_in_cluster;
809 095a9c58 aliguori
810 6db6c638 aliguori
    return cluster_offset & ~QCOW_OFLAG_COPIED;
811 05203524 aliguori
}
812 05203524 aliguori
813 05203524 aliguori
/*
814 52d893ec aliguori
 * free_any_clusters
815 05203524 aliguori
 *
816 52d893ec aliguori
 * free clusters according to its type: compressed or not
817 05203524 aliguori
 *
818 52d893ec aliguori
 */
819 52d893ec aliguori
820 52d893ec aliguori
static void free_any_clusters(BlockDriverState *bs,
821 095a9c58 aliguori
                              uint64_t cluster_offset, int nb_clusters)
822 52d893ec aliguori
{
823 52d893ec aliguori
    BDRVQcowState *s = bs->opaque;
824 52d893ec aliguori
825 52d893ec aliguori
    /* free the cluster */
826 52d893ec aliguori
827 52d893ec aliguori
    if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
828 52d893ec aliguori
        int nb_csectors;
829 52d893ec aliguori
        nb_csectors = ((cluster_offset >> s->csize_shift) &
830 52d893ec aliguori
                       s->csize_mask) + 1;
831 52d893ec aliguori
        free_clusters(bs, (cluster_offset & s->cluster_offset_mask) & ~511,
832 52d893ec aliguori
                      nb_csectors * 512);
833 52d893ec aliguori
        return;
834 52d893ec aliguori
    }
835 52d893ec aliguori
836 095a9c58 aliguori
    free_clusters(bs, cluster_offset, nb_clusters << s->cluster_bits);
837 095a9c58 aliguori
838 095a9c58 aliguori
    return;
839 52d893ec aliguori
}
840 52d893ec aliguori
841 52d893ec aliguori
/*
842 52d893ec aliguori
 * get_cluster_table
843 05203524 aliguori
 *
844 52d893ec aliguori
 * for a given disk offset, load (and allocate if needed)
845 52d893ec aliguori
 * the l2 table.
846 52d893ec aliguori
 *
847 52d893ec aliguori
 * the l2 table offset in the qcow2 file and the cluster index
848 52d893ec aliguori
 * in the l2 table are given to the caller.
849 05203524 aliguori
 *
850 05203524 aliguori
 */
851 05203524 aliguori
852 52d893ec aliguori
static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
853 52d893ec aliguori
                             uint64_t **new_l2_table,
854 52d893ec aliguori
                             uint64_t *new_l2_offset,
855 52d893ec aliguori
                             int *new_l2_index)
856 585f8587 bellard
{
857 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
858 108534b9 aliguori
    int l1_index, l2_index, ret;
859 52d893ec aliguori
    uint64_t l2_offset, *l2_table;
860 108534b9 aliguori
861 108534b9 aliguori
    /* seek the the l2 offset in the l1 table */
862 3b46e624 ths
863 585f8587 bellard
    l1_index = offset >> (s->l2_bits + s->cluster_bits);
864 585f8587 bellard
    if (l1_index >= s->l1_size) {
865 108534b9 aliguori
        ret = grow_l1_table(bs, l1_index + 1);
866 108534b9 aliguori
        if (ret < 0)
867 585f8587 bellard
            return 0;
868 585f8587 bellard
    }
869 585f8587 bellard
    l2_offset = s->l1_table[l1_index];
870 108534b9 aliguori
871 108534b9 aliguori
    /* seek the l2 table of the given l2 offset */
872 108534b9 aliguori
873 05203524 aliguori
    if (l2_offset & QCOW_OFLAG_COPIED) {
874 05203524 aliguori
        /* load the l2 table in memory */
875 05203524 aliguori
        l2_offset &= ~QCOW_OFLAG_COPIED;
876 05203524 aliguori
        l2_table = l2_load(bs, l2_offset);
877 05203524 aliguori
        if (l2_table == NULL)
878 585f8587 bellard
            return 0;
879 05203524 aliguori
    } else {
880 05203524 aliguori
        if (l2_offset)
881 05203524 aliguori
            free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
882 108534b9 aliguori
        l2_table = l2_allocate(bs, l1_index);
883 108534b9 aliguori
        if (l2_table == NULL)
884 585f8587 bellard
            return 0;
885 108534b9 aliguori
        l2_offset = s->l1_table[l1_index] & ~QCOW_OFLAG_COPIED;
886 585f8587 bellard
    }
887 108534b9 aliguori
888 108534b9 aliguori
    /* find the cluster offset for the given disk offset */
889 108534b9 aliguori
890 585f8587 bellard
    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
891 05203524 aliguori
892 52d893ec aliguori
    *new_l2_table = l2_table;
893 52d893ec aliguori
    *new_l2_offset = l2_offset;
894 52d893ec aliguori
    *new_l2_index = l2_index;
895 52d893ec aliguori
896 52d893ec aliguori
    return 1;
897 52d893ec aliguori
}
898 52d893ec aliguori
899 52d893ec aliguori
/*
900 52d893ec aliguori
 * alloc_compressed_cluster_offset
901 52d893ec aliguori
 *
902 52d893ec aliguori
 * For a given offset of the disk image, return cluster offset in
903 52d893ec aliguori
 * qcow2 file.
904 52d893ec aliguori
 *
905 52d893ec aliguori
 * If the offset is not found, allocate a new compressed cluster.
906 52d893ec aliguori
 *
907 52d893ec aliguori
 * Return the cluster offset if successful,
908 52d893ec aliguori
 * Return 0, otherwise.
909 52d893ec aliguori
 *
910 52d893ec aliguori
 */
911 52d893ec aliguori
912 52d893ec aliguori
static uint64_t alloc_compressed_cluster_offset(BlockDriverState *bs,
913 52d893ec aliguori
                                                uint64_t offset,
914 52d893ec aliguori
                                                int compressed_size)
915 52d893ec aliguori
{
916 52d893ec aliguori
    BDRVQcowState *s = bs->opaque;
917 52d893ec aliguori
    int l2_index, ret;
918 52d893ec aliguori
    uint64_t l2_offset, *l2_table, cluster_offset;
919 52d893ec aliguori
    int nb_csectors;
920 52d893ec aliguori
921 52d893ec aliguori
    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
922 52d893ec aliguori
    if (ret == 0)
923 52d893ec aliguori
        return 0;
924 52d893ec aliguori
925 52d893ec aliguori
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
926 05203524 aliguori
    if (cluster_offset & QCOW_OFLAG_COPIED)
927 05203524 aliguori
        return cluster_offset & ~QCOW_OFLAG_COPIED;
928 05203524 aliguori
929 095a9c58 aliguori
    if (cluster_offset)
930 095a9c58 aliguori
        free_any_clusters(bs, cluster_offset, 1);
931 108534b9 aliguori
932 52d893ec aliguori
    cluster_offset = alloc_bytes(bs, compressed_size);
933 52d893ec aliguori
    nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
934 52d893ec aliguori
                  (cluster_offset >> 9);
935 05203524 aliguori
936 52d893ec aliguori
    cluster_offset |= QCOW_OFLAG_COMPRESSED |
937 52d893ec aliguori
                      ((uint64_t)nb_csectors << s->csize_shift);
938 05203524 aliguori
939 52d893ec aliguori
    /* update L2 table */
940 05203524 aliguori
941 52d893ec aliguori
    /* compressed clusters never have the copied flag */
942 05203524 aliguori
943 52d893ec aliguori
    l2_table[l2_index] = cpu_to_be64(cluster_offset);
944 52d893ec aliguori
    if (bdrv_pwrite(s->hd,
945 52d893ec aliguori
                    l2_offset + l2_index * sizeof(uint64_t),
946 52d893ec aliguori
                    l2_table + l2_index,
947 52d893ec aliguori
                    sizeof(uint64_t)) != sizeof(uint64_t))
948 52d893ec aliguori
        return 0;
949 05203524 aliguori
950 52d893ec aliguori
    return cluster_offset;
951 52d893ec aliguori
}
952 05203524 aliguori
953 e976c6a1 aliguori
typedef struct QCowL2Meta
954 e976c6a1 aliguori
{
955 e976c6a1 aliguori
    uint64_t offset;
956 e976c6a1 aliguori
    int n_start;
957 e976c6a1 aliguori
    int nb_available;
958 e976c6a1 aliguori
    int nb_clusters;
959 e976c6a1 aliguori
} QCowL2Meta;
960 e976c6a1 aliguori
961 e976c6a1 aliguori
static int alloc_cluster_link_l2(BlockDriverState *bs, uint64_t cluster_offset,
962 e976c6a1 aliguori
        QCowL2Meta *m)
963 e976c6a1 aliguori
{
964 e976c6a1 aliguori
    BDRVQcowState *s = bs->opaque;
965 e976c6a1 aliguori
    int i, j = 0, l2_index, ret;
966 e976c6a1 aliguori
    uint64_t *old_cluster, start_sect, l2_offset, *l2_table;
967 e976c6a1 aliguori
968 e976c6a1 aliguori
    if (m->nb_clusters == 0)
969 e976c6a1 aliguori
        return 0;
970 e976c6a1 aliguori
971 3ec88e80 aliguori
    old_cluster = qemu_malloc(m->nb_clusters * sizeof(uint64_t));
972 e976c6a1 aliguori
973 e976c6a1 aliguori
    /* copy content of unmodified sectors */
974 e976c6a1 aliguori
    start_sect = (m->offset & ~(s->cluster_size - 1)) >> 9;
975 e976c6a1 aliguori
    if (m->n_start) {
976 e976c6a1 aliguori
        ret = copy_sectors(bs, start_sect, cluster_offset, 0, m->n_start);
977 e976c6a1 aliguori
        if (ret < 0)
978 e976c6a1 aliguori
            goto err;
979 e976c6a1 aliguori
    }
980 e976c6a1 aliguori
981 e976c6a1 aliguori
    if (m->nb_available & (s->cluster_sectors - 1)) {
982 e976c6a1 aliguori
        uint64_t end = m->nb_available & ~(uint64_t)(s->cluster_sectors - 1);
983 e976c6a1 aliguori
        ret = copy_sectors(bs, start_sect + end, cluster_offset + (end << 9),
984 e976c6a1 aliguori
                m->nb_available - end, s->cluster_sectors);
985 e976c6a1 aliguori
        if (ret < 0)
986 e976c6a1 aliguori
            goto err;
987 e976c6a1 aliguori
    }
988 e976c6a1 aliguori
989 e976c6a1 aliguori
    ret = -EIO;
990 e976c6a1 aliguori
    /* update L2 table */
991 e976c6a1 aliguori
    if (!get_cluster_table(bs, m->offset, &l2_table, &l2_offset, &l2_index))
992 e976c6a1 aliguori
        goto err;
993 e976c6a1 aliguori
994 e976c6a1 aliguori
    for (i = 0; i < m->nb_clusters; i++) {
995 e976c6a1 aliguori
        if(l2_table[l2_index + i] != 0)
996 e976c6a1 aliguori
            old_cluster[j++] = l2_table[l2_index + i];
997 e976c6a1 aliguori
998 e976c6a1 aliguori
        l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
999 e976c6a1 aliguori
                    (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
1000 e976c6a1 aliguori
     }
1001 e976c6a1 aliguori
1002 e976c6a1 aliguori
    if (bdrv_pwrite(s->hd, l2_offset + l2_index * sizeof(uint64_t),
1003 e976c6a1 aliguori
                l2_table + l2_index, m->nb_clusters * sizeof(uint64_t)) !=
1004 e976c6a1 aliguori
            m->nb_clusters * sizeof(uint64_t))
1005 e976c6a1 aliguori
        goto err;
1006 e976c6a1 aliguori
1007 e976c6a1 aliguori
    for (i = 0; i < j; i++)
1008 641636d1 aliguori
        free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1);
1009 e976c6a1 aliguori
1010 e976c6a1 aliguori
    ret = 0;
1011 e976c6a1 aliguori
err:
1012 e976c6a1 aliguori
    qemu_free(old_cluster);
1013 e976c6a1 aliguori
    return ret;
1014 e976c6a1 aliguori
 }
1015 e976c6a1 aliguori
1016 52d893ec aliguori
/*
1017 52d893ec aliguori
 * alloc_cluster_offset
1018 52d893ec aliguori
 *
1019 52d893ec aliguori
 * For a given offset of the disk image, return cluster offset in
1020 52d893ec aliguori
 * qcow2 file.
1021 52d893ec aliguori
 *
1022 52d893ec aliguori
 * If the offset is not found, allocate a new cluster.
1023 52d893ec aliguori
 *
1024 52d893ec aliguori
 * Return the cluster offset if successful,
1025 52d893ec aliguori
 * Return 0, otherwise.
1026 52d893ec aliguori
 *
1027 52d893ec aliguori
 */
1028 52d893ec aliguori
1029 52d893ec aliguori
static uint64_t alloc_cluster_offset(BlockDriverState *bs,
1030 52d893ec aliguori
                                     uint64_t offset,
1031 095a9c58 aliguori
                                     int n_start, int n_end,
1032 e976c6a1 aliguori
                                     int *num, QCowL2Meta *m)
1033 52d893ec aliguori
{
1034 52d893ec aliguori
    BDRVQcowState *s = bs->opaque;
1035 52d893ec aliguori
    int l2_index, ret;
1036 52d893ec aliguori
    uint64_t l2_offset, *l2_table, cluster_offset;
1037 e976c6a1 aliguori
    int nb_clusters, i = 0;
1038 52d893ec aliguori
1039 52d893ec aliguori
    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
1040 52d893ec aliguori
    if (ret == 0)
1041 52d893ec aliguori
        return 0;
1042 52d893ec aliguori
1043 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, n_end << 9);
1044 6db6c638 aliguori
1045 e976c6a1 aliguori
    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1046 095a9c58 aliguori
1047 52d893ec aliguori
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
1048 52d893ec aliguori
1049 095a9c58 aliguori
    /* We keep all QCOW_OFLAG_COPIED clusters */
1050 095a9c58 aliguori
1051 095a9c58 aliguori
    if (cluster_offset & QCOW_OFLAG_COPIED) {
1052 6db6c638 aliguori
        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
1053 ff4b91c2 aliguori
                &l2_table[l2_index], 0, 0);
1054 095a9c58 aliguori
1055 095a9c58 aliguori
        cluster_offset &= ~QCOW_OFLAG_COPIED;
1056 e976c6a1 aliguori
        m->nb_clusters = 0;
1057 095a9c58 aliguori
1058 095a9c58 aliguori
        goto out;
1059 095a9c58 aliguori
    }
1060 095a9c58 aliguori
1061 095a9c58 aliguori
    /* for the moment, multiple compressed clusters are not managed */
1062 095a9c58 aliguori
1063 095a9c58 aliguori
    if (cluster_offset & QCOW_OFLAG_COMPRESSED)
1064 095a9c58 aliguori
        nb_clusters = 1;
1065 095a9c58 aliguori
1066 bc352085 aliguori
    /* how many available clusters ? */
1067 095a9c58 aliguori
1068 bc352085 aliguori
    while (i < nb_clusters) {
1069 ab5ccbd6 aliguori
        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
1070 ff4b91c2 aliguori
                &l2_table[l2_index], i, 0);
1071 ab5ccbd6 aliguori
1072 ab5ccbd6 aliguori
        if(be64_to_cpu(l2_table[l2_index + i]))
1073 ab5ccbd6 aliguori
            break;
1074 ab5ccbd6 aliguori
1075 6db6c638 aliguori
        i += count_contiguous_free_clusters(nb_clusters - i,
1076 6db6c638 aliguori
                &l2_table[l2_index + i]);
1077 095a9c58 aliguori
1078 6db6c638 aliguori
        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
1079 095a9c58 aliguori
1080 6db6c638 aliguori
        if ((cluster_offset & QCOW_OFLAG_COPIED) ||
1081 bc352085 aliguori
                (cluster_offset & QCOW_OFLAG_COMPRESSED))
1082 6db6c638 aliguori
            break;
1083 095a9c58 aliguori
    }
1084 bc352085 aliguori
    nb_clusters = i;
1085 05203524 aliguori
1086 05203524 aliguori
    /* allocate a new cluster */
1087 05203524 aliguori
1088 095a9c58 aliguori
    cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);
1089 05203524 aliguori
1090 e976c6a1 aliguori
    /* save info needed for meta data update */
1091 e976c6a1 aliguori
    m->offset = offset;
1092 e976c6a1 aliguori
    m->n_start = n_start;
1093 e976c6a1 aliguori
    m->nb_clusters = nb_clusters;
1094 05203524 aliguori
1095 095a9c58 aliguori
out:
1096 e976c6a1 aliguori
    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
1097 e976c6a1 aliguori
1098 e976c6a1 aliguori
    *num = m->nb_available - n_start;
1099 095a9c58 aliguori
1100 585f8587 bellard
    return cluster_offset;
1101 585f8587 bellard
}
1102 585f8587 bellard
1103 5fafdf24 ths
static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
1104 585f8587 bellard
                             int nb_sectors, int *pnum)
1105 585f8587 bellard
{
1106 585f8587 bellard
    uint64_t cluster_offset;
1107 585f8587 bellard
1108 095a9c58 aliguori
    *pnum = nb_sectors;
1109 095a9c58 aliguori
    cluster_offset = get_cluster_offset(bs, sector_num << 9, pnum);
1110 095a9c58 aliguori
1111 585f8587 bellard
    return (cluster_offset != 0);
1112 585f8587 bellard
}
1113 585f8587 bellard
1114 585f8587 bellard
static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1115 585f8587 bellard
                             const uint8_t *buf, int buf_size)
1116 585f8587 bellard
{
1117 585f8587 bellard
    z_stream strm1, *strm = &strm1;
1118 585f8587 bellard
    int ret, out_len;
1119 585f8587 bellard
1120 585f8587 bellard
    memset(strm, 0, sizeof(*strm));
1121 585f8587 bellard
1122 585f8587 bellard
    strm->next_in = (uint8_t *)buf;
1123 585f8587 bellard
    strm->avail_in = buf_size;
1124 585f8587 bellard
    strm->next_out = out_buf;
1125 585f8587 bellard
    strm->avail_out = out_buf_size;
1126 585f8587 bellard
1127 585f8587 bellard
    ret = inflateInit2(strm, -12);
1128 585f8587 bellard
    if (ret != Z_OK)
1129 585f8587 bellard
        return -1;
1130 585f8587 bellard
    ret = inflate(strm, Z_FINISH);
1131 585f8587 bellard
    out_len = strm->next_out - out_buf;
1132 585f8587 bellard
    if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1133 585f8587 bellard
        out_len != out_buf_size) {
1134 585f8587 bellard
        inflateEnd(strm);
1135 585f8587 bellard
        return -1;
1136 585f8587 bellard
    }
1137 585f8587 bellard
    inflateEnd(strm);
1138 585f8587 bellard
    return 0;
1139 585f8587 bellard
}
1140 3b46e624 ths
1141 585f8587 bellard
static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
1142 585f8587 bellard
{
1143 585f8587 bellard
    int ret, csize, nb_csectors, sector_offset;
1144 585f8587 bellard
    uint64_t coffset;
1145 585f8587 bellard
1146 585f8587 bellard
    coffset = cluster_offset & s->cluster_offset_mask;
1147 585f8587 bellard
    if (s->cluster_cache_offset != coffset) {
1148 585f8587 bellard
        nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1149 585f8587 bellard
        sector_offset = coffset & 511;
1150 585f8587 bellard
        csize = nb_csectors * 512 - sector_offset;
1151 585f8587 bellard
        ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
1152 585f8587 bellard
        if (ret < 0) {
1153 585f8587 bellard
            return -1;
1154 585f8587 bellard
        }
1155 585f8587 bellard
        if (decompress_buffer(s->cluster_cache, s->cluster_size,
1156 585f8587 bellard
                              s->cluster_data + sector_offset, csize) < 0) {
1157 585f8587 bellard
            return -1;
1158 585f8587 bellard
        }
1159 585f8587 bellard
        s->cluster_cache_offset = coffset;
1160 585f8587 bellard
    }
1161 585f8587 bellard
    return 0;
1162 585f8587 bellard
}
1163 585f8587 bellard
1164 a9465922 bellard
/* handle reading after the end of the backing file */
1165 5fafdf24 ths
static int backing_read1(BlockDriverState *bs,
1166 a9465922 bellard
                         int64_t sector_num, uint8_t *buf, int nb_sectors)
1167 a9465922 bellard
{
1168 a9465922 bellard
    int n1;
1169 a9465922 bellard
    if ((sector_num + nb_sectors) <= bs->total_sectors)
1170 a9465922 bellard
        return nb_sectors;
1171 a9465922 bellard
    if (sector_num >= bs->total_sectors)
1172 a9465922 bellard
        n1 = 0;
1173 a9465922 bellard
    else
1174 a9465922 bellard
        n1 = bs->total_sectors - sector_num;
1175 a9465922 bellard
    memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
1176 a9465922 bellard
    return n1;
1177 a9465922 bellard
}
1178 a9465922 bellard
1179 5fafdf24 ths
static int qcow_read(BlockDriverState *bs, int64_t sector_num,
1180 585f8587 bellard
                     uint8_t *buf, int nb_sectors)
1181 585f8587 bellard
{
1182 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1183 a9465922 bellard
    int ret, index_in_cluster, n, n1;
1184 585f8587 bellard
    uint64_t cluster_offset;
1185 3b46e624 ths
1186 585f8587 bellard
    while (nb_sectors > 0) {
1187 095a9c58 aliguori
        n = nb_sectors;
1188 095a9c58 aliguori
        cluster_offset = get_cluster_offset(bs, sector_num << 9, &n);
1189 585f8587 bellard
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
1190 585f8587 bellard
        if (!cluster_offset) {
1191 585f8587 bellard
            if (bs->backing_hd) {
1192 585f8587 bellard
                /* read from the base image */
1193 a9465922 bellard
                n1 = backing_read1(bs->backing_hd, sector_num, buf, n);
1194 a9465922 bellard
                if (n1 > 0) {
1195 a9465922 bellard
                    ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
1196 a9465922 bellard
                    if (ret < 0)
1197 a9465922 bellard
                        return -1;
1198 a9465922 bellard
                }
1199 585f8587 bellard
            } else {
1200 585f8587 bellard
                memset(buf, 0, 512 * n);
1201 585f8587 bellard
            }
1202 585f8587 bellard
        } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
1203 585f8587 bellard
            if (decompress_cluster(s, cluster_offset) < 0)
1204 585f8587 bellard
                return -1;
1205 585f8587 bellard
            memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
1206 585f8587 bellard
        } else {
1207 585f8587 bellard
            ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1208 5fafdf24 ths
            if (ret != n * 512)
1209 585f8587 bellard
                return -1;
1210 585f8587 bellard
            if (s->crypt_method) {
1211 5fafdf24 ths
                encrypt_sectors(s, sector_num, buf, buf, n, 0,
1212 585f8587 bellard
                                &s->aes_decrypt_key);
1213 585f8587 bellard
            }
1214 585f8587 bellard
        }
1215 585f8587 bellard
        nb_sectors -= n;
1216 585f8587 bellard
        sector_num += n;
1217 585f8587 bellard
        buf += n * 512;
1218 585f8587 bellard
    }
1219 585f8587 bellard
    return 0;
1220 585f8587 bellard
}
1221 585f8587 bellard
1222 5fafdf24 ths
static int qcow_write(BlockDriverState *bs, int64_t sector_num,
1223 585f8587 bellard
                     const uint8_t *buf, int nb_sectors)
1224 585f8587 bellard
{
1225 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1226 585f8587 bellard
    int ret, index_in_cluster, n;
1227 585f8587 bellard
    uint64_t cluster_offset;
1228 095a9c58 aliguori
    int n_end;
1229 e976c6a1 aliguori
    QCowL2Meta l2meta;
1230 3b46e624 ths
1231 585f8587 bellard
    while (nb_sectors > 0) {
1232 585f8587 bellard
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
1233 095a9c58 aliguori
        n_end = index_in_cluster + nb_sectors;
1234 095a9c58 aliguori
        if (s->crypt_method &&
1235 095a9c58 aliguori
            n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1236 095a9c58 aliguori
            n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1237 52d893ec aliguori
        cluster_offset = alloc_cluster_offset(bs, sector_num << 9,
1238 05203524 aliguori
                                              index_in_cluster,
1239 e976c6a1 aliguori
                                              n_end, &n, &l2meta);
1240 585f8587 bellard
        if (!cluster_offset)
1241 585f8587 bellard
            return -1;
1242 585f8587 bellard
        if (s->crypt_method) {
1243 585f8587 bellard
            encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
1244 585f8587 bellard
                            &s->aes_encrypt_key);
1245 5fafdf24 ths
            ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512,
1246 585f8587 bellard
                              s->cluster_data, n * 512);
1247 585f8587 bellard
        } else {
1248 585f8587 bellard
            ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1249 585f8587 bellard
        }
1250 e976c6a1 aliguori
        if (ret != n * 512 || alloc_cluster_link_l2(bs, cluster_offset, &l2meta) < 0) {
1251 e976c6a1 aliguori
            free_any_clusters(bs, cluster_offset, l2meta.nb_clusters);
1252 585f8587 bellard
            return -1;
1253 e976c6a1 aliguori
        }
1254 585f8587 bellard
        nb_sectors -= n;
1255 585f8587 bellard
        sector_num += n;
1256 585f8587 bellard
        buf += n * 512;
1257 585f8587 bellard
    }
1258 585f8587 bellard
    s->cluster_cache_offset = -1; /* disable compressed cache */
1259 585f8587 bellard
    return 0;
1260 585f8587 bellard
}
1261 585f8587 bellard
1262 ce1a14dc pbrook
typedef struct QCowAIOCB {
1263 ce1a14dc pbrook
    BlockDriverAIOCB common;
1264 585f8587 bellard
    int64_t sector_num;
1265 f141eafe aliguori
    QEMUIOVector *qiov;
1266 585f8587 bellard
    uint8_t *buf;
1267 f141eafe aliguori
    void *orig_buf;
1268 585f8587 bellard
    int nb_sectors;
1269 585f8587 bellard
    int n;
1270 585f8587 bellard
    uint64_t cluster_offset;
1271 5fafdf24 ths
    uint8_t *cluster_data;
1272 585f8587 bellard
    BlockDriverAIOCB *hd_aiocb;
1273 c87c0672 aliguori
    struct iovec hd_iov;
1274 c87c0672 aliguori
    QEMUIOVector hd_qiov;
1275 1490791f aliguori
    QEMUBH *bh;
1276 e976c6a1 aliguori
    QCowL2Meta l2meta;
1277 585f8587 bellard
} QCowAIOCB;
1278 585f8587 bellard
1279 1490791f aliguori
static void qcow_aio_read_cb(void *opaque, int ret);
1280 1490791f aliguori
static void qcow_aio_read_bh(void *opaque)
1281 1490791f aliguori
{
1282 1490791f aliguori
    QCowAIOCB *acb = opaque;
1283 1490791f aliguori
    qemu_bh_delete(acb->bh);
1284 1490791f aliguori
    acb->bh = NULL;
1285 1490791f aliguori
    qcow_aio_read_cb(opaque, 0);
1286 1490791f aliguori
}
1287 1490791f aliguori
1288 a32ef786 aliguori
static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
1289 a32ef786 aliguori
{
1290 a32ef786 aliguori
    if (acb->bh)
1291 a32ef786 aliguori
        return -EIO;
1292 a32ef786 aliguori
1293 a32ef786 aliguori
    acb->bh = qemu_bh_new(cb, acb);
1294 a32ef786 aliguori
    if (!acb->bh)
1295 a32ef786 aliguori
        return -EIO;
1296 a32ef786 aliguori
1297 a32ef786 aliguori
    qemu_bh_schedule(acb->bh);
1298 a32ef786 aliguori
1299 a32ef786 aliguori
    return 0;
1300 a32ef786 aliguori
}
1301 a32ef786 aliguori
1302 585f8587 bellard
static void qcow_aio_read_cb(void *opaque, int ret)
1303 585f8587 bellard
{
1304 ce1a14dc pbrook
    QCowAIOCB *acb = opaque;
1305 ce1a14dc pbrook
    BlockDriverState *bs = acb->common.bs;
1306 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1307 a9465922 bellard
    int index_in_cluster, n1;
1308 585f8587 bellard
1309 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
1310 f141eafe aliguori
    if (ret < 0)
1311 f141eafe aliguori
        goto done;
1312 585f8587 bellard
1313 585f8587 bellard
    /* post process the read buffer */
1314 ce1a14dc pbrook
    if (!acb->cluster_offset) {
1315 585f8587 bellard
        /* nothing to do */
1316 ce1a14dc pbrook
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1317 585f8587 bellard
        /* nothing to do */
1318 585f8587 bellard
    } else {
1319 585f8587 bellard
        if (s->crypt_method) {
1320 5fafdf24 ths
            encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
1321 5fafdf24 ths
                            acb->n, 0,
1322 585f8587 bellard
                            &s->aes_decrypt_key);
1323 585f8587 bellard
        }
1324 585f8587 bellard
    }
1325 585f8587 bellard
1326 ce1a14dc pbrook
    acb->nb_sectors -= acb->n;
1327 ce1a14dc pbrook
    acb->sector_num += acb->n;
1328 ce1a14dc pbrook
    acb->buf += acb->n * 512;
1329 585f8587 bellard
1330 ce1a14dc pbrook
    if (acb->nb_sectors == 0) {
1331 585f8587 bellard
        /* request completed */
1332 f141eafe aliguori
        ret = 0;
1333 f141eafe aliguori
        goto done;
1334 585f8587 bellard
    }
1335 3b46e624 ths
1336 585f8587 bellard
    /* prepare next AIO request */
1337 095a9c58 aliguori
    acb->n = acb->nb_sectors;
1338 095a9c58 aliguori
    acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
1339 ce1a14dc pbrook
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1340 ce1a14dc pbrook
1341 ce1a14dc pbrook
    if (!acb->cluster_offset) {
1342 585f8587 bellard
        if (bs->backing_hd) {
1343 585f8587 bellard
            /* read from the base image */
1344 5fafdf24 ths
            n1 = backing_read1(bs->backing_hd, acb->sector_num,
1345 ce1a14dc pbrook
                               acb->buf, acb->n);
1346 a9465922 bellard
            if (n1 > 0) {
1347 3f4cb3d3 blueswir1
                acb->hd_iov.iov_base = (void *)acb->buf;
1348 c87c0672 aliguori
                acb->hd_iov.iov_len = acb->n * 512;
1349 c87c0672 aliguori
                qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1350 c87c0672 aliguori
                acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
1351 c87c0672 aliguori
                                    &acb->hd_qiov, acb->n,
1352 c87c0672 aliguori
                                    qcow_aio_read_cb, acb);
1353 ce1a14dc pbrook
                if (acb->hd_aiocb == NULL)
1354 f141eafe aliguori
                    goto done;
1355 a9465922 bellard
            } else {
1356 a32ef786 aliguori
                ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1357 a32ef786 aliguori
                if (ret < 0)
1358 f141eafe aliguori
                    goto done;
1359 a9465922 bellard
            }
1360 585f8587 bellard
        } else {
1361 585f8587 bellard
            /* Note: in this case, no need to wait */
1362 ce1a14dc pbrook
            memset(acb->buf, 0, 512 * acb->n);
1363 a32ef786 aliguori
            ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1364 a32ef786 aliguori
            if (ret < 0)
1365 f141eafe aliguori
                goto done;
1366 585f8587 bellard
        }
1367 ce1a14dc pbrook
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1368 585f8587 bellard
        /* add AIO support for compressed blocks ? */
1369 ce1a14dc pbrook
        if (decompress_cluster(s, acb->cluster_offset) < 0)
1370 f141eafe aliguori
            goto done;
1371 5fafdf24 ths
        memcpy(acb->buf,
1372 ce1a14dc pbrook
               s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
1373 a32ef786 aliguori
        ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1374 a32ef786 aliguori
        if (ret < 0)
1375 f141eafe aliguori
            goto done;
1376 585f8587 bellard
    } else {
1377 ce1a14dc pbrook
        if ((acb->cluster_offset & 511) != 0) {
1378 585f8587 bellard
            ret = -EIO;
1379 f141eafe aliguori
            goto done;
1380 585f8587 bellard
        }
1381 c87c0672 aliguori
1382 3f4cb3d3 blueswir1
        acb->hd_iov.iov_base = (void *)acb->buf;
1383 c87c0672 aliguori
        acb->hd_iov.iov_len = acb->n * 512;
1384 c87c0672 aliguori
        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1385 c87c0672 aliguori
        acb->hd_aiocb = bdrv_aio_readv(s->hd,
1386 5fafdf24 ths
                            (acb->cluster_offset >> 9) + index_in_cluster,
1387 c87c0672 aliguori
                            &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
1388 ce1a14dc pbrook
        if (acb->hd_aiocb == NULL)
1389 f141eafe aliguori
            goto done;
1390 f141eafe aliguori
    }
1391 f141eafe aliguori
1392 f141eafe aliguori
    return;
1393 f141eafe aliguori
done:
1394 f141eafe aliguori
    if (acb->qiov->niov > 1) {
1395 f141eafe aliguori
        qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
1396 f141eafe aliguori
        qemu_vfree(acb->orig_buf);
1397 585f8587 bellard
    }
1398 f141eafe aliguori
    acb->common.cb(acb->common.opaque, ret);
1399 f141eafe aliguori
    qemu_aio_release(acb);
1400 585f8587 bellard
}
1401 585f8587 bellard
1402 ce1a14dc pbrook
static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
1403 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1404 f141eafe aliguori
        BlockDriverCompletionFunc *cb, void *opaque, int is_write)
1405 585f8587 bellard
{
1406 ce1a14dc pbrook
    QCowAIOCB *acb;
1407 ce1a14dc pbrook
1408 ce1a14dc pbrook
    acb = qemu_aio_get(bs, cb, opaque);
1409 ce1a14dc pbrook
    if (!acb)
1410 ce1a14dc pbrook
        return NULL;
1411 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
1412 ce1a14dc pbrook
    acb->sector_num = sector_num;
1413 f141eafe aliguori
    acb->qiov = qiov;
1414 f141eafe aliguori
    if (qiov->niov > 1) {
1415 f141eafe aliguori
        acb->buf = acb->orig_buf = qemu_memalign(512, qiov->size);
1416 f141eafe aliguori
        if (is_write)
1417 f141eafe aliguori
            qemu_iovec_to_buffer(qiov, acb->buf);
1418 3f4cb3d3 blueswir1
    } else {
1419 3f4cb3d3 blueswir1
        acb->buf = (uint8_t *)qiov->iov->iov_base;
1420 3f4cb3d3 blueswir1
    }
1421 ce1a14dc pbrook
    acb->nb_sectors = nb_sectors;
1422 ce1a14dc pbrook
    acb->n = 0;
1423 ce1a14dc pbrook
    acb->cluster_offset = 0;
1424 e976c6a1 aliguori
    acb->l2meta.nb_clusters = 0;
1425 ce1a14dc pbrook
    return acb;
1426 ce1a14dc pbrook
}
1427 ce1a14dc pbrook
1428 f141eafe aliguori
static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
1429 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1430 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque)
1431 ce1a14dc pbrook
{
1432 ce1a14dc pbrook
    QCowAIOCB *acb;
1433 ce1a14dc pbrook
1434 f141eafe aliguori
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1435 ce1a14dc pbrook
    if (!acb)
1436 ce1a14dc pbrook
        return NULL;
1437 585f8587 bellard
1438 585f8587 bellard
    qcow_aio_read_cb(acb, 0);
1439 ce1a14dc pbrook
    return &acb->common;
1440 585f8587 bellard
}
1441 585f8587 bellard
1442 585f8587 bellard
static void qcow_aio_write_cb(void *opaque, int ret)
1443 585f8587 bellard
{
1444 ce1a14dc pbrook
    QCowAIOCB *acb = opaque;
1445 ce1a14dc pbrook
    BlockDriverState *bs = acb->common.bs;
1446 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1447 585f8587 bellard
    int index_in_cluster;
1448 585f8587 bellard
    const uint8_t *src_buf;
1449 095a9c58 aliguori
    int n_end;
1450 ce1a14dc pbrook
1451 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
1452 ce1a14dc pbrook
1453 f141eafe aliguori
    if (ret < 0)
1454 f141eafe aliguori
        goto done;
1455 585f8587 bellard
1456 e976c6a1 aliguori
    if (alloc_cluster_link_l2(bs, acb->cluster_offset, &acb->l2meta) < 0) {
1457 e976c6a1 aliguori
        free_any_clusters(bs, acb->cluster_offset, acb->l2meta.nb_clusters);
1458 f141eafe aliguori
        goto done;
1459 e976c6a1 aliguori
    }
1460 e976c6a1 aliguori
1461 ce1a14dc pbrook
    acb->nb_sectors -= acb->n;
1462 ce1a14dc pbrook
    acb->sector_num += acb->n;
1463 ce1a14dc pbrook
    acb->buf += acb->n * 512;
1464 585f8587 bellard
1465 ce1a14dc pbrook
    if (acb->nb_sectors == 0) {
1466 585f8587 bellard
        /* request completed */
1467 f141eafe aliguori
        ret = 0;
1468 f141eafe aliguori
        goto done;
1469 585f8587 bellard
    }
1470 3b46e624 ths
1471 ce1a14dc pbrook
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1472 095a9c58 aliguori
    n_end = index_in_cluster + acb->nb_sectors;
1473 095a9c58 aliguori
    if (s->crypt_method &&
1474 095a9c58 aliguori
        n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1475 095a9c58 aliguori
        n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1476 095a9c58 aliguori
1477 e976c6a1 aliguori
    acb->cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,
1478 05203524 aliguori
                                          index_in_cluster,
1479 e976c6a1 aliguori
                                          n_end, &acb->n, &acb->l2meta);
1480 e976c6a1 aliguori
    if (!acb->cluster_offset || (acb->cluster_offset & 511) != 0) {
1481 585f8587 bellard
        ret = -EIO;
1482 f141eafe aliguori
        goto done;
1483 585f8587 bellard
    }
1484 585f8587 bellard
    if (s->crypt_method) {
1485 ce1a14dc pbrook
        if (!acb->cluster_data) {
1486 095a9c58 aliguori
            acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
1487 095a9c58 aliguori
                                             s->cluster_size);
1488 585f8587 bellard
        }
1489 5fafdf24 ths
        encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
1490 ce1a14dc pbrook
                        acb->n, 1, &s->aes_encrypt_key);
1491 ce1a14dc pbrook
        src_buf = acb->cluster_data;
1492 585f8587 bellard
    } else {
1493 ce1a14dc pbrook
        src_buf = acb->buf;
1494 585f8587 bellard
    }
1495 c87c0672 aliguori
    acb->hd_iov.iov_base = (void *)src_buf;
1496 c87c0672 aliguori
    acb->hd_iov.iov_len = acb->n * 512;
1497 c87c0672 aliguori
    qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1498 c87c0672 aliguori
    acb->hd_aiocb = bdrv_aio_writev(s->hd,
1499 c87c0672 aliguori
                                    (acb->cluster_offset >> 9) + index_in_cluster,
1500 c87c0672 aliguori
                                    &acb->hd_qiov, acb->n,
1501 c87c0672 aliguori
                                    qcow_aio_write_cb, acb);
1502 ce1a14dc pbrook
    if (acb->hd_aiocb == NULL)
1503 f141eafe aliguori
        goto done;
1504 f141eafe aliguori
1505 f141eafe aliguori
    return;
1506 f141eafe aliguori
1507 f141eafe aliguori
done:
1508 f141eafe aliguori
    if (acb->qiov->niov > 1)
1509 f141eafe aliguori
        qemu_vfree(acb->orig_buf);
1510 f141eafe aliguori
    acb->common.cb(acb->common.opaque, ret);
1511 f141eafe aliguori
    qemu_aio_release(acb);
1512 585f8587 bellard
}
1513 585f8587 bellard
1514 f141eafe aliguori
static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
1515 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1516 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque)
1517 585f8587 bellard
{
1518 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1519 ce1a14dc pbrook
    QCowAIOCB *acb;
1520 3b46e624 ths
1521 585f8587 bellard
    s->cluster_cache_offset = -1; /* disable compressed cache */
1522 585f8587 bellard
1523 f141eafe aliguori
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1524 ce1a14dc pbrook
    if (!acb)
1525 ce1a14dc pbrook
        return NULL;
1526 3b46e624 ths
1527 585f8587 bellard
    qcow_aio_write_cb(acb, 0);
1528 ce1a14dc pbrook
    return &acb->common;
1529 585f8587 bellard
}
1530 585f8587 bellard
1531 ce1a14dc pbrook
static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
1532 585f8587 bellard
{
1533 ce1a14dc pbrook
    QCowAIOCB *acb = (QCowAIOCB *)blockacb;
1534 ce1a14dc pbrook
    if (acb->hd_aiocb)
1535 ce1a14dc pbrook
        bdrv_aio_cancel(acb->hd_aiocb);
1536 ce1a14dc pbrook
    qemu_aio_release(acb);
1537 585f8587 bellard
}
1538 585f8587 bellard
1539 585f8587 bellard
static void qcow_close(BlockDriverState *bs)
1540 585f8587 bellard
{
1541 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1542 585f8587 bellard
    qemu_free(s->l1_table);
1543 585f8587 bellard
    qemu_free(s->l2_cache);
1544 585f8587 bellard
    qemu_free(s->cluster_cache);
1545 585f8587 bellard
    qemu_free(s->cluster_data);
1546 585f8587 bellard
    refcount_close(bs);
1547 585f8587 bellard
    bdrv_delete(s->hd);
1548 585f8587 bellard
}
1549 585f8587 bellard
1550 585f8587 bellard
/* XXX: use std qcow open function ? */
1551 585f8587 bellard
typedef struct QCowCreateState {
1552 585f8587 bellard
    int cluster_size;
1553 585f8587 bellard
    int cluster_bits;
1554 585f8587 bellard
    uint16_t *refcount_block;
1555 585f8587 bellard
    uint64_t *refcount_table;
1556 585f8587 bellard
    int64_t l1_table_offset;
1557 585f8587 bellard
    int64_t refcount_table_offset;
1558 585f8587 bellard
    int64_t refcount_block_offset;
1559 585f8587 bellard
} QCowCreateState;
1560 585f8587 bellard
1561 585f8587 bellard
static void create_refcount_update(QCowCreateState *s,
1562 585f8587 bellard
                                   int64_t offset, int64_t size)
1563 585f8587 bellard
{
1564 585f8587 bellard
    int refcount;
1565 585f8587 bellard
    int64_t start, last, cluster_offset;
1566 585f8587 bellard
    uint16_t *p;
1567 585f8587 bellard
1568 585f8587 bellard
    start = offset & ~(s->cluster_size - 1);
1569 585f8587 bellard
    last = (offset + size - 1)  & ~(s->cluster_size - 1);
1570 5fafdf24 ths
    for(cluster_offset = start; cluster_offset <= last;
1571 585f8587 bellard
        cluster_offset += s->cluster_size) {
1572 585f8587 bellard
        p = &s->refcount_block[cluster_offset >> s->cluster_bits];
1573 585f8587 bellard
        refcount = be16_to_cpu(*p);
1574 585f8587 bellard
        refcount++;
1575 585f8587 bellard
        *p = cpu_to_be16(refcount);
1576 585f8587 bellard
    }
1577 585f8587 bellard
}
1578 585f8587 bellard
1579 f965509c aliguori
static int qcow_create2(const char *filename, int64_t total_size,
1580 f965509c aliguori
                        const char *backing_file, const char *backing_format,
1581 f965509c aliguori
                        int flags)
1582 585f8587 bellard
{
1583 f965509c aliguori
1584 585f8587 bellard
    int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
1585 2d2431f0 aliguori
    int ref_clusters, backing_format_len = 0;
1586 585f8587 bellard
    QCowHeader header;
1587 585f8587 bellard
    uint64_t tmp, offset;
1588 585f8587 bellard
    QCowCreateState s1, *s = &s1;
1589 f965509c aliguori
    QCowExtension ext_bf = {0, 0};
1590 f965509c aliguori
1591 3b46e624 ths
1592 585f8587 bellard
    memset(s, 0, sizeof(*s));
1593 585f8587 bellard
1594 585f8587 bellard
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1595 585f8587 bellard
    if (fd < 0)
1596 585f8587 bellard
        return -1;
1597 585f8587 bellard
    memset(&header, 0, sizeof(header));
1598 585f8587 bellard
    header.magic = cpu_to_be32(QCOW_MAGIC);
1599 585f8587 bellard
    header.version = cpu_to_be32(QCOW_VERSION);
1600 585f8587 bellard
    header.size = cpu_to_be64(total_size * 512);
1601 585f8587 bellard
    header_size = sizeof(header);
1602 585f8587 bellard
    backing_filename_len = 0;
1603 585f8587 bellard
    if (backing_file) {
1604 f965509c aliguori
        if (backing_format) {
1605 f965509c aliguori
            ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
1606 f965509c aliguori
            backing_format_len = strlen(backing_format);
1607 f965509c aliguori
            ext_bf.len = (backing_format_len + 7) & ~7;
1608 f965509c aliguori
            header_size += ((sizeof(ext_bf) + ext_bf.len + 7) & ~7);
1609 f965509c aliguori
        }
1610 585f8587 bellard
        header.backing_file_offset = cpu_to_be64(header_size);
1611 585f8587 bellard
        backing_filename_len = strlen(backing_file);
1612 585f8587 bellard
        header.backing_file_size = cpu_to_be32(backing_filename_len);
1613 585f8587 bellard
        header_size += backing_filename_len;
1614 585f8587 bellard
    }
1615 585f8587 bellard
    s->cluster_bits = 12;  /* 4 KB clusters */
1616 585f8587 bellard
    s->cluster_size = 1 << s->cluster_bits;
1617 585f8587 bellard
    header.cluster_bits = cpu_to_be32(s->cluster_bits);
1618 585f8587 bellard
    header_size = (header_size + 7) & ~7;
1619 ec36ba14 ths
    if (flags & BLOCK_FLAG_ENCRYPT) {
1620 585f8587 bellard
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1621 585f8587 bellard
    } else {
1622 585f8587 bellard
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1623 585f8587 bellard
    }
1624 585f8587 bellard
    l2_bits = s->cluster_bits - 3;
1625 585f8587 bellard
    shift = s->cluster_bits + l2_bits;
1626 585f8587 bellard
    l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
1627 585f8587 bellard
    offset = align_offset(header_size, s->cluster_size);
1628 585f8587 bellard
    s->l1_table_offset = offset;
1629 585f8587 bellard
    header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
1630 585f8587 bellard
    header.l1_size = cpu_to_be32(l1_size);
1631 15e6690a bellard
    offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
1632 585f8587 bellard
1633 585f8587 bellard
    s->refcount_table = qemu_mallocz(s->cluster_size);
1634 3b46e624 ths
1635 585f8587 bellard
    s->refcount_table_offset = offset;
1636 585f8587 bellard
    header.refcount_table_offset = cpu_to_be64(offset);
1637 585f8587 bellard
    header.refcount_table_clusters = cpu_to_be32(1);
1638 585f8587 bellard
    offset += s->cluster_size;
1639 585f8587 bellard
    s->refcount_block_offset = offset;
1640 2d2431f0 aliguori
1641 2d2431f0 aliguori
    /* count how many refcount blocks needed */
1642 2d2431f0 aliguori
    tmp = offset >> s->cluster_bits;
1643 2d2431f0 aliguori
    ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
1644 2d2431f0 aliguori
    for (i=0; i < ref_clusters; i++) {
1645 2d2431f0 aliguori
        s->refcount_table[i] = cpu_to_be64(offset);
1646 2d2431f0 aliguori
        offset += s->cluster_size;
1647 2d2431f0 aliguori
    }
1648 2d2431f0 aliguori
1649 2d2431f0 aliguori
    s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
1650 585f8587 bellard
1651 585f8587 bellard
    /* update refcounts */
1652 585f8587 bellard
    create_refcount_update(s, 0, header_size);
1653 15e6690a bellard
    create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
1654 585f8587 bellard
    create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
1655 2d2431f0 aliguori
    create_refcount_update(s, s->refcount_block_offset, ref_clusters * s->cluster_size);
1656 3b46e624 ths
1657 585f8587 bellard
    /* write all the data */
1658 585f8587 bellard
    write(fd, &header, sizeof(header));
1659 585f8587 bellard
    if (backing_file) {
1660 f965509c aliguori
        if (backing_format_len) {
1661 f965509c aliguori
            char zero[16];
1662 f965509c aliguori
            int d = ext_bf.len - backing_format_len;
1663 f965509c aliguori
1664 f965509c aliguori
            memset(zero, 0, sizeof(zero));
1665 f965509c aliguori
            cpu_to_be32s(&ext_bf.magic);
1666 f965509c aliguori
            cpu_to_be32s(&ext_bf.len);
1667 f965509c aliguori
            write(fd, &ext_bf, sizeof(ext_bf));
1668 f965509c aliguori
            write(fd, backing_format, backing_format_len);
1669 f965509c aliguori
            if (d>0) {
1670 f965509c aliguori
                write(fd, zero, d);
1671 f965509c aliguori
            }
1672 f965509c aliguori
        }
1673 585f8587 bellard
        write(fd, backing_file, backing_filename_len);
1674 585f8587 bellard
    }
1675 585f8587 bellard
    lseek(fd, s->l1_table_offset, SEEK_SET);
1676 585f8587 bellard
    tmp = 0;
1677 585f8587 bellard
    for(i = 0;i < l1_size; i++) {
1678 585f8587 bellard
        write(fd, &tmp, sizeof(tmp));
1679 585f8587 bellard
    }
1680 585f8587 bellard
    lseek(fd, s->refcount_table_offset, SEEK_SET);
1681 585f8587 bellard
    write(fd, s->refcount_table, s->cluster_size);
1682 3b46e624 ths
1683 585f8587 bellard
    lseek(fd, s->refcount_block_offset, SEEK_SET);
1684 2d2431f0 aliguori
    write(fd, s->refcount_block, ref_clusters * s->cluster_size);
1685 585f8587 bellard
1686 585f8587 bellard
    qemu_free(s->refcount_table);
1687 585f8587 bellard
    qemu_free(s->refcount_block);
1688 585f8587 bellard
    close(fd);
1689 585f8587 bellard
    return 0;
1690 585f8587 bellard
}
1691 585f8587 bellard
1692 f965509c aliguori
static int qcow_create(const char *filename, int64_t total_size,
1693 f965509c aliguori
                       const char *backing_file, int flags)
1694 f965509c aliguori
{
1695 f965509c aliguori
    return qcow_create2(filename, total_size, backing_file, NULL, flags);
1696 f965509c aliguori
}
1697 f965509c aliguori
1698 585f8587 bellard
static int qcow_make_empty(BlockDriverState *bs)
1699 585f8587 bellard
{
1700 585f8587 bellard
#if 0
1701 585f8587 bellard
    /* XXX: not correct */
1702 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1703 585f8587 bellard
    uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1704 585f8587 bellard
    int ret;
1705 585f8587 bellard

1706 585f8587 bellard
    memset(s->l1_table, 0, l1_length);
1707 585f8587 bellard
    if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1708 ac674887 aliguori
        return -1;
1709 585f8587 bellard
    ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1710 585f8587 bellard
    if (ret < 0)
1711 585f8587 bellard
        return ret;
1712 3b46e624 ths

1713 585f8587 bellard
    l2_cache_reset(bs);
1714 585f8587 bellard
#endif
1715 585f8587 bellard
    return 0;
1716 585f8587 bellard
}
1717 585f8587 bellard
1718 585f8587 bellard
/* XXX: put compressed sectors first, then all the cluster aligned
1719 585f8587 bellard
   tables to avoid losing bytes in alignment */
1720 5fafdf24 ths
static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1721 585f8587 bellard
                                 const uint8_t *buf, int nb_sectors)
1722 585f8587 bellard
{
1723 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1724 585f8587 bellard
    z_stream strm;
1725 585f8587 bellard
    int ret, out_len;
1726 585f8587 bellard
    uint8_t *out_buf;
1727 585f8587 bellard
    uint64_t cluster_offset;
1728 585f8587 bellard
1729 585f8587 bellard
    if (nb_sectors == 0) {
1730 585f8587 bellard
        /* align end of file to a sector boundary to ease reading with
1731 585f8587 bellard
           sector based I/Os */
1732 585f8587 bellard
        cluster_offset = bdrv_getlength(s->hd);
1733 585f8587 bellard
        cluster_offset = (cluster_offset + 511) & ~511;
1734 585f8587 bellard
        bdrv_truncate(s->hd, cluster_offset);
1735 585f8587 bellard
        return 0;
1736 585f8587 bellard
    }
1737 585f8587 bellard
1738 585f8587 bellard
    if (nb_sectors != s->cluster_sectors)
1739 585f8587 bellard
        return -EINVAL;
1740 585f8587 bellard
1741 585f8587 bellard
    out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1742 585f8587 bellard
1743 585f8587 bellard
    /* best compression, small window, no zlib header */
1744 585f8587 bellard
    memset(&strm, 0, sizeof(strm));
1745 585f8587 bellard
    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1746 5fafdf24 ths
                       Z_DEFLATED, -12,
1747 585f8587 bellard
                       9, Z_DEFAULT_STRATEGY);
1748 585f8587 bellard
    if (ret != 0) {
1749 585f8587 bellard
        qemu_free(out_buf);
1750 585f8587 bellard
        return -1;
1751 585f8587 bellard
    }
1752 585f8587 bellard
1753 585f8587 bellard
    strm.avail_in = s->cluster_size;
1754 585f8587 bellard
    strm.next_in = (uint8_t *)buf;
1755 585f8587 bellard
    strm.avail_out = s->cluster_size;
1756 585f8587 bellard
    strm.next_out = out_buf;
1757 585f8587 bellard
1758 585f8587 bellard
    ret = deflate(&strm, Z_FINISH);
1759 585f8587 bellard
    if (ret != Z_STREAM_END && ret != Z_OK) {
1760 585f8587 bellard
        qemu_free(out_buf);
1761 585f8587 bellard
        deflateEnd(&strm);
1762 585f8587 bellard
        return -1;
1763 585f8587 bellard
    }
1764 585f8587 bellard
    out_len = strm.next_out - out_buf;
1765 585f8587 bellard
1766 585f8587 bellard
    deflateEnd(&strm);
1767 585f8587 bellard
1768 585f8587 bellard
    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1769 585f8587 bellard
        /* could not compress: write normal cluster */
1770 585f8587 bellard
        qcow_write(bs, sector_num, buf, s->cluster_sectors);
1771 585f8587 bellard
    } else {
1772 52d893ec aliguori
        cluster_offset = alloc_compressed_cluster_offset(bs, sector_num << 9,
1773 52d893ec aliguori
                                              out_len);
1774 52d893ec aliguori
        if (!cluster_offset)
1775 52d893ec aliguori
            return -1;
1776 585f8587 bellard
        cluster_offset &= s->cluster_offset_mask;
1777 585f8587 bellard
        if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1778 585f8587 bellard
            qemu_free(out_buf);
1779 585f8587 bellard
            return -1;
1780 585f8587 bellard
        }
1781 585f8587 bellard
    }
1782 3b46e624 ths
1783 585f8587 bellard
    qemu_free(out_buf);
1784 585f8587 bellard
    return 0;
1785 585f8587 bellard
}
1786 585f8587 bellard
1787 585f8587 bellard
static void qcow_flush(BlockDriverState *bs)
1788 585f8587 bellard
{
1789 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1790 585f8587 bellard
    bdrv_flush(s->hd);
1791 585f8587 bellard
}
1792 585f8587 bellard
1793 585f8587 bellard
static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1794 585f8587 bellard
{
1795 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1796 585f8587 bellard
    bdi->cluster_size = s->cluster_size;
1797 5fafdf24 ths
    bdi->vm_state_offset = (int64_t)s->l1_vm_state_index <<
1798 585f8587 bellard
        (s->cluster_bits + s->l2_bits);
1799 585f8587 bellard
    return 0;
1800 585f8587 bellard
}
1801 585f8587 bellard
1802 585f8587 bellard
/*********************************************************/
1803 585f8587 bellard
/* snapshot support */
1804 585f8587 bellard
1805 585f8587 bellard
/* update the refcounts of snapshots and the copied flag */
1806 5fafdf24 ths
static int update_snapshot_refcount(BlockDriverState *bs,
1807 585f8587 bellard
                                    int64_t l1_table_offset,
1808 585f8587 bellard
                                    int l1_size,
1809 585f8587 bellard
                                    int addend)
1810 585f8587 bellard
{
1811 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1812 585f8587 bellard
    uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;
1813 585f8587 bellard
    int64_t old_offset, old_l2_offset;
1814 585f8587 bellard
    int l2_size, i, j, l1_modified, l2_modified, nb_csectors, refcount;
1815 3b46e624 ths
1816 585f8587 bellard
    l2_cache_reset(bs);
1817 585f8587 bellard
1818 585f8587 bellard
    l2_table = NULL;
1819 585f8587 bellard
    l1_table = NULL;
1820 585f8587 bellard
    l1_size2 = l1_size * sizeof(uint64_t);
1821 585f8587 bellard
    l1_allocated = 0;
1822 585f8587 bellard
    if (l1_table_offset != s->l1_table_offset) {
1823 585f8587 bellard
        l1_table = qemu_malloc(l1_size2);
1824 585f8587 bellard
        l1_allocated = 1;
1825 5fafdf24 ths
        if (bdrv_pread(s->hd, l1_table_offset,
1826 585f8587 bellard
                       l1_table, l1_size2) != l1_size2)
1827 585f8587 bellard
            goto fail;
1828 585f8587 bellard
        for(i = 0;i < l1_size; i++)
1829 585f8587 bellard
            be64_to_cpus(&l1_table[i]);
1830 585f8587 bellard
    } else {
1831 585f8587 bellard
        assert(l1_size == s->l1_size);
1832 585f8587 bellard
        l1_table = s->l1_table;
1833 585f8587 bellard
        l1_allocated = 0;
1834 585f8587 bellard
    }
1835 3b46e624 ths
1836 585f8587 bellard
    l2_size = s->l2_size * sizeof(uint64_t);
1837 585f8587 bellard
    l2_table = qemu_malloc(l2_size);
1838 585f8587 bellard
    l1_modified = 0;
1839 585f8587 bellard
    for(i = 0; i < l1_size; i++) {
1840 585f8587 bellard
        l2_offset = l1_table[i];
1841 585f8587 bellard
        if (l2_offset) {
1842 585f8587 bellard
            old_l2_offset = l2_offset;
1843 585f8587 bellard
            l2_offset &= ~QCOW_OFLAG_COPIED;
1844 585f8587 bellard
            l2_modified = 0;
1845 585f8587 bellard
            if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
1846 585f8587 bellard
                goto fail;
1847 585f8587 bellard
            for(j = 0; j < s->l2_size; j++) {
1848 585f8587 bellard
                offset = be64_to_cpu(l2_table[j]);
1849 585f8587 bellard
                if (offset != 0) {
1850 585f8587 bellard
                    old_offset = offset;
1851 585f8587 bellard
                    offset &= ~QCOW_OFLAG_COPIED;
1852 585f8587 bellard
                    if (offset & QCOW_OFLAG_COMPRESSED) {
1853 5fafdf24 ths
                        nb_csectors = ((offset >> s->csize_shift) &
1854 585f8587 bellard
                                       s->csize_mask) + 1;
1855 585f8587 bellard
                        if (addend != 0)
1856 585f8587 bellard
                            update_refcount(bs, (offset & s->cluster_offset_mask) & ~511,
1857 585f8587 bellard
                                            nb_csectors * 512, addend);
1858 585f8587 bellard
                        /* compressed clusters are never modified */
1859 5fafdf24 ths
                        refcount = 2;
1860 585f8587 bellard
                    } else {
1861 585f8587 bellard
                        if (addend != 0) {
1862 585f8587 bellard
                            refcount = update_cluster_refcount(bs, offset >> s->cluster_bits, addend);
1863 585f8587 bellard
                        } else {
1864 585f8587 bellard
                            refcount = get_refcount(bs, offset >> s->cluster_bits);
1865 585f8587 bellard
                        }
1866 585f8587 bellard
                    }
1867 585f8587 bellard
1868 585f8587 bellard
                    if (refcount == 1) {
1869 585f8587 bellard
                        offset |= QCOW_OFLAG_COPIED;
1870 585f8587 bellard
                    }
1871 585f8587 bellard
                    if (offset != old_offset) {
1872 585f8587 bellard
                        l2_table[j] = cpu_to_be64(offset);
1873 585f8587 bellard
                        l2_modified = 1;
1874 585f8587 bellard
                    }
1875 585f8587 bellard
                }
1876 585f8587 bellard
            }
1877 585f8587 bellard
            if (l2_modified) {
1878 5fafdf24 ths
                if (bdrv_pwrite(s->hd,
1879 585f8587 bellard
                                l2_offset, l2_table, l2_size) != l2_size)
1880 585f8587 bellard
                    goto fail;
1881 585f8587 bellard
            }
1882 585f8587 bellard
1883 585f8587 bellard
            if (addend != 0) {
1884 585f8587 bellard
                refcount = update_cluster_refcount(bs, l2_offset >> s->cluster_bits, addend);
1885 585f8587 bellard
            } else {
1886 585f8587 bellard
                refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1887 585f8587 bellard
            }
1888 585f8587 bellard
            if (refcount == 1) {
1889 585f8587 bellard
                l2_offset |= QCOW_OFLAG_COPIED;
1890 585f8587 bellard
            }
1891 585f8587 bellard
            if (l2_offset != old_l2_offset) {
1892 585f8587 bellard
                l1_table[i] = l2_offset;
1893 585f8587 bellard
                l1_modified = 1;
1894 585f8587 bellard
            }
1895 585f8587 bellard
        }
1896 585f8587 bellard
    }
1897 585f8587 bellard
    if (l1_modified) {
1898 585f8587 bellard
        for(i = 0; i < l1_size; i++)
1899 585f8587 bellard
            cpu_to_be64s(&l1_table[i]);
1900 5fafdf24 ths
        if (bdrv_pwrite(s->hd, l1_table_offset, l1_table,
1901 585f8587 bellard
                        l1_size2) != l1_size2)
1902 585f8587 bellard
            goto fail;
1903 585f8587 bellard
        for(i = 0; i < l1_size; i++)
1904 585f8587 bellard
            be64_to_cpus(&l1_table[i]);
1905 585f8587 bellard
    }
1906 585f8587 bellard
    if (l1_allocated)
1907 585f8587 bellard
        qemu_free(l1_table);
1908 585f8587 bellard
    qemu_free(l2_table);
1909 585f8587 bellard
    return 0;
1910 585f8587 bellard
 fail:
1911 585f8587 bellard
    if (l1_allocated)
1912 585f8587 bellard
        qemu_free(l1_table);
1913 585f8587 bellard
    qemu_free(l2_table);
1914 585f8587 bellard
    return -EIO;
1915 585f8587 bellard
}
1916 585f8587 bellard
1917 585f8587 bellard
static void qcow_free_snapshots(BlockDriverState *bs)
1918 585f8587 bellard
{
1919 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1920 585f8587 bellard
    int i;
1921 585f8587 bellard
1922 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
1923 585f8587 bellard
        qemu_free(s->snapshots[i].name);
1924 585f8587 bellard
        qemu_free(s->snapshots[i].id_str);
1925 585f8587 bellard
    }
1926 585f8587 bellard
    qemu_free(s->snapshots);
1927 585f8587 bellard
    s->snapshots = NULL;
1928 585f8587 bellard
    s->nb_snapshots = 0;
1929 585f8587 bellard
}
1930 585f8587 bellard
1931 585f8587 bellard
static int qcow_read_snapshots(BlockDriverState *bs)
1932 585f8587 bellard
{
1933 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1934 585f8587 bellard
    QCowSnapshotHeader h;
1935 585f8587 bellard
    QCowSnapshot *sn;
1936 585f8587 bellard
    int i, id_str_size, name_size;
1937 585f8587 bellard
    int64_t offset;
1938 585f8587 bellard
    uint32_t extra_data_size;
1939 585f8587 bellard
1940 63c75dcd malc
    if (!s->nb_snapshots) {
1941 63c75dcd malc
        s->snapshots = NULL;
1942 63c75dcd malc
        s->snapshots_size = 0;
1943 63c75dcd malc
        return 0;
1944 63c75dcd malc
    }
1945 63c75dcd malc
1946 585f8587 bellard
    offset = s->snapshots_offset;
1947 585f8587 bellard
    s->snapshots = qemu_mallocz(s->nb_snapshots * sizeof(QCowSnapshot));
1948 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
1949 585f8587 bellard
        offset = align_offset(offset, 8);
1950 585f8587 bellard
        if (bdrv_pread(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1951 585f8587 bellard
            goto fail;
1952 585f8587 bellard
        offset += sizeof(h);
1953 585f8587 bellard
        sn = s->snapshots + i;
1954 585f8587 bellard
        sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
1955 585f8587 bellard
        sn->l1_size = be32_to_cpu(h.l1_size);
1956 585f8587 bellard
        sn->vm_state_size = be32_to_cpu(h.vm_state_size);
1957 585f8587 bellard
        sn->date_sec = be32_to_cpu(h.date_sec);
1958 585f8587 bellard
        sn->date_nsec = be32_to_cpu(h.date_nsec);
1959 585f8587 bellard
        sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
1960 585f8587 bellard
        extra_data_size = be32_to_cpu(h.extra_data_size);
1961 585f8587 bellard
1962 585f8587 bellard
        id_str_size = be16_to_cpu(h.id_str_size);
1963 585f8587 bellard
        name_size = be16_to_cpu(h.name_size);
1964 585f8587 bellard
1965 585f8587 bellard
        offset += extra_data_size;
1966 585f8587 bellard
1967 585f8587 bellard
        sn->id_str = qemu_malloc(id_str_size + 1);
1968 585f8587 bellard
        if (bdrv_pread(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1969 585f8587 bellard
            goto fail;
1970 585f8587 bellard
        offset += id_str_size;
1971 585f8587 bellard
        sn->id_str[id_str_size] = '\0';
1972 585f8587 bellard
1973 585f8587 bellard
        sn->name = qemu_malloc(name_size + 1);
1974 585f8587 bellard
        if (bdrv_pread(s->hd, offset, sn->name, name_size) != name_size)
1975 585f8587 bellard
            goto fail;
1976 585f8587 bellard
        offset += name_size;
1977 585f8587 bellard
        sn->name[name_size] = '\0';
1978 585f8587 bellard
    }
1979 585f8587 bellard
    s->snapshots_size = offset - s->snapshots_offset;
1980 585f8587 bellard
    return 0;
1981 585f8587 bellard
 fail:
1982 585f8587 bellard
    qcow_free_snapshots(bs);
1983 585f8587 bellard
    return -1;
1984 585f8587 bellard
}
1985 585f8587 bellard
1986 585f8587 bellard
/* add at the end of the file a new list of snapshots */
1987 585f8587 bellard
static int qcow_write_snapshots(BlockDriverState *bs)
1988 585f8587 bellard
{
1989 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1990 585f8587 bellard
    QCowSnapshot *sn;
1991 585f8587 bellard
    QCowSnapshotHeader h;
1992 585f8587 bellard
    int i, name_size, id_str_size, snapshots_size;
1993 585f8587 bellard
    uint64_t data64;
1994 585f8587 bellard
    uint32_t data32;
1995 585f8587 bellard
    int64_t offset, snapshots_offset;
1996 585f8587 bellard
1997 585f8587 bellard
    /* compute the size of the snapshots */
1998 585f8587 bellard
    offset = 0;
1999 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
2000 585f8587 bellard
        sn = s->snapshots + i;
2001 585f8587 bellard
        offset = align_offset(offset, 8);
2002 585f8587 bellard
        offset += sizeof(h);
2003 585f8587 bellard
        offset += strlen(sn->id_str);
2004 585f8587 bellard
        offset += strlen(sn->name);
2005 585f8587 bellard
    }
2006 585f8587 bellard
    snapshots_size = offset;
2007 585f8587 bellard
2008 585f8587 bellard
    snapshots_offset = alloc_clusters(bs, snapshots_size);
2009 585f8587 bellard
    offset = snapshots_offset;
2010 3b46e624 ths
2011 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
2012 585f8587 bellard
        sn = s->snapshots + i;
2013 585f8587 bellard
        memset(&h, 0, sizeof(h));
2014 585f8587 bellard
        h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);
2015 585f8587 bellard
        h.l1_size = cpu_to_be32(sn->l1_size);
2016 585f8587 bellard
        h.vm_state_size = cpu_to_be32(sn->vm_state_size);
2017 585f8587 bellard
        h.date_sec = cpu_to_be32(sn->date_sec);
2018 585f8587 bellard
        h.date_nsec = cpu_to_be32(sn->date_nsec);
2019 585f8587 bellard
        h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);
2020 3b46e624 ths
2021 585f8587 bellard
        id_str_size = strlen(sn->id_str);
2022 585f8587 bellard
        name_size = strlen(sn->name);
2023 585f8587 bellard
        h.id_str_size = cpu_to_be16(id_str_size);
2024 585f8587 bellard
        h.name_size = cpu_to_be16(name_size);
2025 585f8587 bellard
        offset = align_offset(offset, 8);
2026 585f8587 bellard
        if (bdrv_pwrite(s->hd, offset, &h, sizeof(h)) != sizeof(h))
2027 585f8587 bellard
            goto fail;
2028 585f8587 bellard
        offset += sizeof(h);
2029 585f8587 bellard
        if (bdrv_pwrite(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
2030 585f8587 bellard
            goto fail;
2031 585f8587 bellard
        offset += id_str_size;
2032 585f8587 bellard
        if (bdrv_pwrite(s->hd, offset, sn->name, name_size) != name_size)
2033 585f8587 bellard
            goto fail;
2034 585f8587 bellard
        offset += name_size;
2035 585f8587 bellard
    }
2036 585f8587 bellard
2037 585f8587 bellard
    /* update the various header fields */
2038 585f8587 bellard
    data64 = cpu_to_be64(snapshots_offset);
2039 585f8587 bellard
    if (bdrv_pwrite(s->hd, offsetof(QCowHeader, snapshots_offset),
2040 585f8587 bellard
                    &data64, sizeof(data64)) != sizeof(data64))
2041 585f8587 bellard
        goto fail;
2042 585f8587 bellard
    data32 = cpu_to_be32(s->nb_snapshots);
2043 585f8587 bellard
    if (bdrv_pwrite(s->hd, offsetof(QCowHeader, nb_snapshots),
2044 585f8587 bellard
                    &data32, sizeof(data32)) != sizeof(data32))
2045 585f8587 bellard
        goto fail;
2046 585f8587 bellard
2047 585f8587 bellard
    /* free the old snapshot table */
2048 585f8587 bellard
    free_clusters(bs, s->snapshots_offset, s->snapshots_size);
2049 585f8587 bellard
    s->snapshots_offset = snapshots_offset;
2050 585f8587 bellard
    s->snapshots_size = snapshots_size;
2051 585f8587 bellard
    return 0;
2052 585f8587 bellard
 fail:
2053 585f8587 bellard
    return -1;
2054 585f8587 bellard
}
2055 585f8587 bellard
2056 585f8587 bellard
static void find_new_snapshot_id(BlockDriverState *bs,
2057 585f8587 bellard
                                 char *id_str, int id_str_size)
2058 585f8587 bellard
{
2059 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2060 585f8587 bellard
    QCowSnapshot *sn;
2061 585f8587 bellard
    int i, id, id_max = 0;
2062 585f8587 bellard
2063 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
2064 585f8587 bellard
        sn = s->snapshots + i;
2065 585f8587 bellard
        id = strtoul(sn->id_str, NULL, 10);
2066 585f8587 bellard
        if (id > id_max)
2067 585f8587 bellard
            id_max = id;
2068 585f8587 bellard
    }
2069 585f8587 bellard
    snprintf(id_str, id_str_size, "%d", id_max + 1);
2070 585f8587 bellard
}
2071 585f8587 bellard
2072 585f8587 bellard
static int find_snapshot_by_id(BlockDriverState *bs, const char *id_str)
2073 585f8587 bellard
{
2074 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2075 585f8587 bellard
    int i;
2076 585f8587 bellard
2077 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
2078 585f8587 bellard
        if (!strcmp(s->snapshots[i].id_str, id_str))
2079 585f8587 bellard
            return i;
2080 585f8587 bellard
    }
2081 585f8587 bellard
    return -1;
2082 585f8587 bellard
}
2083 585f8587 bellard
2084 585f8587 bellard
static int find_snapshot_by_id_or_name(BlockDriverState *bs, const char *name)
2085 585f8587 bellard
{
2086 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2087 585f8587 bellard
    int i, ret;
2088 3b46e624 ths
2089 585f8587 bellard
    ret = find_snapshot_by_id(bs, name);
2090 585f8587 bellard
    if (ret >= 0)
2091 585f8587 bellard
        return ret;
2092 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
2093 585f8587 bellard
        if (!strcmp(s->snapshots[i].name, name))
2094 585f8587 bellard
            return i;
2095 585f8587 bellard
    }
2096 585f8587 bellard
    return -1;
2097 585f8587 bellard
}
2098 585f8587 bellard
2099 585f8587 bellard
/* if no id is provided, a new one is constructed */
2100 5fafdf24 ths
static int qcow_snapshot_create(BlockDriverState *bs,
2101 585f8587 bellard
                                QEMUSnapshotInfo *sn_info)
2102 585f8587 bellard
{
2103 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2104 585f8587 bellard
    QCowSnapshot *snapshots1, sn1, *sn = &sn1;
2105 585f8587 bellard
    int i, ret;
2106 585f8587 bellard
    uint64_t *l1_table = NULL;
2107 3b46e624 ths
2108 585f8587 bellard
    memset(sn, 0, sizeof(*sn));
2109 585f8587 bellard
2110 585f8587 bellard
    if (sn_info->id_str[0] == '\0') {
2111 585f8587 bellard
        /* compute a new id */
2112 585f8587 bellard
        find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));
2113 585f8587 bellard
    }
2114 585f8587 bellard
2115 585f8587 bellard
    /* check that the ID is unique */
2116 585f8587 bellard
    if (find_snapshot_by_id(bs, sn_info->id_str) >= 0)
2117 585f8587 bellard
        return -ENOENT;
2118 585f8587 bellard
2119 585f8587 bellard
    sn->id_str = qemu_strdup(sn_info->id_str);
2120 585f8587 bellard
    if (!sn->id_str)
2121 585f8587 bellard
        goto fail;
2122 585f8587 bellard
    sn->name = qemu_strdup(sn_info->name);
2123 585f8587 bellard
    if (!sn->name)
2124 585f8587 bellard
        goto fail;
2125 585f8587 bellard
    sn->vm_state_size = sn_info->vm_state_size;
2126 585f8587 bellard
    sn->date_sec = sn_info->date_sec;
2127 585f8587 bellard
    sn->date_nsec = sn_info->date_nsec;
2128 585f8587 bellard
    sn->vm_clock_nsec = sn_info->vm_clock_nsec;
2129 585f8587 bellard
2130 585f8587 bellard
    ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);
2131 585f8587 bellard
    if (ret < 0)
2132 585f8587 bellard
        goto fail;
2133 585f8587 bellard
2134 585f8587 bellard
    /* create the L1 table of the snapshot */
2135 585f8587 bellard
    sn->l1_table_offset = alloc_clusters(bs, s->l1_size * sizeof(uint64_t));
2136 585f8587 bellard
    sn->l1_size = s->l1_size;
2137 585f8587 bellard
2138 585f8587 bellard
    l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
2139 585f8587 bellard
    for(i = 0; i < s->l1_size; i++) {
2140 585f8587 bellard
        l1_table[i] = cpu_to_be64(s->l1_table[i]);
2141 585f8587 bellard
    }
2142 585f8587 bellard
    if (bdrv_pwrite(s->hd, sn->l1_table_offset,
2143 5fafdf24 ths
                    l1_table, s->l1_size * sizeof(uint64_t)) !=
2144 585f8587 bellard
        (s->l1_size * sizeof(uint64_t)))
2145 585f8587 bellard
        goto fail;
2146 585f8587 bellard
    qemu_free(l1_table);
2147 585f8587 bellard
    l1_table = NULL;
2148 585f8587 bellard
2149 585f8587 bellard
    snapshots1 = qemu_malloc((s->nb_snapshots + 1) * sizeof(QCowSnapshot));
2150 63c75dcd malc
    if (s->snapshots) {
2151 63c75dcd malc
        memcpy(snapshots1, s->snapshots, s->nb_snapshots * sizeof(QCowSnapshot));
2152 63c75dcd malc
        qemu_free(s->snapshots);
2153 63c75dcd malc
    }
2154 585f8587 bellard
    s->snapshots = snapshots1;
2155 585f8587 bellard
    s->snapshots[s->nb_snapshots++] = *sn;
2156 585f8587 bellard
2157 585f8587 bellard
    if (qcow_write_snapshots(bs) < 0)
2158 585f8587 bellard
        goto fail;
2159 585f8587 bellard
#ifdef DEBUG_ALLOC
2160 585f8587 bellard
    check_refcounts(bs);
2161 585f8587 bellard
#endif
2162 585f8587 bellard
    return 0;
2163 585f8587 bellard
 fail:
2164 585f8587 bellard
    qemu_free(sn->name);
2165 585f8587 bellard
    qemu_free(l1_table);
2166 585f8587 bellard
    return -1;
2167 585f8587 bellard
}
2168 585f8587 bellard
2169 585f8587 bellard
/* copy the snapshot 'snapshot_name' into the current disk image */
2170 5fafdf24 ths
static int qcow_snapshot_goto(BlockDriverState *bs,
2171 585f8587 bellard
                              const char *snapshot_id)
2172 585f8587 bellard
{
2173 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2174 585f8587 bellard
    QCowSnapshot *sn;
2175 585f8587 bellard
    int i, snapshot_index, l1_size2;
2176 585f8587 bellard
2177 585f8587 bellard
    snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2178 585f8587 bellard
    if (snapshot_index < 0)
2179 585f8587 bellard
        return -ENOENT;
2180 585f8587 bellard
    sn = &s->snapshots[snapshot_index];
2181 585f8587 bellard
2182 585f8587 bellard
    if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, -1) < 0)
2183 585f8587 bellard
        goto fail;
2184 585f8587 bellard
2185 585f8587 bellard
    if (grow_l1_table(bs, sn->l1_size) < 0)
2186 585f8587 bellard
        goto fail;
2187 585f8587 bellard
2188 585f8587 bellard
    s->l1_size = sn->l1_size;
2189 585f8587 bellard
    l1_size2 = s->l1_size * sizeof(uint64_t);
2190 585f8587 bellard
    /* copy the snapshot l1 table to the current l1 table */
2191 5fafdf24 ths
    if (bdrv_pread(s->hd, sn->l1_table_offset,
2192 585f8587 bellard
                   s->l1_table, l1_size2) != l1_size2)
2193 585f8587 bellard
        goto fail;
2194 585f8587 bellard
    if (bdrv_pwrite(s->hd, s->l1_table_offset,
2195 585f8587 bellard
                    s->l1_table, l1_size2) != l1_size2)
2196 585f8587 bellard
        goto fail;
2197 585f8587 bellard
    for(i = 0;i < s->l1_size; i++) {
2198 585f8587 bellard
        be64_to_cpus(&s->l1_table[i]);
2199 585f8587 bellard
    }
2200 585f8587 bellard
2201 585f8587 bellard
    if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1) < 0)
2202 585f8587 bellard
        goto fail;
2203 585f8587 bellard
2204 585f8587 bellard
#ifdef DEBUG_ALLOC
2205 585f8587 bellard
    check_refcounts(bs);
2206 585f8587 bellard
#endif
2207 585f8587 bellard
    return 0;
2208 585f8587 bellard
 fail:
2209 585f8587 bellard
    return -EIO;
2210 585f8587 bellard
}
2211 585f8587 bellard
2212 585f8587 bellard
static int qcow_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2213 585f8587 bellard
{
2214 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2215 585f8587 bellard
    QCowSnapshot *sn;
2216 585f8587 bellard
    int snapshot_index, ret;
2217 3b46e624 ths
2218 585f8587 bellard
    snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2219 585f8587 bellard
    if (snapshot_index < 0)
2220 585f8587 bellard
        return -ENOENT;
2221 585f8587 bellard
    sn = &s->snapshots[snapshot_index];
2222 585f8587 bellard
2223 585f8587 bellard
    ret = update_snapshot_refcount(bs, sn->l1_table_offset, sn->l1_size, -1);
2224 585f8587 bellard
    if (ret < 0)
2225 585f8587 bellard
        return ret;
2226 585f8587 bellard
    /* must update the copied flag on the current cluster offsets */
2227 585f8587 bellard
    ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
2228 585f8587 bellard
    if (ret < 0)
2229 585f8587 bellard
        return ret;
2230 585f8587 bellard
    free_clusters(bs, sn->l1_table_offset, sn->l1_size * sizeof(uint64_t));
2231 585f8587 bellard
2232 585f8587 bellard
    qemu_free(sn->id_str);
2233 585f8587 bellard
    qemu_free(sn->name);
2234 585f8587 bellard
    memmove(sn, sn + 1, (s->nb_snapshots - snapshot_index - 1) * sizeof(*sn));
2235 585f8587 bellard
    s->nb_snapshots--;
2236 585f8587 bellard
    ret = qcow_write_snapshots(bs);
2237 585f8587 bellard
    if (ret < 0) {
2238 585f8587 bellard
        /* XXX: restore snapshot if error ? */
2239 585f8587 bellard
        return ret;
2240 585f8587 bellard
    }
2241 585f8587 bellard
#ifdef DEBUG_ALLOC
2242 585f8587 bellard
    check_refcounts(bs);
2243 585f8587 bellard
#endif
2244 585f8587 bellard
    return 0;
2245 585f8587 bellard
}
2246 585f8587 bellard
2247 5fafdf24 ths
static int qcow_snapshot_list(BlockDriverState *bs,
2248 585f8587 bellard
                              QEMUSnapshotInfo **psn_tab)
2249 585f8587 bellard
{
2250 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2251 585f8587 bellard
    QEMUSnapshotInfo *sn_tab, *sn_info;
2252 585f8587 bellard
    QCowSnapshot *sn;
2253 585f8587 bellard
    int i;
2254 585f8587 bellard
2255 585f8587 bellard
    sn_tab = qemu_mallocz(s->nb_snapshots * sizeof(QEMUSnapshotInfo));
2256 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
2257 585f8587 bellard
        sn_info = sn_tab + i;
2258 585f8587 bellard
        sn = s->snapshots + i;
2259 585f8587 bellard
        pstrcpy(sn_info->id_str, sizeof(sn_info->id_str),
2260 585f8587 bellard
                sn->id_str);
2261 585f8587 bellard
        pstrcpy(sn_info->name, sizeof(sn_info->name),
2262 585f8587 bellard
                sn->name);
2263 585f8587 bellard
        sn_info->vm_state_size = sn->vm_state_size;
2264 585f8587 bellard
        sn_info->date_sec = sn->date_sec;
2265 585f8587 bellard
        sn_info->date_nsec = sn->date_nsec;
2266 585f8587 bellard
        sn_info->vm_clock_nsec = sn->vm_clock_nsec;
2267 585f8587 bellard
    }
2268 585f8587 bellard
    *psn_tab = sn_tab;
2269 585f8587 bellard
    return s->nb_snapshots;
2270 585f8587 bellard
}
2271 585f8587 bellard
2272 585f8587 bellard
/*********************************************************/
2273 585f8587 bellard
/* refcount handling */
2274 585f8587 bellard
2275 585f8587 bellard
static int refcount_init(BlockDriverState *bs)
2276 585f8587 bellard
{
2277 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2278 585f8587 bellard
    int ret, refcount_table_size2, i;
2279 3b46e624 ths
2280 585f8587 bellard
    s->refcount_block_cache = qemu_malloc(s->cluster_size);
2281 585f8587 bellard
    refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
2282 585f8587 bellard
    s->refcount_table = qemu_malloc(refcount_table_size2);
2283 585f8587 bellard
    if (s->refcount_table_size > 0) {
2284 585f8587 bellard
        ret = bdrv_pread(s->hd, s->refcount_table_offset,
2285 585f8587 bellard
                         s->refcount_table, refcount_table_size2);
2286 585f8587 bellard
        if (ret != refcount_table_size2)
2287 585f8587 bellard
            goto fail;
2288 585f8587 bellard
        for(i = 0; i < s->refcount_table_size; i++)
2289 585f8587 bellard
            be64_to_cpus(&s->refcount_table[i]);
2290 585f8587 bellard
    }
2291 585f8587 bellard
    return 0;
2292 585f8587 bellard
 fail:
2293 585f8587 bellard
    return -ENOMEM;
2294 585f8587 bellard
}
2295 585f8587 bellard
2296 585f8587 bellard
static void refcount_close(BlockDriverState *bs)
2297 585f8587 bellard
{
2298 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2299 585f8587 bellard
    qemu_free(s->refcount_block_cache);
2300 585f8587 bellard
    qemu_free(s->refcount_table);
2301 585f8587 bellard
}
2302 585f8587 bellard
2303 585f8587 bellard
2304 5fafdf24 ths
static int load_refcount_block(BlockDriverState *bs,
2305 585f8587 bellard
                               int64_t refcount_block_offset)
2306 585f8587 bellard
{
2307 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2308 585f8587 bellard
    int ret;
2309 5fafdf24 ths
    ret = bdrv_pread(s->hd, refcount_block_offset, s->refcount_block_cache,
2310 585f8587 bellard
                     s->cluster_size);
2311 585f8587 bellard
    if (ret != s->cluster_size)
2312 585f8587 bellard
        return -EIO;
2313 585f8587 bellard
    s->refcount_block_cache_offset = refcount_block_offset;
2314 585f8587 bellard
    return 0;
2315 585f8587 bellard
}
2316 585f8587 bellard
2317 585f8587 bellard
static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
2318 585f8587 bellard
{
2319 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2320 585f8587 bellard
    int refcount_table_index, block_index;
2321 585f8587 bellard
    int64_t refcount_block_offset;
2322 585f8587 bellard
2323 585f8587 bellard
    refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2324 585f8587 bellard
    if (refcount_table_index >= s->refcount_table_size)
2325 585f8587 bellard
        return 0;
2326 585f8587 bellard
    refcount_block_offset = s->refcount_table[refcount_table_index];
2327 585f8587 bellard
    if (!refcount_block_offset)
2328 585f8587 bellard
        return 0;
2329 585f8587 bellard
    if (refcount_block_offset != s->refcount_block_cache_offset) {
2330 585f8587 bellard
        /* better than nothing: return allocated if read error */
2331 585f8587 bellard
        if (load_refcount_block(bs, refcount_block_offset) < 0)
2332 585f8587 bellard
            return 1;
2333 585f8587 bellard
    }
2334 5fafdf24 ths
    block_index = cluster_index &
2335 585f8587 bellard
        ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2336 585f8587 bellard
    return be16_to_cpu(s->refcount_block_cache[block_index]);
2337 585f8587 bellard
}
2338 585f8587 bellard
2339 585f8587 bellard
/* return < 0 if error */
2340 585f8587 bellard
static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)
2341 585f8587 bellard
{
2342 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2343 585f8587 bellard
    int i, nb_clusters;
2344 585f8587 bellard
2345 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, size);
2346 6db6c638 aliguori
retry:
2347 6db6c638 aliguori
    for(i = 0; i < nb_clusters; i++) {
2348 6db6c638 aliguori
        int64_t i = s->free_cluster_index++;
2349 6db6c638 aliguori
        if (get_refcount(bs, i) != 0)
2350 6db6c638 aliguori
            goto retry;
2351 6db6c638 aliguori
    }
2352 585f8587 bellard
#ifdef DEBUG_ALLOC2
2353 6db6c638 aliguori
    printf("alloc_clusters: size=%lld -> %lld\n",
2354 6db6c638 aliguori
            size,
2355 6db6c638 aliguori
            (s->free_cluster_index - nb_clusters) << s->cluster_bits);
2356 585f8587 bellard
#endif
2357 6db6c638 aliguori
    return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
2358 585f8587 bellard
}
2359 585f8587 bellard
2360 585f8587 bellard
static int64_t alloc_clusters(BlockDriverState *bs, int64_t size)
2361 585f8587 bellard
{
2362 585f8587 bellard
    int64_t offset;
2363 585f8587 bellard
2364 585f8587 bellard
    offset = alloc_clusters_noref(bs, size);
2365 585f8587 bellard
    update_refcount(bs, offset, size, 1);
2366 585f8587 bellard
    return offset;
2367 585f8587 bellard
}
2368 585f8587 bellard
2369 585f8587 bellard
/* only used to allocate compressed sectors. We try to allocate
2370 585f8587 bellard
   contiguous sectors. size must be <= cluster_size */
2371 585f8587 bellard
static int64_t alloc_bytes(BlockDriverState *bs, int size)
2372 585f8587 bellard
{
2373 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2374 585f8587 bellard
    int64_t offset, cluster_offset;
2375 585f8587 bellard
    int free_in_cluster;
2376 3b46e624 ths
2377 585f8587 bellard
    assert(size > 0 && size <= s->cluster_size);
2378 585f8587 bellard
    if (s->free_byte_offset == 0) {
2379 585f8587 bellard
        s->free_byte_offset = alloc_clusters(bs, s->cluster_size);
2380 585f8587 bellard
    }
2381 585f8587 bellard
 redo:
2382 5fafdf24 ths
    free_in_cluster = s->cluster_size -
2383 585f8587 bellard
        (s->free_byte_offset & (s->cluster_size - 1));
2384 585f8587 bellard
    if (size <= free_in_cluster) {
2385 585f8587 bellard
        /* enough space in current cluster */
2386 585f8587 bellard
        offset = s->free_byte_offset;
2387 585f8587 bellard
        s->free_byte_offset += size;
2388 585f8587 bellard
        free_in_cluster -= size;
2389 585f8587 bellard
        if (free_in_cluster == 0)
2390 585f8587 bellard
            s->free_byte_offset = 0;
2391 585f8587 bellard
        if ((offset & (s->cluster_size - 1)) != 0)
2392 585f8587 bellard
            update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2393 585f8587 bellard
    } else {
2394 585f8587 bellard
        offset = alloc_clusters(bs, s->cluster_size);
2395 585f8587 bellard
        cluster_offset = s->free_byte_offset & ~(s->cluster_size - 1);
2396 585f8587 bellard
        if ((cluster_offset + s->cluster_size) == offset) {
2397 585f8587 bellard
            /* we are lucky: contiguous data */
2398 585f8587 bellard
            offset = s->free_byte_offset;
2399 585f8587 bellard
            update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2400 585f8587 bellard
            s->free_byte_offset += size;
2401 585f8587 bellard
        } else {
2402 585f8587 bellard
            s->free_byte_offset = offset;
2403 585f8587 bellard
            goto redo;
2404 585f8587 bellard
        }
2405 585f8587 bellard
    }
2406 585f8587 bellard
    return offset;
2407 585f8587 bellard
}
2408 585f8587 bellard
2409 5fafdf24 ths
static void free_clusters(BlockDriverState *bs,
2410 585f8587 bellard
                          int64_t offset, int64_t size)
2411 585f8587 bellard
{
2412 585f8587 bellard
    update_refcount(bs, offset, size, -1);
2413 585f8587 bellard
}
2414 585f8587 bellard
2415 585f8587 bellard
static int grow_refcount_table(BlockDriverState *bs, int min_size)
2416 585f8587 bellard
{
2417 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2418 585f8587 bellard
    int new_table_size, new_table_size2, refcount_table_clusters, i, ret;
2419 585f8587 bellard
    uint64_t *new_table;
2420 585f8587 bellard
    int64_t table_offset;
2421 643e5399 aliguori
    uint8_t data[12];
2422 23be50f1 ths
    int old_table_size;
2423 23be50f1 ths
    int64_t old_table_offset;
2424 585f8587 bellard
2425 585f8587 bellard
    if (min_size <= s->refcount_table_size)
2426 585f8587 bellard
        return 0;
2427 585f8587 bellard
    /* compute new table size */
2428 585f8587 bellard
    refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2429 585f8587 bellard
    for(;;) {
2430 585f8587 bellard
        if (refcount_table_clusters == 0) {
2431 585f8587 bellard
            refcount_table_clusters = 1;
2432 585f8587 bellard
        } else {
2433 585f8587 bellard
            refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
2434 585f8587 bellard
        }
2435 585f8587 bellard
        new_table_size = refcount_table_clusters << (s->cluster_bits - 3);
2436 585f8587 bellard
        if (min_size <= new_table_size)
2437 585f8587 bellard
            break;
2438 585f8587 bellard
    }
2439 15e6690a bellard
#ifdef DEBUG_ALLOC2
2440 15e6690a bellard
    printf("grow_refcount_table from %d to %d\n",
2441 15e6690a bellard
           s->refcount_table_size,
2442 15e6690a bellard
           new_table_size);
2443 15e6690a bellard
#endif
2444 585f8587 bellard
    new_table_size2 = new_table_size * sizeof(uint64_t);
2445 585f8587 bellard
    new_table = qemu_mallocz(new_table_size2);
2446 5fafdf24 ths
    memcpy(new_table, s->refcount_table,
2447 585f8587 bellard
           s->refcount_table_size * sizeof(uint64_t));
2448 585f8587 bellard
    for(i = 0; i < s->refcount_table_size; i++)
2449 585f8587 bellard
        cpu_to_be64s(&new_table[i]);
2450 585f8587 bellard
    /* Note: we cannot update the refcount now to avoid recursion */
2451 585f8587 bellard
    table_offset = alloc_clusters_noref(bs, new_table_size2);
2452 585f8587 bellard
    ret = bdrv_pwrite(s->hd, table_offset, new_table, new_table_size2);
2453 5fafdf24 ths
    if (ret != new_table_size2)
2454 585f8587 bellard
        goto fail;
2455 585f8587 bellard
    for(i = 0; i < s->refcount_table_size; i++)
2456 585f8587 bellard
        be64_to_cpus(&new_table[i]);
2457 585f8587 bellard
2458 643e5399 aliguori
    cpu_to_be64w((uint64_t*)data, table_offset);
2459 643e5399 aliguori
    cpu_to_be32w((uint32_t*)(data + 8), refcount_table_clusters);
2460 585f8587 bellard
    if (bdrv_pwrite(s->hd, offsetof(QCowHeader, refcount_table_offset),
2461 643e5399 aliguori
                    data, sizeof(data)) != sizeof(data))
2462 585f8587 bellard
        goto fail;
2463 585f8587 bellard
    qemu_free(s->refcount_table);
2464 23be50f1 ths
    old_table_offset = s->refcount_table_offset;
2465 23be50f1 ths
    old_table_size = s->refcount_table_size;
2466 585f8587 bellard
    s->refcount_table = new_table;
2467 585f8587 bellard
    s->refcount_table_size = new_table_size;
2468 a4080ece ths
    s->refcount_table_offset = table_offset;
2469 585f8587 bellard
2470 585f8587 bellard
    update_refcount(bs, table_offset, new_table_size2, 1);
2471 23be50f1 ths
    free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));
2472 585f8587 bellard
    return 0;
2473 585f8587 bellard
 fail:
2474 585f8587 bellard
    free_clusters(bs, table_offset, new_table_size2);
2475 585f8587 bellard
    qemu_free(new_table);
2476 585f8587 bellard
    return -EIO;
2477 585f8587 bellard
}
2478 585f8587 bellard
2479 585f8587 bellard
/* addend must be 1 or -1 */
2480 585f8587 bellard
/* XXX: cache several refcount block clusters ? */
2481 5fafdf24 ths
static int update_cluster_refcount(BlockDriverState *bs,
2482 585f8587 bellard
                                   int64_t cluster_index,
2483 585f8587 bellard
                                   int addend)
2484 585f8587 bellard
{
2485 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2486 585f8587 bellard
    int64_t offset, refcount_block_offset;
2487 585f8587 bellard
    int ret, refcount_table_index, block_index, refcount;
2488 585f8587 bellard
    uint64_t data64;
2489 585f8587 bellard
2490 585f8587 bellard
    refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2491 585f8587 bellard
    if (refcount_table_index >= s->refcount_table_size) {
2492 585f8587 bellard
        if (addend < 0)
2493 585f8587 bellard
            return -EINVAL;
2494 585f8587 bellard
        ret = grow_refcount_table(bs, refcount_table_index + 1);
2495 585f8587 bellard
        if (ret < 0)
2496 585f8587 bellard
            return ret;
2497 585f8587 bellard
    }
2498 585f8587 bellard
    refcount_block_offset = s->refcount_table[refcount_table_index];
2499 585f8587 bellard
    if (!refcount_block_offset) {
2500 585f8587 bellard
        if (addend < 0)
2501 585f8587 bellard
            return -EINVAL;
2502 585f8587 bellard
        /* create a new refcount block */
2503 585f8587 bellard
        /* Note: we cannot update the refcount now to avoid recursion */
2504 585f8587 bellard
        offset = alloc_clusters_noref(bs, s->cluster_size);
2505 585f8587 bellard
        memset(s->refcount_block_cache, 0, s->cluster_size);
2506 585f8587 bellard
        ret = bdrv_pwrite(s->hd, offset, s->refcount_block_cache, s->cluster_size);
2507 585f8587 bellard
        if (ret != s->cluster_size)
2508 585f8587 bellard
            return -EINVAL;
2509 585f8587 bellard
        s->refcount_table[refcount_table_index] = offset;
2510 585f8587 bellard
        data64 = cpu_to_be64(offset);
2511 5fafdf24 ths
        ret = bdrv_pwrite(s->hd, s->refcount_table_offset +
2512 5fafdf24 ths
                          refcount_table_index * sizeof(uint64_t),
2513 585f8587 bellard
                          &data64, sizeof(data64));
2514 585f8587 bellard
        if (ret != sizeof(data64))
2515 585f8587 bellard
            return -EINVAL;
2516 585f8587 bellard
2517 585f8587 bellard
        refcount_block_offset = offset;
2518 585f8587 bellard
        s->refcount_block_cache_offset = offset;
2519 585f8587 bellard
        update_refcount(bs, offset, s->cluster_size, 1);
2520 585f8587 bellard
    } else {
2521 585f8587 bellard
        if (refcount_block_offset != s->refcount_block_cache_offset) {
2522 585f8587 bellard
            if (load_refcount_block(bs, refcount_block_offset) < 0)
2523 585f8587 bellard
                return -EIO;
2524 585f8587 bellard
        }
2525 585f8587 bellard
    }
2526 585f8587 bellard
    /* we can update the count and save it */
2527 5fafdf24 ths
    block_index = cluster_index &
2528 585f8587 bellard
        ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2529 585f8587 bellard
    refcount = be16_to_cpu(s->refcount_block_cache[block_index]);
2530 585f8587 bellard
    refcount += addend;
2531 585f8587 bellard
    if (refcount < 0 || refcount > 0xffff)
2532 585f8587 bellard
        return -EINVAL;
2533 585f8587 bellard
    if (refcount == 0 && cluster_index < s->free_cluster_index) {
2534 585f8587 bellard
        s->free_cluster_index = cluster_index;
2535 585f8587 bellard
    }
2536 585f8587 bellard
    s->refcount_block_cache[block_index] = cpu_to_be16(refcount);
2537 5fafdf24 ths
    if (bdrv_pwrite(s->hd,
2538 5fafdf24 ths
                    refcount_block_offset + (block_index << REFCOUNT_SHIFT),
2539 585f8587 bellard
                    &s->refcount_block_cache[block_index], 2) != 2)
2540 585f8587 bellard
        return -EIO;
2541 585f8587 bellard
    return refcount;
2542 585f8587 bellard
}
2543 585f8587 bellard
2544 5fafdf24 ths
static void update_refcount(BlockDriverState *bs,
2545 5fafdf24 ths
                            int64_t offset, int64_t length,
2546 585f8587 bellard
                            int addend)
2547 585f8587 bellard
{
2548 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2549 585f8587 bellard
    int64_t start, last, cluster_offset;
2550 585f8587 bellard
2551 585f8587 bellard
#ifdef DEBUG_ALLOC2
2552 5fafdf24 ths
    printf("update_refcount: offset=%lld size=%lld addend=%d\n",
2553 585f8587 bellard
           offset, length, addend);
2554 585f8587 bellard
#endif
2555 585f8587 bellard
    if (length <= 0)
2556 585f8587 bellard
        return;
2557 585f8587 bellard
    start = offset & ~(s->cluster_size - 1);
2558 585f8587 bellard
    last = (offset + length - 1) & ~(s->cluster_size - 1);
2559 5fafdf24 ths
    for(cluster_offset = start; cluster_offset <= last;
2560 585f8587 bellard
        cluster_offset += s->cluster_size) {
2561 585f8587 bellard
        update_cluster_refcount(bs, cluster_offset >> s->cluster_bits, addend);
2562 585f8587 bellard
    }
2563 585f8587 bellard
}
2564 585f8587 bellard
2565 e97fc193 aliguori
/*
2566 e97fc193 aliguori
 * Increases the refcount for a range of clusters in a given refcount table.
2567 e97fc193 aliguori
 * This is used to construct a temporary refcount table out of L1 and L2 tables
2568 e97fc193 aliguori
 * which can be compared the the refcount table saved in the image.
2569 e97fc193 aliguori
 *
2570 e97fc193 aliguori
 * Returns the number of errors in the image that were found
2571 e97fc193 aliguori
 */
2572 e97fc193 aliguori
static int inc_refcounts(BlockDriverState *bs,
2573 5fafdf24 ths
                          uint16_t *refcount_table,
2574 585f8587 bellard
                          int refcount_table_size,
2575 585f8587 bellard
                          int64_t offset, int64_t size)
2576 585f8587 bellard
{
2577 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2578 585f8587 bellard
    int64_t start, last, cluster_offset;
2579 585f8587 bellard
    int k;
2580 e97fc193 aliguori
    int errors = 0;
2581 3b46e624 ths
2582 585f8587 bellard
    if (size <= 0)
2583 e97fc193 aliguori
        return 0;
2584 585f8587 bellard
2585 585f8587 bellard
    start = offset & ~(s->cluster_size - 1);
2586 585f8587 bellard
    last = (offset + size - 1) & ~(s->cluster_size - 1);
2587 5fafdf24 ths
    for(cluster_offset = start; cluster_offset <= last;
2588 585f8587 bellard
        cluster_offset += s->cluster_size) {
2589 585f8587 bellard
        k = cluster_offset >> s->cluster_bits;
2590 585f8587 bellard
        if (k < 0 || k >= refcount_table_size) {
2591 8ddbc04f aliguori
            fprintf(stderr, "ERROR: invalid cluster offset=0x%" PRIx64 "\n",
2592 8ddbc04f aliguori
                cluster_offset);
2593 e97fc193 aliguori
            errors++;
2594 585f8587 bellard
        } else {
2595 585f8587 bellard
            if (++refcount_table[k] == 0) {
2596 8ddbc04f aliguori
                fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64
2597 8ddbc04f aliguori
                    "\n", cluster_offset);
2598 e97fc193 aliguori
                errors++;
2599 585f8587 bellard
            }
2600 585f8587 bellard
        }
2601 585f8587 bellard
    }
2602 e97fc193 aliguori
2603 e97fc193 aliguori
    return errors;
2604 585f8587 bellard
}
2605 585f8587 bellard
2606 ae2f14af aliguori
/*
2607 ae2f14af aliguori
 * Increases the refcount in the given refcount table for the all clusters
2608 ae2f14af aliguori
 * referenced in the L2 table. While doing so, performs some checks on L2
2609 ae2f14af aliguori
 * entries.
2610 ae2f14af aliguori
 *
2611 ae2f14af aliguori
 * Returns the number of errors found by the checks or -errno if an internal
2612 ae2f14af aliguori
 * error occurred.
2613 ae2f14af aliguori
 */
2614 ae2f14af aliguori
static int check_refcounts_l2(BlockDriverState *bs,
2615 ae2f14af aliguori
    uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,
2616 ae2f14af aliguori
    int check_copied)
2617 ae2f14af aliguori
{
2618 ae2f14af aliguori
    BDRVQcowState *s = bs->opaque;
2619 ae2f14af aliguori
    uint64_t *l2_table, offset;
2620 ae2f14af aliguori
    int i, l2_size, nb_csectors, refcount;
2621 ae2f14af aliguori
    int errors = 0;
2622 ae2f14af aliguori
2623 ae2f14af aliguori
    /* Read L2 table from disk */
2624 ae2f14af aliguori
    l2_size = s->l2_size * sizeof(uint64_t);
2625 ae2f14af aliguori
    l2_table = qemu_malloc(l2_size);
2626 ae2f14af aliguori
2627 ae2f14af aliguori
    if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
2628 ae2f14af aliguori
        goto fail;
2629 ae2f14af aliguori
2630 ae2f14af aliguori
    /* Do the actual checks */
2631 ae2f14af aliguori
    for(i = 0; i < s->l2_size; i++) {
2632 ae2f14af aliguori
        offset = be64_to_cpu(l2_table[i]);
2633 ae2f14af aliguori
        if (offset != 0) {
2634 ae2f14af aliguori
            if (offset & QCOW_OFLAG_COMPRESSED) {
2635 ae2f14af aliguori
                /* Compressed clusters don't have QCOW_OFLAG_COPIED */
2636 ae2f14af aliguori
                if (offset & QCOW_OFLAG_COPIED) {
2637 ae2f14af aliguori
                    fprintf(stderr, "ERROR: cluster %" PRId64 ": "
2638 ae2f14af aliguori
                        "copied flag must never be set for compressed "
2639 ae2f14af aliguori
                        "clusters\n", offset >> s->cluster_bits);
2640 ae2f14af aliguori
                    offset &= ~QCOW_OFLAG_COPIED;
2641 ae2f14af aliguori
                    errors++;
2642 ae2f14af aliguori
                }
2643 ae2f14af aliguori
2644 ae2f14af aliguori
                /* Mark cluster as used */
2645 ae2f14af aliguori
                nb_csectors = ((offset >> s->csize_shift) &
2646 ae2f14af aliguori
                               s->csize_mask) + 1;
2647 ae2f14af aliguori
                offset &= s->cluster_offset_mask;
2648 ae2f14af aliguori
                errors += inc_refcounts(bs, refcount_table,
2649 ae2f14af aliguori
                              refcount_table_size,
2650 ae2f14af aliguori
                              offset & ~511, nb_csectors * 512);
2651 ae2f14af aliguori
            } else {
2652 ae2f14af aliguori
                /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
2653 ae2f14af aliguori
                if (check_copied) {
2654 ae2f14af aliguori
                    uint64_t entry = offset;
2655 ae2f14af aliguori
                    offset &= ~QCOW_OFLAG_COPIED;
2656 ae2f14af aliguori
                    refcount = get_refcount(bs, offset >> s->cluster_bits);
2657 ae2f14af aliguori
                    if ((refcount == 1) != ((entry & QCOW_OFLAG_COPIED) != 0)) {
2658 ae2f14af aliguori
                        fprintf(stderr, "ERROR OFLAG_COPIED: offset=%"
2659 ae2f14af aliguori
                            PRIx64 " refcount=%d\n", entry, refcount);
2660 ae2f14af aliguori
                        errors++;
2661 ae2f14af aliguori
                    }
2662 ae2f14af aliguori
                }
2663 ae2f14af aliguori
2664 ae2f14af aliguori
                /* Mark cluster as used */
2665 ae2f14af aliguori
                offset &= ~QCOW_OFLAG_COPIED;
2666 ae2f14af aliguori
                errors += inc_refcounts(bs, refcount_table,
2667 ae2f14af aliguori
                              refcount_table_size,
2668 ae2f14af aliguori
                              offset, s->cluster_size);
2669 54c42368 aliguori
2670 54c42368 aliguori
                /* Correct offsets are cluster aligned */
2671 54c42368 aliguori
                if (offset & (s->cluster_size - 1)) {
2672 54c42368 aliguori
                    fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "
2673 54c42368 aliguori
                        "properly aligned; L2 entry corrupted.\n", offset);
2674 54c42368 aliguori
                    errors++;
2675 54c42368 aliguori
                }
2676 ae2f14af aliguori
            }
2677 ae2f14af aliguori
        }
2678 ae2f14af aliguori
    }
2679 ae2f14af aliguori
2680 ae2f14af aliguori
    qemu_free(l2_table);
2681 ae2f14af aliguori
    return errors;
2682 ae2f14af aliguori
2683 ae2f14af aliguori
fail:
2684 ae2f14af aliguori
    fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
2685 ae2f14af aliguori
    qemu_free(l2_table);
2686 ae2f14af aliguori
    return -EIO;
2687 ae2f14af aliguori
}
2688 ae2f14af aliguori
2689 ae2f14af aliguori
/*
2690 ae2f14af aliguori
 * Increases the refcount for the L1 table, its L2 tables and all referenced
2691 ae2f14af aliguori
 * clusters in the given refcount table. While doing so, performs some checks
2692 ae2f14af aliguori
 * on L1 and L2 entries.
2693 ae2f14af aliguori
 *
2694 ae2f14af aliguori
 * Returns the number of errors found by the checks or -errno if an internal
2695 ae2f14af aliguori
 * error occurred.
2696 ae2f14af aliguori
 */
2697 5fafdf24 ths
static int check_refcounts_l1(BlockDriverState *bs,
2698 5fafdf24 ths
                              uint16_t *refcount_table,
2699 585f8587 bellard
                              int refcount_table_size,
2700 585f8587 bellard
                              int64_t l1_table_offset, int l1_size,
2701 585f8587 bellard
                              int check_copied)
2702 585f8587 bellard
{
2703 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2704 ae2f14af aliguori
    uint64_t *l1_table, l2_offset, l1_size2;
2705 ae2f14af aliguori
    int i, refcount, ret;
2706 e97fc193 aliguori
    int errors = 0;
2707 585f8587 bellard
2708 585f8587 bellard
    l1_size2 = l1_size * sizeof(uint64_t);
2709 585f8587 bellard
2710 ae2f14af aliguori
    /* Mark L1 table as used */
2711 e97fc193 aliguori
    errors += inc_refcounts(bs, refcount_table, refcount_table_size,
2712 585f8587 bellard
                  l1_table_offset, l1_size2);
2713 585f8587 bellard
2714 ae2f14af aliguori
    /* Read L1 table entries from disk */
2715 585f8587 bellard
    l1_table = qemu_malloc(l1_size2);
2716 5fafdf24 ths
    if (bdrv_pread(s->hd, l1_table_offset,
2717 585f8587 bellard
                   l1_table, l1_size2) != l1_size2)
2718 585f8587 bellard
        goto fail;
2719 585f8587 bellard
    for(i = 0;i < l1_size; i++)
2720 585f8587 bellard
        be64_to_cpus(&l1_table[i]);
2721 3b46e624 ths
2722 ae2f14af aliguori
    /* Do the actual checks */
2723 585f8587 bellard
    for(i = 0; i < l1_size; i++) {
2724 585f8587 bellard
        l2_offset = l1_table[i];
2725 585f8587 bellard
        if (l2_offset) {
2726 ae2f14af aliguori
            /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
2727 585f8587 bellard
            if (check_copied) {
2728 ae2f14af aliguori
                refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED)
2729 ae2f14af aliguori
                    >> s->cluster_bits);
2730 585f8587 bellard
                if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
2731 8ddbc04f aliguori
                    fprintf(stderr, "ERROR OFLAG_COPIED: l2_offset=%" PRIx64
2732 8ddbc04f aliguori
                        " refcount=%d\n", l2_offset, refcount);
2733 e97fc193 aliguori
                    errors++;
2734 585f8587 bellard
                }
2735 585f8587 bellard
            }
2736 ae2f14af aliguori
2737 ae2f14af aliguori
            /* Mark L2 table as used */
2738 585f8587 bellard
            l2_offset &= ~QCOW_OFLAG_COPIED;
2739 e97fc193 aliguori
            errors += inc_refcounts(bs, refcount_table,
2740 585f8587 bellard
                          refcount_table_size,
2741 585f8587 bellard
                          l2_offset,
2742 585f8587 bellard
                          s->cluster_size);
2743 ae2f14af aliguori
2744 54c42368 aliguori
            /* L2 tables are cluster aligned */
2745 54c42368 aliguori
            if (l2_offset & (s->cluster_size - 1)) {
2746 54c42368 aliguori
                fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "
2747 54c42368 aliguori
                    "cluster aligned; L1 entry corrupted\n", l2_offset);
2748 54c42368 aliguori
                errors++;
2749 54c42368 aliguori
            }
2750 54c42368 aliguori
2751 ae2f14af aliguori
            /* Process and check L2 entries */
2752 ae2f14af aliguori
            ret = check_refcounts_l2(bs, refcount_table, refcount_table_size,
2753 ae2f14af aliguori
                l2_offset, check_copied);
2754 ae2f14af aliguori
            if (ret < 0) {
2755 ae2f14af aliguori
                goto fail;
2756 ae2f14af aliguori
            }
2757 ae2f14af aliguori
            errors += ret;
2758 585f8587 bellard
        }
2759 585f8587 bellard
    }
2760 585f8587 bellard
    qemu_free(l1_table);
2761 e97fc193 aliguori
    return errors;
2762 ae2f14af aliguori
2763 ae2f14af aliguori
fail:
2764 8ddbc04f aliguori
    fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
2765 585f8587 bellard
    qemu_free(l1_table);
2766 585f8587 bellard
    return -EIO;
2767 585f8587 bellard
}
2768 585f8587 bellard
2769 e97fc193 aliguori
/*
2770 e97fc193 aliguori
 * Checks an image for refcount consistency.
2771 e97fc193 aliguori
 *
2772 e97fc193 aliguori
 * Returns 0 if no errors are found, the number of errors in case the image is
2773 e97fc193 aliguori
 * detected as corrupted, and -errno when an internal error occured.
2774 e97fc193 aliguori
 */
2775 e97fc193 aliguori
static int check_refcounts(BlockDriverState *bs)
2776 585f8587 bellard
{
2777 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2778 585f8587 bellard
    int64_t size;
2779 585f8587 bellard
    int nb_clusters, refcount1, refcount2, i;
2780 585f8587 bellard
    QCowSnapshot *sn;
2781 585f8587 bellard
    uint16_t *refcount_table;
2782 e97fc193 aliguori
    int ret, errors = 0;
2783 585f8587 bellard
2784 585f8587 bellard
    size = bdrv_getlength(s->hd);
2785 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, size);
2786 585f8587 bellard
    refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));
2787 15e6690a bellard
2788 585f8587 bellard
    /* header */
2789 e97fc193 aliguori
    errors += inc_refcounts(bs, refcount_table, nb_clusters,
2790 585f8587 bellard
                  0, s->cluster_size);
2791 3b46e624 ths
2792 ae2f14af aliguori
    /* current L1 table */
2793 e97fc193 aliguori
    ret = check_refcounts_l1(bs, refcount_table, nb_clusters,
2794 585f8587 bellard
                       s->l1_table_offset, s->l1_size, 1);
2795 e97fc193 aliguori
    if (ret < 0) {
2796 e97fc193 aliguori
        return ret;
2797 e97fc193 aliguori
    }
2798 e97fc193 aliguori
    errors += ret;
2799 585f8587 bellard
2800 585f8587 bellard
    /* snapshots */
2801 585f8587 bellard
    for(i = 0; i < s->nb_snapshots; i++) {
2802 585f8587 bellard
        sn = s->snapshots + i;
2803 585f8587 bellard
        check_refcounts_l1(bs, refcount_table, nb_clusters,
2804 585f8587 bellard
                           sn->l1_table_offset, sn->l1_size, 0);
2805 585f8587 bellard
    }
2806 e97fc193 aliguori
    errors += inc_refcounts(bs, refcount_table, nb_clusters,
2807 585f8587 bellard
                  s->snapshots_offset, s->snapshots_size);
2808 585f8587 bellard
2809 585f8587 bellard
    /* refcount data */
2810 e97fc193 aliguori
    errors += inc_refcounts(bs, refcount_table, nb_clusters,
2811 5fafdf24 ths
                  s->refcount_table_offset,
2812 585f8587 bellard
                  s->refcount_table_size * sizeof(uint64_t));
2813 585f8587 bellard
    for(i = 0; i < s->refcount_table_size; i++) {
2814 585f8587 bellard
        int64_t offset;
2815 585f8587 bellard
        offset = s->refcount_table[i];
2816 585f8587 bellard
        if (offset != 0) {
2817 e97fc193 aliguori
            errors += inc_refcounts(bs, refcount_table, nb_clusters,
2818 585f8587 bellard
                          offset, s->cluster_size);
2819 585f8587 bellard
        }
2820 585f8587 bellard
    }
2821 585f8587 bellard
2822 585f8587 bellard
    /* compare ref counts */
2823 585f8587 bellard
    for(i = 0; i < nb_clusters; i++) {
2824 585f8587 bellard
        refcount1 = get_refcount(bs, i);
2825 585f8587 bellard
        refcount2 = refcount_table[i];
2826 e97fc193 aliguori
        if (refcount1 != refcount2) {
2827 8ddbc04f aliguori
            fprintf(stderr, "ERROR cluster %d refcount=%d reference=%d\n",
2828 585f8587 bellard
                   i, refcount1, refcount2);
2829 e97fc193 aliguori
            errors++;
2830 e97fc193 aliguori
        }
2831 585f8587 bellard
    }
2832 585f8587 bellard
2833 585f8587 bellard
    qemu_free(refcount_table);
2834 e97fc193 aliguori
2835 e97fc193 aliguori
    return errors;
2836 e97fc193 aliguori
}
2837 e97fc193 aliguori
2838 e97fc193 aliguori
static int qcow_check(BlockDriverState *bs)
2839 e97fc193 aliguori
{
2840 e97fc193 aliguori
    return check_refcounts(bs);
2841 585f8587 bellard
}
2842 585f8587 bellard
2843 585f8587 bellard
#if 0
2844 585f8587 bellard
static void dump_refcounts(BlockDriverState *bs)
2845 585f8587 bellard
{
2846 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
2847 585f8587 bellard
    int64_t nb_clusters, k, k1, size;
2848 585f8587 bellard
    int refcount;
2849 585f8587 bellard

2850 585f8587 bellard
    size = bdrv_getlength(s->hd);
2851 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, size);
2852 585f8587 bellard
    for(k = 0; k < nb_clusters;) {
2853 585f8587 bellard
        k1 = k;
2854 585f8587 bellard
        refcount = get_refcount(bs, k);
2855 585f8587 bellard
        k++;
2856 585f8587 bellard
        while (k < nb_clusters && get_refcount(bs, k) == refcount)
2857 585f8587 bellard
            k++;
2858 585f8587 bellard
        printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
2859 585f8587 bellard
    }
2860 585f8587 bellard
}
2861 585f8587 bellard
#endif
2862 585f8587 bellard
2863 178e08a5 aliguori
static int qcow_put_buffer(BlockDriverState *bs, const uint8_t *buf,
2864 178e08a5 aliguori
                           int64_t pos, int size)
2865 178e08a5 aliguori
{
2866 178e08a5 aliguori
    int growable = bs->growable;
2867 178e08a5 aliguori
2868 178e08a5 aliguori
    bs->growable = 1;
2869 178e08a5 aliguori
    bdrv_pwrite(bs, pos, buf, size);
2870 178e08a5 aliguori
    bs->growable = growable;
2871 178e08a5 aliguori
2872 178e08a5 aliguori
    return size;
2873 178e08a5 aliguori
}
2874 178e08a5 aliguori
2875 178e08a5 aliguori
static int qcow_get_buffer(BlockDriverState *bs, uint8_t *buf,
2876 178e08a5 aliguori
                           int64_t pos, int size)
2877 178e08a5 aliguori
{
2878 178e08a5 aliguori
    int growable = bs->growable;
2879 178e08a5 aliguori
    int ret;
2880 178e08a5 aliguori
2881 178e08a5 aliguori
    bs->growable = 1;
2882 178e08a5 aliguori
    ret = bdrv_pread(bs, pos, buf, size);
2883 178e08a5 aliguori
    bs->growable = growable;
2884 178e08a5 aliguori
2885 178e08a5 aliguori
    return ret;
2886 178e08a5 aliguori
}
2887 178e08a5 aliguori
2888 585f8587 bellard
BlockDriver bdrv_qcow2 = {
2889 e60f469c aurel32
    .format_name        = "qcow2",
2890 e60f469c aurel32
    .instance_size        = sizeof(BDRVQcowState),
2891 e60f469c aurel32
    .bdrv_probe                = qcow_probe,
2892 e60f469c aurel32
    .bdrv_open                = qcow_open,
2893 e60f469c aurel32
    .bdrv_close                = qcow_close,
2894 e60f469c aurel32
    .bdrv_create        = qcow_create,
2895 e60f469c aurel32
    .bdrv_flush                = qcow_flush,
2896 e60f469c aurel32
    .bdrv_is_allocated        = qcow_is_allocated,
2897 e60f469c aurel32
    .bdrv_set_key        = qcow_set_key,
2898 e60f469c aurel32
    .bdrv_make_empty        = qcow_make_empty,
2899 e60f469c aurel32
2900 f141eafe aliguori
    .bdrv_aio_readv        = qcow_aio_readv,
2901 f141eafe aliguori
    .bdrv_aio_writev        = qcow_aio_writev,
2902 e60f469c aurel32
    .bdrv_aio_cancel        = qcow_aio_cancel,
2903 e60f469c aurel32
    .aiocb_size                = sizeof(QCowAIOCB),
2904 585f8587 bellard
    .bdrv_write_compressed = qcow_write_compressed,
2905 585f8587 bellard
2906 585f8587 bellard
    .bdrv_snapshot_create = qcow_snapshot_create,
2907 e60f469c aurel32
    .bdrv_snapshot_goto        = qcow_snapshot_goto,
2908 585f8587 bellard
    .bdrv_snapshot_delete = qcow_snapshot_delete,
2909 e60f469c aurel32
    .bdrv_snapshot_list        = qcow_snapshot_list,
2910 e60f469c aurel32
    .bdrv_get_info        = qcow_get_info,
2911 f965509c aliguori
2912 178e08a5 aliguori
    .bdrv_put_buffer    = qcow_put_buffer,
2913 178e08a5 aliguori
    .bdrv_get_buffer    = qcow_get_buffer,
2914 178e08a5 aliguori
2915 f965509c aliguori
    .bdrv_create2 = qcow_create2,
2916 e97fc193 aliguori
    .bdrv_check = qcow_check,
2917 585f8587 bellard
};