Statistics
| Branch: | Revision:

root / block / qcow2.c @ 5493e33f

History | View | Annotate | Download (89.4 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 5efa9d5a Anthony Liguori
#include "module.h"
27 585f8587 bellard
#include <zlib.h>
28 585f8587 bellard
#include "aes.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 d4d698f0 Gleb Natapov
        /* if two concurrent writes happen to the same unallocated cluster
996 d4d698f0 Gleb Natapov
         * each write allocates separate cluster and writes data concurrently.
997 d4d698f0 Gleb Natapov
         * The first one to complete updates l2 table with pointer to its
998 d4d698f0 Gleb Natapov
         * cluster the second one has to do RMW (which is done above by
999 d4d698f0 Gleb Natapov
         * copy_sectors()), update l2 table with its cluster pointer and free
1000 d4d698f0 Gleb Natapov
         * old cluster. This is what this loop does */
1001 e976c6a1 aliguori
        if(l2_table[l2_index + i] != 0)
1002 e976c6a1 aliguori
            old_cluster[j++] = l2_table[l2_index + i];
1003 e976c6a1 aliguori
1004 e976c6a1 aliguori
        l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
1005 e976c6a1 aliguori
                    (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
1006 e976c6a1 aliguori
     }
1007 e976c6a1 aliguori
1008 e976c6a1 aliguori
    if (bdrv_pwrite(s->hd, l2_offset + l2_index * sizeof(uint64_t),
1009 e976c6a1 aliguori
                l2_table + l2_index, m->nb_clusters * sizeof(uint64_t)) !=
1010 e976c6a1 aliguori
            m->nb_clusters * sizeof(uint64_t))
1011 e976c6a1 aliguori
        goto err;
1012 e976c6a1 aliguori
1013 e976c6a1 aliguori
    for (i = 0; i < j; i++)
1014 d4d698f0 Gleb Natapov
        free_any_clusters(bs, be64_to_cpu(old_cluster[i]) & ~QCOW_OFLAG_COPIED,
1015 d4d698f0 Gleb Natapov
                          1);
1016 e976c6a1 aliguori
1017 e976c6a1 aliguori
    ret = 0;
1018 e976c6a1 aliguori
err:
1019 e976c6a1 aliguori
    qemu_free(old_cluster);
1020 e976c6a1 aliguori
    return ret;
1021 e976c6a1 aliguori
 }
1022 e976c6a1 aliguori
1023 52d893ec aliguori
/*
1024 52d893ec aliguori
 * alloc_cluster_offset
1025 52d893ec aliguori
 *
1026 52d893ec aliguori
 * For a given offset of the disk image, return cluster offset in
1027 52d893ec aliguori
 * qcow2 file.
1028 52d893ec aliguori
 *
1029 52d893ec aliguori
 * If the offset is not found, allocate a new cluster.
1030 52d893ec aliguori
 *
1031 52d893ec aliguori
 * Return the cluster offset if successful,
1032 52d893ec aliguori
 * Return 0, otherwise.
1033 52d893ec aliguori
 *
1034 52d893ec aliguori
 */
1035 52d893ec aliguori
1036 52d893ec aliguori
static uint64_t alloc_cluster_offset(BlockDriverState *bs,
1037 52d893ec aliguori
                                     uint64_t offset,
1038 095a9c58 aliguori
                                     int n_start, int n_end,
1039 e976c6a1 aliguori
                                     int *num, QCowL2Meta *m)
1040 52d893ec aliguori
{
1041 52d893ec aliguori
    BDRVQcowState *s = bs->opaque;
1042 52d893ec aliguori
    int l2_index, ret;
1043 52d893ec aliguori
    uint64_t l2_offset, *l2_table, cluster_offset;
1044 e976c6a1 aliguori
    int nb_clusters, i = 0;
1045 52d893ec aliguori
1046 52d893ec aliguori
    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
1047 52d893ec aliguori
    if (ret == 0)
1048 52d893ec aliguori
        return 0;
1049 52d893ec aliguori
1050 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, n_end << 9);
1051 6db6c638 aliguori
1052 e976c6a1 aliguori
    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1053 095a9c58 aliguori
1054 52d893ec aliguori
    cluster_offset = be64_to_cpu(l2_table[l2_index]);
1055 52d893ec aliguori
1056 095a9c58 aliguori
    /* We keep all QCOW_OFLAG_COPIED clusters */
1057 095a9c58 aliguori
1058 095a9c58 aliguori
    if (cluster_offset & QCOW_OFLAG_COPIED) {
1059 6db6c638 aliguori
        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
1060 ff4b91c2 aliguori
                &l2_table[l2_index], 0, 0);
1061 095a9c58 aliguori
1062 095a9c58 aliguori
        cluster_offset &= ~QCOW_OFLAG_COPIED;
1063 e976c6a1 aliguori
        m->nb_clusters = 0;
1064 095a9c58 aliguori
1065 095a9c58 aliguori
        goto out;
1066 095a9c58 aliguori
    }
1067 095a9c58 aliguori
1068 095a9c58 aliguori
    /* for the moment, multiple compressed clusters are not managed */
1069 095a9c58 aliguori
1070 095a9c58 aliguori
    if (cluster_offset & QCOW_OFLAG_COMPRESSED)
1071 095a9c58 aliguori
        nb_clusters = 1;
1072 095a9c58 aliguori
1073 bc352085 aliguori
    /* how many available clusters ? */
1074 095a9c58 aliguori
1075 bc352085 aliguori
    while (i < nb_clusters) {
1076 ab5ccbd6 aliguori
        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
1077 ff4b91c2 aliguori
                &l2_table[l2_index], i, 0);
1078 ab5ccbd6 aliguori
1079 ab5ccbd6 aliguori
        if(be64_to_cpu(l2_table[l2_index + i]))
1080 ab5ccbd6 aliguori
            break;
1081 ab5ccbd6 aliguori
1082 6db6c638 aliguori
        i += count_contiguous_free_clusters(nb_clusters - i,
1083 6db6c638 aliguori
                &l2_table[l2_index + i]);
1084 095a9c58 aliguori
1085 6db6c638 aliguori
        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
1086 095a9c58 aliguori
1087 6db6c638 aliguori
        if ((cluster_offset & QCOW_OFLAG_COPIED) ||
1088 bc352085 aliguori
                (cluster_offset & QCOW_OFLAG_COMPRESSED))
1089 6db6c638 aliguori
            break;
1090 095a9c58 aliguori
    }
1091 bc352085 aliguori
    nb_clusters = i;
1092 05203524 aliguori
1093 05203524 aliguori
    /* allocate a new cluster */
1094 05203524 aliguori
1095 095a9c58 aliguori
    cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);
1096 05203524 aliguori
1097 e976c6a1 aliguori
    /* save info needed for meta data update */
1098 e976c6a1 aliguori
    m->offset = offset;
1099 e976c6a1 aliguori
    m->n_start = n_start;
1100 e976c6a1 aliguori
    m->nb_clusters = nb_clusters;
1101 05203524 aliguori
1102 095a9c58 aliguori
out:
1103 e976c6a1 aliguori
    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
1104 e976c6a1 aliguori
1105 e976c6a1 aliguori
    *num = m->nb_available - n_start;
1106 095a9c58 aliguori
1107 585f8587 bellard
    return cluster_offset;
1108 585f8587 bellard
}
1109 585f8587 bellard
1110 5fafdf24 ths
static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
1111 585f8587 bellard
                             int nb_sectors, int *pnum)
1112 585f8587 bellard
{
1113 585f8587 bellard
    uint64_t cluster_offset;
1114 585f8587 bellard
1115 095a9c58 aliguori
    *pnum = nb_sectors;
1116 095a9c58 aliguori
    cluster_offset = get_cluster_offset(bs, sector_num << 9, pnum);
1117 095a9c58 aliguori
1118 585f8587 bellard
    return (cluster_offset != 0);
1119 585f8587 bellard
}
1120 585f8587 bellard
1121 585f8587 bellard
static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1122 585f8587 bellard
                             const uint8_t *buf, int buf_size)
1123 585f8587 bellard
{
1124 585f8587 bellard
    z_stream strm1, *strm = &strm1;
1125 585f8587 bellard
    int ret, out_len;
1126 585f8587 bellard
1127 585f8587 bellard
    memset(strm, 0, sizeof(*strm));
1128 585f8587 bellard
1129 585f8587 bellard
    strm->next_in = (uint8_t *)buf;
1130 585f8587 bellard
    strm->avail_in = buf_size;
1131 585f8587 bellard
    strm->next_out = out_buf;
1132 585f8587 bellard
    strm->avail_out = out_buf_size;
1133 585f8587 bellard
1134 585f8587 bellard
    ret = inflateInit2(strm, -12);
1135 585f8587 bellard
    if (ret != Z_OK)
1136 585f8587 bellard
        return -1;
1137 585f8587 bellard
    ret = inflate(strm, Z_FINISH);
1138 585f8587 bellard
    out_len = strm->next_out - out_buf;
1139 585f8587 bellard
    if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1140 585f8587 bellard
        out_len != out_buf_size) {
1141 585f8587 bellard
        inflateEnd(strm);
1142 585f8587 bellard
        return -1;
1143 585f8587 bellard
    }
1144 585f8587 bellard
    inflateEnd(strm);
1145 585f8587 bellard
    return 0;
1146 585f8587 bellard
}
1147 3b46e624 ths
1148 585f8587 bellard
static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
1149 585f8587 bellard
{
1150 585f8587 bellard
    int ret, csize, nb_csectors, sector_offset;
1151 585f8587 bellard
    uint64_t coffset;
1152 585f8587 bellard
1153 585f8587 bellard
    coffset = cluster_offset & s->cluster_offset_mask;
1154 585f8587 bellard
    if (s->cluster_cache_offset != coffset) {
1155 585f8587 bellard
        nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1156 585f8587 bellard
        sector_offset = coffset & 511;
1157 585f8587 bellard
        csize = nb_csectors * 512 - sector_offset;
1158 585f8587 bellard
        ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
1159 585f8587 bellard
        if (ret < 0) {
1160 585f8587 bellard
            return -1;
1161 585f8587 bellard
        }
1162 585f8587 bellard
        if (decompress_buffer(s->cluster_cache, s->cluster_size,
1163 585f8587 bellard
                              s->cluster_data + sector_offset, csize) < 0) {
1164 585f8587 bellard
            return -1;
1165 585f8587 bellard
        }
1166 585f8587 bellard
        s->cluster_cache_offset = coffset;
1167 585f8587 bellard
    }
1168 585f8587 bellard
    return 0;
1169 585f8587 bellard
}
1170 585f8587 bellard
1171 a9465922 bellard
/* handle reading after the end of the backing file */
1172 5fafdf24 ths
static int backing_read1(BlockDriverState *bs,
1173 a9465922 bellard
                         int64_t sector_num, uint8_t *buf, int nb_sectors)
1174 a9465922 bellard
{
1175 a9465922 bellard
    int n1;
1176 a9465922 bellard
    if ((sector_num + nb_sectors) <= bs->total_sectors)
1177 a9465922 bellard
        return nb_sectors;
1178 a9465922 bellard
    if (sector_num >= bs->total_sectors)
1179 a9465922 bellard
        n1 = 0;
1180 a9465922 bellard
    else
1181 a9465922 bellard
        n1 = bs->total_sectors - sector_num;
1182 a9465922 bellard
    memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
1183 a9465922 bellard
    return n1;
1184 a9465922 bellard
}
1185 a9465922 bellard
1186 5fafdf24 ths
static int qcow_read(BlockDriverState *bs, int64_t sector_num,
1187 585f8587 bellard
                     uint8_t *buf, int nb_sectors)
1188 585f8587 bellard
{
1189 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1190 a9465922 bellard
    int ret, index_in_cluster, n, n1;
1191 585f8587 bellard
    uint64_t cluster_offset;
1192 3b46e624 ths
1193 585f8587 bellard
    while (nb_sectors > 0) {
1194 095a9c58 aliguori
        n = nb_sectors;
1195 095a9c58 aliguori
        cluster_offset = get_cluster_offset(bs, sector_num << 9, &n);
1196 585f8587 bellard
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
1197 585f8587 bellard
        if (!cluster_offset) {
1198 585f8587 bellard
            if (bs->backing_hd) {
1199 585f8587 bellard
                /* read from the base image */
1200 a9465922 bellard
                n1 = backing_read1(bs->backing_hd, sector_num, buf, n);
1201 a9465922 bellard
                if (n1 > 0) {
1202 a9465922 bellard
                    ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
1203 a9465922 bellard
                    if (ret < 0)
1204 a9465922 bellard
                        return -1;
1205 a9465922 bellard
                }
1206 585f8587 bellard
            } else {
1207 585f8587 bellard
                memset(buf, 0, 512 * n);
1208 585f8587 bellard
            }
1209 585f8587 bellard
        } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
1210 585f8587 bellard
            if (decompress_cluster(s, cluster_offset) < 0)
1211 585f8587 bellard
                return -1;
1212 585f8587 bellard
            memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
1213 585f8587 bellard
        } else {
1214 585f8587 bellard
            ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1215 5fafdf24 ths
            if (ret != n * 512)
1216 585f8587 bellard
                return -1;
1217 585f8587 bellard
            if (s->crypt_method) {
1218 5fafdf24 ths
                encrypt_sectors(s, sector_num, buf, buf, n, 0,
1219 585f8587 bellard
                                &s->aes_decrypt_key);
1220 585f8587 bellard
            }
1221 585f8587 bellard
        }
1222 585f8587 bellard
        nb_sectors -= n;
1223 585f8587 bellard
        sector_num += n;
1224 585f8587 bellard
        buf += n * 512;
1225 585f8587 bellard
    }
1226 585f8587 bellard
    return 0;
1227 585f8587 bellard
}
1228 585f8587 bellard
1229 5fafdf24 ths
static int qcow_write(BlockDriverState *bs, int64_t sector_num,
1230 585f8587 bellard
                     const uint8_t *buf, int nb_sectors)
1231 585f8587 bellard
{
1232 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1233 585f8587 bellard
    int ret, index_in_cluster, n;
1234 585f8587 bellard
    uint64_t cluster_offset;
1235 095a9c58 aliguori
    int n_end;
1236 e976c6a1 aliguori
    QCowL2Meta l2meta;
1237 3b46e624 ths
1238 585f8587 bellard
    while (nb_sectors > 0) {
1239 585f8587 bellard
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
1240 095a9c58 aliguori
        n_end = index_in_cluster + nb_sectors;
1241 095a9c58 aliguori
        if (s->crypt_method &&
1242 095a9c58 aliguori
            n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1243 095a9c58 aliguori
            n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1244 52d893ec aliguori
        cluster_offset = alloc_cluster_offset(bs, sector_num << 9,
1245 05203524 aliguori
                                              index_in_cluster,
1246 e976c6a1 aliguori
                                              n_end, &n, &l2meta);
1247 585f8587 bellard
        if (!cluster_offset)
1248 585f8587 bellard
            return -1;
1249 585f8587 bellard
        if (s->crypt_method) {
1250 585f8587 bellard
            encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
1251 585f8587 bellard
                            &s->aes_encrypt_key);
1252 5fafdf24 ths
            ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512,
1253 585f8587 bellard
                              s->cluster_data, n * 512);
1254 585f8587 bellard
        } else {
1255 585f8587 bellard
            ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1256 585f8587 bellard
        }
1257 e976c6a1 aliguori
        if (ret != n * 512 || alloc_cluster_link_l2(bs, cluster_offset, &l2meta) < 0) {
1258 e976c6a1 aliguori
            free_any_clusters(bs, cluster_offset, l2meta.nb_clusters);
1259 585f8587 bellard
            return -1;
1260 e976c6a1 aliguori
        }
1261 585f8587 bellard
        nb_sectors -= n;
1262 585f8587 bellard
        sector_num += n;
1263 585f8587 bellard
        buf += n * 512;
1264 585f8587 bellard
    }
1265 585f8587 bellard
    s->cluster_cache_offset = -1; /* disable compressed cache */
1266 585f8587 bellard
    return 0;
1267 585f8587 bellard
}
1268 585f8587 bellard
1269 ce1a14dc pbrook
typedef struct QCowAIOCB {
1270 ce1a14dc pbrook
    BlockDriverAIOCB common;
1271 585f8587 bellard
    int64_t sector_num;
1272 f141eafe aliguori
    QEMUIOVector *qiov;
1273 585f8587 bellard
    uint8_t *buf;
1274 f141eafe aliguori
    void *orig_buf;
1275 585f8587 bellard
    int nb_sectors;
1276 585f8587 bellard
    int n;
1277 585f8587 bellard
    uint64_t cluster_offset;
1278 5fafdf24 ths
    uint8_t *cluster_data;
1279 585f8587 bellard
    BlockDriverAIOCB *hd_aiocb;
1280 c87c0672 aliguori
    struct iovec hd_iov;
1281 c87c0672 aliguori
    QEMUIOVector hd_qiov;
1282 1490791f aliguori
    QEMUBH *bh;
1283 e976c6a1 aliguori
    QCowL2Meta l2meta;
1284 585f8587 bellard
} QCowAIOCB;
1285 585f8587 bellard
1286 1490791f aliguori
static void qcow_aio_read_cb(void *opaque, int ret);
1287 1490791f aliguori
static void qcow_aio_read_bh(void *opaque)
1288 1490791f aliguori
{
1289 1490791f aliguori
    QCowAIOCB *acb = opaque;
1290 1490791f aliguori
    qemu_bh_delete(acb->bh);
1291 1490791f aliguori
    acb->bh = NULL;
1292 1490791f aliguori
    qcow_aio_read_cb(opaque, 0);
1293 1490791f aliguori
}
1294 1490791f aliguori
1295 a32ef786 aliguori
static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
1296 a32ef786 aliguori
{
1297 a32ef786 aliguori
    if (acb->bh)
1298 a32ef786 aliguori
        return -EIO;
1299 a32ef786 aliguori
1300 a32ef786 aliguori
    acb->bh = qemu_bh_new(cb, acb);
1301 a32ef786 aliguori
    if (!acb->bh)
1302 a32ef786 aliguori
        return -EIO;
1303 a32ef786 aliguori
1304 a32ef786 aliguori
    qemu_bh_schedule(acb->bh);
1305 a32ef786 aliguori
1306 a32ef786 aliguori
    return 0;
1307 a32ef786 aliguori
}
1308 a32ef786 aliguori
1309 585f8587 bellard
static void qcow_aio_read_cb(void *opaque, int ret)
1310 585f8587 bellard
{
1311 ce1a14dc pbrook
    QCowAIOCB *acb = opaque;
1312 ce1a14dc pbrook
    BlockDriverState *bs = acb->common.bs;
1313 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1314 a9465922 bellard
    int index_in_cluster, n1;
1315 585f8587 bellard
1316 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
1317 f141eafe aliguori
    if (ret < 0)
1318 f141eafe aliguori
        goto done;
1319 585f8587 bellard
1320 585f8587 bellard
    /* post process the read buffer */
1321 ce1a14dc pbrook
    if (!acb->cluster_offset) {
1322 585f8587 bellard
        /* nothing to do */
1323 ce1a14dc pbrook
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1324 585f8587 bellard
        /* nothing to do */
1325 585f8587 bellard
    } else {
1326 585f8587 bellard
        if (s->crypt_method) {
1327 5fafdf24 ths
            encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
1328 5fafdf24 ths
                            acb->n, 0,
1329 585f8587 bellard
                            &s->aes_decrypt_key);
1330 585f8587 bellard
        }
1331 585f8587 bellard
    }
1332 585f8587 bellard
1333 ce1a14dc pbrook
    acb->nb_sectors -= acb->n;
1334 ce1a14dc pbrook
    acb->sector_num += acb->n;
1335 ce1a14dc pbrook
    acb->buf += acb->n * 512;
1336 585f8587 bellard
1337 ce1a14dc pbrook
    if (acb->nb_sectors == 0) {
1338 585f8587 bellard
        /* request completed */
1339 f141eafe aliguori
        ret = 0;
1340 f141eafe aliguori
        goto done;
1341 585f8587 bellard
    }
1342 3b46e624 ths
1343 585f8587 bellard
    /* prepare next AIO request */
1344 095a9c58 aliguori
    acb->n = acb->nb_sectors;
1345 095a9c58 aliguori
    acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
1346 ce1a14dc pbrook
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1347 ce1a14dc pbrook
1348 ce1a14dc pbrook
    if (!acb->cluster_offset) {
1349 585f8587 bellard
        if (bs->backing_hd) {
1350 585f8587 bellard
            /* read from the base image */
1351 5fafdf24 ths
            n1 = backing_read1(bs->backing_hd, acb->sector_num,
1352 ce1a14dc pbrook
                               acb->buf, acb->n);
1353 a9465922 bellard
            if (n1 > 0) {
1354 3f4cb3d3 blueswir1
                acb->hd_iov.iov_base = (void *)acb->buf;
1355 c87c0672 aliguori
                acb->hd_iov.iov_len = acb->n * 512;
1356 c87c0672 aliguori
                qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1357 c87c0672 aliguori
                acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
1358 c87c0672 aliguori
                                    &acb->hd_qiov, acb->n,
1359 c87c0672 aliguori
                                    qcow_aio_read_cb, acb);
1360 ce1a14dc pbrook
                if (acb->hd_aiocb == NULL)
1361 f141eafe aliguori
                    goto done;
1362 a9465922 bellard
            } else {
1363 a32ef786 aliguori
                ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1364 a32ef786 aliguori
                if (ret < 0)
1365 f141eafe aliguori
                    goto done;
1366 a9465922 bellard
            }
1367 585f8587 bellard
        } else {
1368 585f8587 bellard
            /* Note: in this case, no need to wait */
1369 ce1a14dc pbrook
            memset(acb->buf, 0, 512 * acb->n);
1370 a32ef786 aliguori
            ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1371 a32ef786 aliguori
            if (ret < 0)
1372 f141eafe aliguori
                goto done;
1373 585f8587 bellard
        }
1374 ce1a14dc pbrook
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1375 585f8587 bellard
        /* add AIO support for compressed blocks ? */
1376 ce1a14dc pbrook
        if (decompress_cluster(s, acb->cluster_offset) < 0)
1377 f141eafe aliguori
            goto done;
1378 5fafdf24 ths
        memcpy(acb->buf,
1379 ce1a14dc pbrook
               s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
1380 a32ef786 aliguori
        ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1381 a32ef786 aliguori
        if (ret < 0)
1382 f141eafe aliguori
            goto done;
1383 585f8587 bellard
    } else {
1384 ce1a14dc pbrook
        if ((acb->cluster_offset & 511) != 0) {
1385 585f8587 bellard
            ret = -EIO;
1386 f141eafe aliguori
            goto done;
1387 585f8587 bellard
        }
1388 c87c0672 aliguori
1389 3f4cb3d3 blueswir1
        acb->hd_iov.iov_base = (void *)acb->buf;
1390 c87c0672 aliguori
        acb->hd_iov.iov_len = acb->n * 512;
1391 c87c0672 aliguori
        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1392 c87c0672 aliguori
        acb->hd_aiocb = bdrv_aio_readv(s->hd,
1393 5fafdf24 ths
                            (acb->cluster_offset >> 9) + index_in_cluster,
1394 c87c0672 aliguori
                            &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
1395 ce1a14dc pbrook
        if (acb->hd_aiocb == NULL)
1396 f141eafe aliguori
            goto done;
1397 f141eafe aliguori
    }
1398 f141eafe aliguori
1399 f141eafe aliguori
    return;
1400 f141eafe aliguori
done:
1401 f141eafe aliguori
    if (acb->qiov->niov > 1) {
1402 f141eafe aliguori
        qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
1403 f141eafe aliguori
        qemu_vfree(acb->orig_buf);
1404 585f8587 bellard
    }
1405 f141eafe aliguori
    acb->common.cb(acb->common.opaque, ret);
1406 f141eafe aliguori
    qemu_aio_release(acb);
1407 585f8587 bellard
}
1408 585f8587 bellard
1409 ce1a14dc pbrook
static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
1410 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1411 f141eafe aliguori
        BlockDriverCompletionFunc *cb, void *opaque, int is_write)
1412 585f8587 bellard
{
1413 ce1a14dc pbrook
    QCowAIOCB *acb;
1414 ce1a14dc pbrook
1415 ce1a14dc pbrook
    acb = qemu_aio_get(bs, cb, opaque);
1416 ce1a14dc pbrook
    if (!acb)
1417 ce1a14dc pbrook
        return NULL;
1418 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
1419 ce1a14dc pbrook
    acb->sector_num = sector_num;
1420 f141eafe aliguori
    acb->qiov = qiov;
1421 f141eafe aliguori
    if (qiov->niov > 1) {
1422 e268ca52 aliguori
        acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
1423 f141eafe aliguori
        if (is_write)
1424 f141eafe aliguori
            qemu_iovec_to_buffer(qiov, acb->buf);
1425 3f4cb3d3 blueswir1
    } else {
1426 3f4cb3d3 blueswir1
        acb->buf = (uint8_t *)qiov->iov->iov_base;
1427 3f4cb3d3 blueswir1
    }
1428 ce1a14dc pbrook
    acb->nb_sectors = nb_sectors;
1429 ce1a14dc pbrook
    acb->n = 0;
1430 ce1a14dc pbrook
    acb->cluster_offset = 0;
1431 e976c6a1 aliguori
    acb->l2meta.nb_clusters = 0;
1432 ce1a14dc pbrook
    return acb;
1433 ce1a14dc pbrook
}
1434 ce1a14dc pbrook
1435 f141eafe aliguori
static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
1436 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1437 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque)
1438 ce1a14dc pbrook
{
1439 ce1a14dc pbrook
    QCowAIOCB *acb;
1440 ce1a14dc pbrook
1441 f141eafe aliguori
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1442 ce1a14dc pbrook
    if (!acb)
1443 ce1a14dc pbrook
        return NULL;
1444 585f8587 bellard
1445 585f8587 bellard
    qcow_aio_read_cb(acb, 0);
1446 ce1a14dc pbrook
    return &acb->common;
1447 585f8587 bellard
}
1448 585f8587 bellard
1449 585f8587 bellard
static void qcow_aio_write_cb(void *opaque, int ret)
1450 585f8587 bellard
{
1451 ce1a14dc pbrook
    QCowAIOCB *acb = opaque;
1452 ce1a14dc pbrook
    BlockDriverState *bs = acb->common.bs;
1453 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1454 585f8587 bellard
    int index_in_cluster;
1455 585f8587 bellard
    const uint8_t *src_buf;
1456 095a9c58 aliguori
    int n_end;
1457 ce1a14dc pbrook
1458 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
1459 ce1a14dc pbrook
1460 f141eafe aliguori
    if (ret < 0)
1461 f141eafe aliguori
        goto done;
1462 585f8587 bellard
1463 e976c6a1 aliguori
    if (alloc_cluster_link_l2(bs, acb->cluster_offset, &acb->l2meta) < 0) {
1464 e976c6a1 aliguori
        free_any_clusters(bs, acb->cluster_offset, acb->l2meta.nb_clusters);
1465 f141eafe aliguori
        goto done;
1466 e976c6a1 aliguori
    }
1467 e976c6a1 aliguori
1468 ce1a14dc pbrook
    acb->nb_sectors -= acb->n;
1469 ce1a14dc pbrook
    acb->sector_num += acb->n;
1470 ce1a14dc pbrook
    acb->buf += acb->n * 512;
1471 585f8587 bellard
1472 ce1a14dc pbrook
    if (acb->nb_sectors == 0) {
1473 585f8587 bellard
        /* request completed */
1474 f141eafe aliguori
        ret = 0;
1475 f141eafe aliguori
        goto done;
1476 585f8587 bellard
    }
1477 3b46e624 ths
1478 ce1a14dc pbrook
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1479 095a9c58 aliguori
    n_end = index_in_cluster + acb->nb_sectors;
1480 095a9c58 aliguori
    if (s->crypt_method &&
1481 095a9c58 aliguori
        n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1482 095a9c58 aliguori
        n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1483 095a9c58 aliguori
1484 e976c6a1 aliguori
    acb->cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,
1485 05203524 aliguori
                                          index_in_cluster,
1486 e976c6a1 aliguori
                                          n_end, &acb->n, &acb->l2meta);
1487 e976c6a1 aliguori
    if (!acb->cluster_offset || (acb->cluster_offset & 511) != 0) {
1488 585f8587 bellard
        ret = -EIO;
1489 f141eafe aliguori
        goto done;
1490 585f8587 bellard
    }
1491 585f8587 bellard
    if (s->crypt_method) {
1492 ce1a14dc pbrook
        if (!acb->cluster_data) {
1493 095a9c58 aliguori
            acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
1494 095a9c58 aliguori
                                             s->cluster_size);
1495 585f8587 bellard
        }
1496 5fafdf24 ths
        encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
1497 ce1a14dc pbrook
                        acb->n, 1, &s->aes_encrypt_key);
1498 ce1a14dc pbrook
        src_buf = acb->cluster_data;
1499 585f8587 bellard
    } else {
1500 ce1a14dc pbrook
        src_buf = acb->buf;
1501 585f8587 bellard
    }
1502 c87c0672 aliguori
    acb->hd_iov.iov_base = (void *)src_buf;
1503 c87c0672 aliguori
    acb->hd_iov.iov_len = acb->n * 512;
1504 c87c0672 aliguori
    qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
1505 c87c0672 aliguori
    acb->hd_aiocb = bdrv_aio_writev(s->hd,
1506 c87c0672 aliguori
                                    (acb->cluster_offset >> 9) + index_in_cluster,
1507 c87c0672 aliguori
                                    &acb->hd_qiov, acb->n,
1508 c87c0672 aliguori
                                    qcow_aio_write_cb, acb);
1509 ce1a14dc pbrook
    if (acb->hd_aiocb == NULL)
1510 f141eafe aliguori
        goto done;
1511 f141eafe aliguori
1512 f141eafe aliguori
    return;
1513 f141eafe aliguori
1514 f141eafe aliguori
done:
1515 f141eafe aliguori
    if (acb->qiov->niov > 1)
1516 f141eafe aliguori
        qemu_vfree(acb->orig_buf);
1517 f141eafe aliguori
    acb->common.cb(acb->common.opaque, ret);
1518 f141eafe aliguori
    qemu_aio_release(acb);
1519 585f8587 bellard
}
1520 585f8587 bellard
1521 f141eafe aliguori
static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
1522 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1523 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque)
1524 585f8587 bellard
{
1525 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1526 ce1a14dc pbrook
    QCowAIOCB *acb;
1527 3b46e624 ths
1528 585f8587 bellard
    s->cluster_cache_offset = -1; /* disable compressed cache */
1529 585f8587 bellard
1530 f141eafe aliguori
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1531 ce1a14dc pbrook
    if (!acb)
1532 ce1a14dc pbrook
        return NULL;
1533 3b46e624 ths
1534 585f8587 bellard
    qcow_aio_write_cb(acb, 0);
1535 ce1a14dc pbrook
    return &acb->common;
1536 585f8587 bellard
}
1537 585f8587 bellard
1538 ce1a14dc pbrook
static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
1539 585f8587 bellard
{
1540 ce1a14dc pbrook
    QCowAIOCB *acb = (QCowAIOCB *)blockacb;
1541 ce1a14dc pbrook
    if (acb->hd_aiocb)
1542 ce1a14dc pbrook
        bdrv_aio_cancel(acb->hd_aiocb);
1543 ce1a14dc pbrook
    qemu_aio_release(acb);
1544 585f8587 bellard
}
1545 585f8587 bellard
1546 585f8587 bellard
static void qcow_close(BlockDriverState *bs)
1547 585f8587 bellard
{
1548 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1549 585f8587 bellard
    qemu_free(s->l1_table);
1550 585f8587 bellard
    qemu_free(s->l2_cache);
1551 585f8587 bellard
    qemu_free(s->cluster_cache);
1552 585f8587 bellard
    qemu_free(s->cluster_data);
1553 585f8587 bellard
    refcount_close(bs);
1554 585f8587 bellard
    bdrv_delete(s->hd);
1555 585f8587 bellard
}
1556 585f8587 bellard
1557 585f8587 bellard
/* XXX: use std qcow open function ? */
1558 585f8587 bellard
typedef struct QCowCreateState {
1559 585f8587 bellard
    int cluster_size;
1560 585f8587 bellard
    int cluster_bits;
1561 585f8587 bellard
    uint16_t *refcount_block;
1562 585f8587 bellard
    uint64_t *refcount_table;
1563 585f8587 bellard
    int64_t l1_table_offset;
1564 585f8587 bellard
    int64_t refcount_table_offset;
1565 585f8587 bellard
    int64_t refcount_block_offset;
1566 585f8587 bellard
} QCowCreateState;
1567 585f8587 bellard
1568 585f8587 bellard
static void create_refcount_update(QCowCreateState *s,
1569 585f8587 bellard
                                   int64_t offset, int64_t size)
1570 585f8587 bellard
{
1571 585f8587 bellard
    int refcount;
1572 585f8587 bellard
    int64_t start, last, cluster_offset;
1573 585f8587 bellard
    uint16_t *p;
1574 585f8587 bellard
1575 585f8587 bellard
    start = offset & ~(s->cluster_size - 1);
1576 585f8587 bellard
    last = (offset + size - 1)  & ~(s->cluster_size - 1);
1577 5fafdf24 ths
    for(cluster_offset = start; cluster_offset <= last;
1578 585f8587 bellard
        cluster_offset += s->cluster_size) {
1579 585f8587 bellard
        p = &s->refcount_block[cluster_offset >> s->cluster_bits];
1580 585f8587 bellard
        refcount = be16_to_cpu(*p);
1581 585f8587 bellard
        refcount++;
1582 585f8587 bellard
        *p = cpu_to_be16(refcount);
1583 585f8587 bellard
    }
1584 585f8587 bellard
}
1585 585f8587 bellard
1586 f965509c aliguori
static int qcow_create2(const char *filename, int64_t total_size,
1587 f965509c aliguori
                        const char *backing_file, const char *backing_format,
1588 f965509c aliguori
                        int flags)
1589 585f8587 bellard
{
1590 f965509c aliguori
1591 585f8587 bellard
    int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
1592 2d2431f0 aliguori
    int ref_clusters, backing_format_len = 0;
1593 585f8587 bellard
    QCowHeader header;
1594 585f8587 bellard
    uint64_t tmp, offset;
1595 585f8587 bellard
    QCowCreateState s1, *s = &s1;
1596 f965509c aliguori
    QCowExtension ext_bf = {0, 0};
1597 f965509c aliguori
1598 3b46e624 ths
1599 585f8587 bellard
    memset(s, 0, sizeof(*s));
1600 585f8587 bellard
1601 585f8587 bellard
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1602 585f8587 bellard
    if (fd < 0)
1603 585f8587 bellard
        return -1;
1604 585f8587 bellard
    memset(&header, 0, sizeof(header));
1605 585f8587 bellard
    header.magic = cpu_to_be32(QCOW_MAGIC);
1606 585f8587 bellard
    header.version = cpu_to_be32(QCOW_VERSION);
1607 585f8587 bellard
    header.size = cpu_to_be64(total_size * 512);
1608 585f8587 bellard
    header_size = sizeof(header);
1609 585f8587 bellard
    backing_filename_len = 0;
1610 585f8587 bellard
    if (backing_file) {
1611 f965509c aliguori
        if (backing_format) {
1612 f965509c aliguori
            ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
1613 f965509c aliguori
            backing_format_len = strlen(backing_format);
1614 f965509c aliguori
            ext_bf.len = (backing_format_len + 7) & ~7;
1615 f965509c aliguori
            header_size += ((sizeof(ext_bf) + ext_bf.len + 7) & ~7);
1616 f965509c aliguori
        }
1617 585f8587 bellard
        header.backing_file_offset = cpu_to_be64(header_size);
1618 585f8587 bellard
        backing_filename_len = strlen(backing_file);
1619 585f8587 bellard
        header.backing_file_size = cpu_to_be32(backing_filename_len);
1620 585f8587 bellard
        header_size += backing_filename_len;
1621 585f8587 bellard
    }
1622 585f8587 bellard
    s->cluster_bits = 12;  /* 4 KB clusters */
1623 585f8587 bellard
    s->cluster_size = 1 << s->cluster_bits;
1624 585f8587 bellard
    header.cluster_bits = cpu_to_be32(s->cluster_bits);
1625 585f8587 bellard
    header_size = (header_size + 7) & ~7;
1626 ec36ba14 ths
    if (flags & BLOCK_FLAG_ENCRYPT) {
1627 585f8587 bellard
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1628 585f8587 bellard
    } else {
1629 585f8587 bellard
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1630 585f8587 bellard
    }
1631 585f8587 bellard
    l2_bits = s->cluster_bits - 3;
1632 585f8587 bellard
    shift = s->cluster_bits + l2_bits;
1633 585f8587 bellard
    l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
1634 585f8587 bellard
    offset = align_offset(header_size, s->cluster_size);
1635 585f8587 bellard
    s->l1_table_offset = offset;
1636 585f8587 bellard
    header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
1637 585f8587 bellard
    header.l1_size = cpu_to_be32(l1_size);
1638 15e6690a bellard
    offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
1639 585f8587 bellard
1640 585f8587 bellard
    s->refcount_table = qemu_mallocz(s->cluster_size);
1641 3b46e624 ths
1642 585f8587 bellard
    s->refcount_table_offset = offset;
1643 585f8587 bellard
    header.refcount_table_offset = cpu_to_be64(offset);
1644 585f8587 bellard
    header.refcount_table_clusters = cpu_to_be32(1);
1645 585f8587 bellard
    offset += s->cluster_size;
1646 585f8587 bellard
    s->refcount_block_offset = offset;
1647 2d2431f0 aliguori
1648 2d2431f0 aliguori
    /* count how many refcount blocks needed */
1649 2d2431f0 aliguori
    tmp = offset >> s->cluster_bits;
1650 2d2431f0 aliguori
    ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
1651 2d2431f0 aliguori
    for (i=0; i < ref_clusters; i++) {
1652 2d2431f0 aliguori
        s->refcount_table[i] = cpu_to_be64(offset);
1653 2d2431f0 aliguori
        offset += s->cluster_size;
1654 2d2431f0 aliguori
    }
1655 2d2431f0 aliguori
1656 2d2431f0 aliguori
    s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
1657 585f8587 bellard
1658 585f8587 bellard
    /* update refcounts */
1659 585f8587 bellard
    create_refcount_update(s, 0, header_size);
1660 15e6690a bellard
    create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
1661 585f8587 bellard
    create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
1662 2d2431f0 aliguori
    create_refcount_update(s, s->refcount_block_offset, ref_clusters * s->cluster_size);
1663 3b46e624 ths
1664 585f8587 bellard
    /* write all the data */
1665 585f8587 bellard
    write(fd, &header, sizeof(header));
1666 585f8587 bellard
    if (backing_file) {
1667 f965509c aliguori
        if (backing_format_len) {
1668 f965509c aliguori
            char zero[16];
1669 f965509c aliguori
            int d = ext_bf.len - backing_format_len;
1670 f965509c aliguori
1671 f965509c aliguori
            memset(zero, 0, sizeof(zero));
1672 f965509c aliguori
            cpu_to_be32s(&ext_bf.magic);
1673 f965509c aliguori
            cpu_to_be32s(&ext_bf.len);
1674 f965509c aliguori
            write(fd, &ext_bf, sizeof(ext_bf));
1675 f965509c aliguori
            write(fd, backing_format, backing_format_len);
1676 f965509c aliguori
            if (d>0) {
1677 f965509c aliguori
                write(fd, zero, d);
1678 f965509c aliguori
            }
1679 f965509c aliguori
        }
1680 585f8587 bellard
        write(fd, backing_file, backing_filename_len);
1681 585f8587 bellard
    }
1682 585f8587 bellard
    lseek(fd, s->l1_table_offset, SEEK_SET);
1683 585f8587 bellard
    tmp = 0;
1684 585f8587 bellard
    for(i = 0;i < l1_size; i++) {
1685 585f8587 bellard
        write(fd, &tmp, sizeof(tmp));
1686 585f8587 bellard
    }
1687 585f8587 bellard
    lseek(fd, s->refcount_table_offset, SEEK_SET);
1688 585f8587 bellard
    write(fd, s->refcount_table, s->cluster_size);
1689 3b46e624 ths
1690 585f8587 bellard
    lseek(fd, s->refcount_block_offset, SEEK_SET);
1691 2d2431f0 aliguori
    write(fd, s->refcount_block, ref_clusters * s->cluster_size);
1692 585f8587 bellard
1693 585f8587 bellard
    qemu_free(s->refcount_table);
1694 585f8587 bellard
    qemu_free(s->refcount_block);
1695 585f8587 bellard
    close(fd);
1696 585f8587 bellard
    return 0;
1697 585f8587 bellard
}
1698 585f8587 bellard
1699 f965509c aliguori
static int qcow_create(const char *filename, int64_t total_size,
1700 f965509c aliguori
                       const char *backing_file, int flags)
1701 f965509c aliguori
{
1702 f965509c aliguori
    return qcow_create2(filename, total_size, backing_file, NULL, flags);
1703 f965509c aliguori
}
1704 f965509c aliguori
1705 585f8587 bellard
static int qcow_make_empty(BlockDriverState *bs)
1706 585f8587 bellard
{
1707 585f8587 bellard
#if 0
1708 585f8587 bellard
    /* XXX: not correct */
1709 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1710 585f8587 bellard
    uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1711 585f8587 bellard
    int ret;
1712 585f8587 bellard

1713 585f8587 bellard
    memset(s->l1_table, 0, l1_length);
1714 585f8587 bellard
    if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1715 ac674887 aliguori
        return -1;
1716 585f8587 bellard
    ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1717 585f8587 bellard
    if (ret < 0)
1718 585f8587 bellard
        return ret;
1719 3b46e624 ths

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

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