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