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