Statistics
| Branch: | Revision:

root / block / qcow2.c @ 73c632ed

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

1773 585f8587 bellard
    memset(s->l1_table, 0, l1_length);
1774 585f8587 bellard
    if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1775 ac674887 aliguori
        return -1;
1776 585f8587 bellard
    ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1777 585f8587 bellard
    if (ret < 0)
1778 585f8587 bellard
        return ret;
1779 3b46e624 ths

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

2922 585f8587 bellard
    size = bdrv_getlength(s->hd);
2923 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, size);
2924 585f8587 bellard
    for(k = 0; k < nb_clusters;) {
2925 585f8587 bellard
        k1 = k;
2926 585f8587 bellard
        refcount = get_refcount(bs, k);
2927 585f8587 bellard
        k++;
2928 585f8587 bellard
        while (k < nb_clusters && get_refcount(bs, k) == refcount)
2929 585f8587 bellard
            k++;
2930 585f8587 bellard
        printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
2931 585f8587 bellard
    }
2932 585f8587 bellard
}
2933 585f8587 bellard
#endif
2934 585f8587 bellard
2935 178e08a5 aliguori
static int qcow_put_buffer(BlockDriverState *bs, const uint8_t *buf,
2936 178e08a5 aliguori
                           int64_t pos, int size)
2937 178e08a5 aliguori
{
2938 178e08a5 aliguori
    int growable = bs->growable;
2939 178e08a5 aliguori
2940 178e08a5 aliguori
    bs->growable = 1;
2941 178e08a5 aliguori
    bdrv_pwrite(bs, pos, buf, size);
2942 178e08a5 aliguori
    bs->growable = growable;
2943 178e08a5 aliguori
2944 178e08a5 aliguori
    return size;
2945 178e08a5 aliguori
}
2946 178e08a5 aliguori
2947 178e08a5 aliguori
static int qcow_get_buffer(BlockDriverState *bs, uint8_t *buf,
2948 178e08a5 aliguori
                           int64_t pos, int size)
2949 178e08a5 aliguori
{
2950 178e08a5 aliguori
    int growable = bs->growable;
2951 178e08a5 aliguori
    int ret;
2952 178e08a5 aliguori
2953 178e08a5 aliguori
    bs->growable = 1;
2954 178e08a5 aliguori
    ret = bdrv_pread(bs, pos, buf, size);
2955 178e08a5 aliguori
    bs->growable = growable;
2956 178e08a5 aliguori
2957 178e08a5 aliguori
    return ret;
2958 178e08a5 aliguori
}
2959 178e08a5 aliguori
2960 0e7e1989 Kevin Wolf
static QEMUOptionParameter qcow_create_options[] = {
2961 0e7e1989 Kevin Wolf
    { BLOCK_OPT_SIZE,           OPT_SIZE },
2962 0e7e1989 Kevin Wolf
    { BLOCK_OPT_BACKING_FILE,   OPT_STRING },
2963 0e7e1989 Kevin Wolf
    { BLOCK_OPT_BACKING_FMT,    OPT_STRING },
2964 0e7e1989 Kevin Wolf
    { BLOCK_OPT_ENCRYPT,        OPT_FLAG },
2965 73c632ed Kevin Wolf
    { BLOCK_OPT_CLUSTER_SIZE,   OPT_SIZE },
2966 0e7e1989 Kevin Wolf
    { NULL }
2967 0e7e1989 Kevin Wolf
};
2968 0e7e1989 Kevin Wolf
2969 5efa9d5a Anthony Liguori
static BlockDriver bdrv_qcow2 = {
2970 e60f469c aurel32
    .format_name        = "qcow2",
2971 e60f469c aurel32
    .instance_size        = sizeof(BDRVQcowState),
2972 e60f469c aurel32
    .bdrv_probe                = qcow_probe,
2973 e60f469c aurel32
    .bdrv_open                = qcow_open,
2974 e60f469c aurel32
    .bdrv_close                = qcow_close,
2975 e60f469c aurel32
    .bdrv_create        = qcow_create,
2976 e60f469c aurel32
    .bdrv_flush                = qcow_flush,
2977 e60f469c aurel32
    .bdrv_is_allocated        = qcow_is_allocated,
2978 e60f469c aurel32
    .bdrv_set_key        = qcow_set_key,
2979 e60f469c aurel32
    .bdrv_make_empty        = qcow_make_empty,
2980 e60f469c aurel32
2981 f141eafe aliguori
    .bdrv_aio_readv        = qcow_aio_readv,
2982 f141eafe aliguori
    .bdrv_aio_writev        = qcow_aio_writev,
2983 e60f469c aurel32
    .bdrv_aio_cancel        = qcow_aio_cancel,
2984 e60f469c aurel32
    .aiocb_size                = sizeof(QCowAIOCB),
2985 585f8587 bellard
    .bdrv_write_compressed = qcow_write_compressed,
2986 585f8587 bellard
2987 585f8587 bellard
    .bdrv_snapshot_create = qcow_snapshot_create,
2988 e60f469c aurel32
    .bdrv_snapshot_goto        = qcow_snapshot_goto,
2989 585f8587 bellard
    .bdrv_snapshot_delete = qcow_snapshot_delete,
2990 e60f469c aurel32
    .bdrv_snapshot_list        = qcow_snapshot_list,
2991 e60f469c aurel32
    .bdrv_get_info        = qcow_get_info,
2992 f965509c aliguori
2993 178e08a5 aliguori
    .bdrv_put_buffer    = qcow_put_buffer,
2994 178e08a5 aliguori
    .bdrv_get_buffer    = qcow_get_buffer,
2995 178e08a5 aliguori
2996 0e7e1989 Kevin Wolf
    .create_options = qcow_create_options,
2997 e97fc193 aliguori
    .bdrv_check = qcow_check,
2998 585f8587 bellard
};
2999 5efa9d5a Anthony Liguori
3000 5efa9d5a Anthony Liguori
static void bdrv_qcow2_init(void)
3001 5efa9d5a Anthony Liguori
{
3002 5efa9d5a Anthony Liguori
    bdrv_register(&bdrv_qcow2);
3003 5efa9d5a Anthony Liguori
}
3004 5efa9d5a Anthony Liguori
3005 5efa9d5a Anthony Liguori
block_init(bdrv_qcow2_init);