Revert r6405
[sniper_test.git] / block-qcow2.c
blob0a1ddeb6e2e16a3aa655cce8907e7abf534fb185
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu-common.h"
25 #include "block_int.h"
26 #include <zlib.h>
27 #include "aes.h"
28 #include <assert.h>
31 Differences with QCOW:
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.
37 - Size of compressed clusters is stored in sectors to reduce bit usage
38 in the cluster offsets.
39 - Support for storing additional data (such as the VM state) in the
40 snapshots.
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.
46 //#define DEBUG_ALLOC
47 //#define DEBUG_ALLOC2
49 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
50 #define QCOW_VERSION 2
52 #define QCOW_CRYPT_NONE 0
53 #define QCOW_CRYPT_AES 1
55 #define QCOW_MAX_CRYPT_CLUSTERS 32
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)
62 #define REFCOUNT_SHIFT 1 /* refcount size is 2 bytes */
64 typedef 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;
80 typedef struct __attribute__((packed)) QCowSnapshotHeader {
81 /* header is 8 byte aligned */
82 uint64_t l1_table_offset;
84 uint32_t l1_size;
85 uint16_t id_str_size;
86 uint16_t name_size;
88 uint32_t date_sec;
89 uint32_t date_nsec;
91 uint64_t vm_clock_nsec;
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;
100 #define L2_CACHE_SIZE 16
102 typedef 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;
113 typedef 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;
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;
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;
147 int64_t highest_alloc; /* highest cluester allocated (in clusters) */
149 uint64_t snapshots_offset;
150 int snapshots_size;
151 int nb_snapshots;
152 QCowSnapshot *snapshots;
153 } BDRVQcowState;
155 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset);
156 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
157 uint8_t *buf, int nb_sectors);
158 static int qcow_read_snapshots(BlockDriverState *bs);
159 static void qcow_free_snapshots(BlockDriverState *bs);
160 static int refcount_init(BlockDriverState *bs);
161 static void refcount_close(BlockDriverState *bs);
162 static int get_refcount(BlockDriverState *bs, int64_t cluster_index);
163 static int update_cluster_refcount(BlockDriverState *bs,
164 int64_t cluster_index,
165 int addend);
166 static void update_refcount(BlockDriverState *bs,
167 int64_t offset, int64_t length,
168 int addend);
169 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size);
170 static int64_t alloc_bytes(BlockDriverState *bs, int size);
171 static void free_clusters(BlockDriverState *bs,
172 int64_t offset, int64_t size);
173 #ifdef DEBUG_ALLOC
174 static void check_refcounts(BlockDriverState *bs);
175 #endif
176 static void scan_refcount(BlockDriverState *bs, int64_t *high);
179 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
181 const QCowHeader *cow_header = (const void *)buf;
183 if (buf_size >= sizeof(QCowHeader) &&
184 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
185 be32_to_cpu(cow_header->version) == QCOW_VERSION)
186 return 100;
187 else
188 return 0;
191 static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
193 BDRVQcowState *s = bs->opaque;
194 int len, i, shift, ret;
195 QCowHeader header;
197 /* Performance is terrible right now with cache=writethrough due mainly
198 * to reference count updates. If the user does not explicitly specify
199 * a caching type, force to writeback caching.
201 if ((flags & BDRV_O_CACHE_DEF)) {
202 flags |= BDRV_O_CACHE_WB;
203 flags &= ~BDRV_O_CACHE_DEF;
205 ret = bdrv_file_open(&s->hd, filename, flags);
206 if (ret < 0)
207 return ret;
208 if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
209 goto fail;
210 be32_to_cpus(&header.magic);
211 be32_to_cpus(&header.version);
212 be64_to_cpus(&header.backing_file_offset);
213 be32_to_cpus(&header.backing_file_size);
214 be64_to_cpus(&header.size);
215 be32_to_cpus(&header.cluster_bits);
216 be32_to_cpus(&header.crypt_method);
217 be64_to_cpus(&header.l1_table_offset);
218 be32_to_cpus(&header.l1_size);
219 be64_to_cpus(&header.refcount_table_offset);
220 be32_to_cpus(&header.refcount_table_clusters);
221 be64_to_cpus(&header.snapshots_offset);
222 be32_to_cpus(&header.nb_snapshots);
224 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
225 goto fail;
226 if (header.size <= 1 ||
227 header.cluster_bits < 9 ||
228 header.cluster_bits > 16)
229 goto fail;
230 if (header.crypt_method > QCOW_CRYPT_AES)
231 goto fail;
232 s->crypt_method_header = header.crypt_method;
233 if (s->crypt_method_header)
234 bs->encrypted = 1;
235 s->cluster_bits = header.cluster_bits;
236 s->cluster_size = 1 << s->cluster_bits;
237 s->cluster_sectors = 1 << (s->cluster_bits - 9);
238 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
239 s->l2_size = 1 << s->l2_bits;
240 bs->total_sectors = header.size / 512;
241 s->csize_shift = (62 - (s->cluster_bits - 8));
242 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
243 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
244 s->refcount_table_offset = header.refcount_table_offset;
245 s->refcount_table_size =
246 header.refcount_table_clusters << (s->cluster_bits - 3);
248 s->snapshots_offset = header.snapshots_offset;
249 s->nb_snapshots = header.nb_snapshots;
251 /* read the level 1 table */
252 s->l1_size = header.l1_size;
253 shift = s->cluster_bits + s->l2_bits;
254 s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
255 /* the L1 table must contain at least enough entries to put
256 header.size bytes */
257 if (s->l1_size < s->l1_vm_state_index)
258 goto fail;
259 s->l1_table_offset = header.l1_table_offset;
260 s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
261 if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
262 s->l1_size * sizeof(uint64_t))
263 goto fail;
264 for(i = 0;i < s->l1_size; i++) {
265 be64_to_cpus(&s->l1_table[i]);
267 /* alloc L2 cache */
268 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
269 s->cluster_cache = qemu_malloc(s->cluster_size);
270 /* one more sector for decompressed data alignment */
271 s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
272 + 512);
273 s->cluster_cache_offset = -1;
275 if (refcount_init(bs) < 0)
276 goto fail;
278 scan_refcount(bs, &s->highest_alloc);
280 /* read the backing file name */
281 if (header.backing_file_offset != 0) {
282 len = header.backing_file_size;
283 if (len > 1023)
284 len = 1023;
285 if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
286 goto fail;
287 bs->backing_file[len] = '\0';
289 if (qcow_read_snapshots(bs) < 0)
290 goto fail;
292 #ifdef DEBUG_ALLOC
293 check_refcounts(bs);
294 #endif
295 return 0;
297 fail:
298 qcow_free_snapshots(bs);
299 refcount_close(bs);
300 qemu_free(s->l1_table);
301 qemu_free(s->l2_cache);
302 qemu_free(s->cluster_cache);
303 qemu_free(s->cluster_data);
304 bdrv_delete(s->hd);
305 return -1;
308 static int qcow_set_key(BlockDriverState *bs, const char *key)
310 BDRVQcowState *s = bs->opaque;
311 uint8_t keybuf[16];
312 int len, i;
314 memset(keybuf, 0, 16);
315 len = strlen(key);
316 if (len > 16)
317 len = 16;
318 /* XXX: we could compress the chars to 7 bits to increase
319 entropy */
320 for(i = 0;i < len;i++) {
321 keybuf[i] = key[i];
323 s->crypt_method = s->crypt_method_header;
325 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
326 return -1;
327 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
328 return -1;
329 #if 0
330 /* test */
332 uint8_t in[16];
333 uint8_t out[16];
334 uint8_t tmp[16];
335 for(i=0;i<16;i++)
336 in[i] = i;
337 AES_encrypt(in, tmp, &s->aes_encrypt_key);
338 AES_decrypt(tmp, out, &s->aes_decrypt_key);
339 for(i = 0; i < 16; i++)
340 printf(" %02x", tmp[i]);
341 printf("\n");
342 for(i = 0; i < 16; i++)
343 printf(" %02x", out[i]);
344 printf("\n");
346 #endif
347 return 0;
350 /* The crypt function is compatible with the linux cryptoloop
351 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
352 supported */
353 static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
354 uint8_t *out_buf, const uint8_t *in_buf,
355 int nb_sectors, int enc,
356 const AES_KEY *key)
358 union {
359 uint64_t ll[2];
360 uint8_t b[16];
361 } ivec;
362 int i;
364 for(i = 0; i < nb_sectors; i++) {
365 ivec.ll[0] = cpu_to_le64(sector_num);
366 ivec.ll[1] = 0;
367 AES_cbc_encrypt(in_buf, out_buf, 512, key,
368 ivec.b, enc);
369 sector_num++;
370 in_buf += 512;
371 out_buf += 512;
375 static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,
376 uint64_t cluster_offset, int n_start, int n_end)
378 BDRVQcowState *s = bs->opaque;
379 int n, ret;
381 n = n_end - n_start;
382 if (n <= 0)
383 return 0;
384 ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);
385 if (ret < 0)
386 return ret;
387 if (s->crypt_method) {
388 encrypt_sectors(s, start_sect + n_start,
389 s->cluster_data,
390 s->cluster_data, n, 1,
391 &s->aes_encrypt_key);
393 ret = bdrv_write(s->hd, (cluster_offset >> 9) + n_start,
394 s->cluster_data, n);
395 if (ret < 0)
396 return ret;
397 return 0;
400 static void l2_cache_reset(BlockDriverState *bs)
402 BDRVQcowState *s = bs->opaque;
404 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
405 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
406 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
409 static inline int l2_cache_new_entry(BlockDriverState *bs)
411 BDRVQcowState *s = bs->opaque;
412 uint32_t min_count;
413 int min_index, i;
415 /* find a new entry in the least used one */
416 min_index = 0;
417 min_count = 0xffffffff;
418 for(i = 0; i < L2_CACHE_SIZE; i++) {
419 if (s->l2_cache_counts[i] < min_count) {
420 min_count = s->l2_cache_counts[i];
421 min_index = i;
424 return min_index;
427 static int64_t align_offset(int64_t offset, int n)
429 offset = (offset + n - 1) & ~(n - 1);
430 return offset;
433 static int grow_l1_table(BlockDriverState *bs, int min_size)
435 BDRVQcowState *s = bs->opaque;
436 int new_l1_size, new_l1_size2, ret, i;
437 uint64_t *new_l1_table;
438 uint64_t new_l1_table_offset;
439 uint8_t data[12];
441 new_l1_size = s->l1_size;
442 if (min_size <= new_l1_size)
443 return 0;
444 while (min_size > new_l1_size) {
445 new_l1_size = (new_l1_size * 3 + 1) / 2;
447 #ifdef DEBUG_ALLOC2
448 printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
449 #endif
451 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
452 new_l1_table = qemu_mallocz(new_l1_size2);
453 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
455 /* write new table (align to cluster) */
456 new_l1_table_offset = alloc_clusters(bs, new_l1_size2);
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]);
466 /* set new table */
467 cpu_to_be32w((uint32_t*)data, new_l1_size);
468 cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);
469 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, l1_size), data,
470 sizeof(data)) != sizeof(data))
471 goto fail;
472 qemu_free(s->l1_table);
473 free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
474 s->l1_table_offset = new_l1_table_offset;
475 s->l1_table = new_l1_table;
476 s->l1_size = new_l1_size;
477 return 0;
478 fail:
479 qemu_free(s->l1_table);
480 return -EIO;
484 * seek_l2_table
486 * seek l2_offset in the l2_cache table
487 * if not found, return NULL,
488 * if found,
489 * increments the l2 cache hit count of the entry,
490 * if counter overflow, divide by two all counters
491 * return the pointer to the l2 cache entry
495 static uint64_t *seek_l2_table(BDRVQcowState *s, uint64_t l2_offset)
497 int i, j;
499 for(i = 0; i < L2_CACHE_SIZE; i++) {
500 if (l2_offset == s->l2_cache_offsets[i]) {
501 /* increment the hit count */
502 if (++s->l2_cache_counts[i] == 0xffffffff) {
503 for(j = 0; j < L2_CACHE_SIZE; j++) {
504 s->l2_cache_counts[j] >>= 1;
507 return s->l2_cache + (i << s->l2_bits);
510 return NULL;
514 * l2_load
516 * Loads a L2 table into memory. If the table is in the cache, the cache
517 * is used; otherwise the L2 table is loaded from the image file.
519 * Returns a pointer to the L2 table on success, or NULL if the read from
520 * the image file failed.
523 static uint64_t *l2_load(BlockDriverState *bs, uint64_t l2_offset)
525 BDRVQcowState *s = bs->opaque;
526 int min_index;
527 uint64_t *l2_table;
529 /* seek if the table for the given offset is in the cache */
531 l2_table = seek_l2_table(s, l2_offset);
532 if (l2_table != NULL)
533 return l2_table;
535 /* not found: load a new entry in the least used one */
537 min_index = l2_cache_new_entry(bs);
538 l2_table = s->l2_cache + (min_index << s->l2_bits);
539 if (bdrv_pread(s->hd, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
540 s->l2_size * sizeof(uint64_t))
541 return NULL;
542 s->l2_cache_offsets[min_index] = l2_offset;
543 s->l2_cache_counts[min_index] = 1;
545 return l2_table;
549 * l2_allocate
551 * Allocate a new l2 entry in the file. If l1_index points to an already
552 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
553 * table) copy the contents of the old L2 table into the newly allocated one.
554 * Otherwise the new table is initialized with zeros.
558 static uint64_t *l2_allocate(BlockDriverState *bs, int l1_index)
560 BDRVQcowState *s = bs->opaque;
561 int min_index;
562 uint64_t old_l2_offset, tmp;
563 uint64_t *l2_table, l2_offset;
565 old_l2_offset = s->l1_table[l1_index];
567 /* allocate a new l2 entry */
569 l2_offset = alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
571 /* update the L1 entry */
573 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
575 tmp = cpu_to_be64(l2_offset | QCOW_OFLAG_COPIED);
576 if (bdrv_pwrite(s->hd, s->l1_table_offset + l1_index * sizeof(tmp),
577 &tmp, sizeof(tmp)) != sizeof(tmp))
578 return NULL;
580 /* allocate a new entry in the l2 cache */
582 min_index = l2_cache_new_entry(bs);
583 l2_table = s->l2_cache + (min_index << s->l2_bits);
585 if (old_l2_offset == 0) {
586 /* if there was no old l2 table, clear the new table */
587 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
588 } else {
589 /* if there was an old l2 table, read it from the disk */
590 if (bdrv_pread(s->hd, old_l2_offset,
591 l2_table, s->l2_size * sizeof(uint64_t)) !=
592 s->l2_size * sizeof(uint64_t))
593 return NULL;
595 /* write the l2 table to the file */
596 if (bdrv_pwrite(s->hd, l2_offset,
597 l2_table, s->l2_size * sizeof(uint64_t)) !=
598 s->l2_size * sizeof(uint64_t))
599 return NULL;
601 /* update the l2 cache entry */
603 s->l2_cache_offsets[min_index] = l2_offset;
604 s->l2_cache_counts[min_index] = 1;
606 return l2_table;
609 static int size_to_clusters(BDRVQcowState *s, int64_t size)
611 return (size + (s->cluster_size - 1)) >> s->cluster_bits;
614 static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
615 uint64_t *l2_table, uint64_t start, uint64_t mask)
617 int i;
618 uint64_t offset = be64_to_cpu(l2_table[0]) & ~mask;
620 if (!offset)
621 return 0;
623 for (i = start; i < start + nb_clusters; i++)
624 if (offset + i * cluster_size != (be64_to_cpu(l2_table[i]) & ~mask))
625 break;
627 return (i - start);
630 static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
632 int i = 0;
634 while(nb_clusters-- && l2_table[i] == 0)
635 i++;
637 return i;
641 * get_cluster_offset
643 * For a given offset of the disk image, return cluster offset in
644 * qcow2 file.
646 * on entry, *num is the number of contiguous clusters we'd like to
647 * access following offset.
649 * on exit, *num is the number of contiguous clusters we can read.
651 * Return 1, if the offset is found
652 * Return 0, otherwise.
656 static uint64_t get_cluster_offset(BlockDriverState *bs,
657 uint64_t offset, int *num)
659 BDRVQcowState *s = bs->opaque;
660 int l1_index, l2_index;
661 uint64_t l2_offset, *l2_table, cluster_offset;
662 int l1_bits, c;
663 int index_in_cluster, nb_available, nb_needed, nb_clusters;
665 index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
666 nb_needed = *num + index_in_cluster;
668 l1_bits = s->l2_bits + s->cluster_bits;
670 /* compute how many bytes there are between the offset and
671 * the end of the l1 entry
674 nb_available = (1 << l1_bits) - (offset & ((1 << l1_bits) - 1));
676 /* compute the number of available sectors */
678 nb_available = (nb_available >> 9) + index_in_cluster;
680 cluster_offset = 0;
682 /* seek the the l2 offset in the l1 table */
684 l1_index = offset >> l1_bits;
685 if (l1_index >= s->l1_size)
686 goto out;
688 l2_offset = s->l1_table[l1_index];
690 /* seek the l2 table of the given l2 offset */
692 if (!l2_offset)
693 goto out;
695 /* load the l2 table in memory */
697 l2_offset &= ~QCOW_OFLAG_COPIED;
698 l2_table = l2_load(bs, l2_offset);
699 if (l2_table == NULL)
700 return 0;
702 /* find the cluster offset for the given disk offset */
704 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
705 cluster_offset = be64_to_cpu(l2_table[l2_index]);
706 nb_clusters = size_to_clusters(s, nb_needed << 9);
708 if (!cluster_offset) {
709 /* how many empty clusters ? */
710 c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
711 } else {
712 /* how many allocated clusters ? */
713 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
714 &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);
717 nb_available = (c * s->cluster_sectors);
718 out:
719 if (nb_available > nb_needed)
720 nb_available = nb_needed;
722 *num = nb_available - index_in_cluster;
724 return cluster_offset & ~QCOW_OFLAG_COPIED;
728 * free_any_clusters
730 * free clusters according to its type: compressed or not
734 static void free_any_clusters(BlockDriverState *bs,
735 uint64_t cluster_offset, int nb_clusters)
737 BDRVQcowState *s = bs->opaque;
739 /* free the cluster */
741 if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
742 int nb_csectors;
743 nb_csectors = ((cluster_offset >> s->csize_shift) &
744 s->csize_mask) + 1;
745 free_clusters(bs, (cluster_offset & s->cluster_offset_mask) & ~511,
746 nb_csectors * 512);
747 return;
750 free_clusters(bs, cluster_offset, nb_clusters << s->cluster_bits);
752 return;
756 * get_cluster_table
758 * for a given disk offset, load (and allocate if needed)
759 * the l2 table.
761 * the l2 table offset in the qcow2 file and the cluster index
762 * in the l2 table are given to the caller.
766 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
767 uint64_t **new_l2_table,
768 uint64_t *new_l2_offset,
769 int *new_l2_index)
771 BDRVQcowState *s = bs->opaque;
772 int l1_index, l2_index, ret;
773 uint64_t l2_offset, *l2_table;
775 /* seek the the l2 offset in the l1 table */
777 l1_index = offset >> (s->l2_bits + s->cluster_bits);
778 if (l1_index >= s->l1_size) {
779 ret = grow_l1_table(bs, l1_index + 1);
780 if (ret < 0)
781 return 0;
783 l2_offset = s->l1_table[l1_index];
785 /* seek the l2 table of the given l2 offset */
787 if (l2_offset & QCOW_OFLAG_COPIED) {
788 /* load the l2 table in memory */
789 l2_offset &= ~QCOW_OFLAG_COPIED;
790 l2_table = l2_load(bs, l2_offset);
791 if (l2_table == NULL)
792 return 0;
793 } else {
794 if (l2_offset)
795 free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
796 l2_table = l2_allocate(bs, l1_index);
797 if (l2_table == NULL)
798 return 0;
799 l2_offset = s->l1_table[l1_index] & ~QCOW_OFLAG_COPIED;
802 /* find the cluster offset for the given disk offset */
804 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
806 *new_l2_table = l2_table;
807 *new_l2_offset = l2_offset;
808 *new_l2_index = l2_index;
810 return 1;
814 * alloc_compressed_cluster_offset
816 * For a given offset of the disk image, return cluster offset in
817 * qcow2 file.
819 * If the offset is not found, allocate a new compressed cluster.
821 * Return the cluster offset if successful,
822 * Return 0, otherwise.
826 static uint64_t alloc_compressed_cluster_offset(BlockDriverState *bs,
827 uint64_t offset,
828 int compressed_size)
830 BDRVQcowState *s = bs->opaque;
831 int l2_index, ret;
832 uint64_t l2_offset, *l2_table, cluster_offset;
833 int nb_csectors;
835 ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
836 if (ret == 0)
837 return 0;
839 cluster_offset = be64_to_cpu(l2_table[l2_index]);
840 if (cluster_offset & QCOW_OFLAG_COPIED)
841 return cluster_offset & ~QCOW_OFLAG_COPIED;
843 if (cluster_offset)
844 free_any_clusters(bs, cluster_offset, 1);
846 cluster_offset = alloc_bytes(bs, compressed_size);
847 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
848 (cluster_offset >> 9);
850 cluster_offset |= QCOW_OFLAG_COMPRESSED |
851 ((uint64_t)nb_csectors << s->csize_shift);
853 /* update L2 table */
855 /* compressed clusters never have the copied flag */
857 l2_table[l2_index] = cpu_to_be64(cluster_offset);
858 if (bdrv_pwrite(s->hd,
859 l2_offset + l2_index * sizeof(uint64_t),
860 l2_table + l2_index,
861 sizeof(uint64_t)) != sizeof(uint64_t))
862 return 0;
864 return cluster_offset;
867 typedef struct QCowL2Meta
869 uint64_t offset;
870 int n_start;
871 int nb_available;
872 int nb_clusters;
873 } QCowL2Meta;
875 static int alloc_cluster_link_l2(BlockDriverState *bs, uint64_t cluster_offset,
876 QCowL2Meta *m)
878 BDRVQcowState *s = bs->opaque;
879 int i, j = 0, l2_index, ret;
880 uint64_t *old_cluster, start_sect, l2_offset, *l2_table;
882 if (m->nb_clusters == 0)
883 return 0;
885 old_cluster = qemu_malloc(m->nb_clusters * sizeof(uint64_t));
887 /* copy content of unmodified sectors */
888 start_sect = (m->offset & ~(s->cluster_size - 1)) >> 9;
889 if (m->n_start) {
890 ret = copy_sectors(bs, start_sect, cluster_offset, 0, m->n_start);
891 if (ret < 0)
892 goto err;
895 if (m->nb_available & (s->cluster_sectors - 1)) {
896 uint64_t end = m->nb_available & ~(uint64_t)(s->cluster_sectors - 1);
897 ret = copy_sectors(bs, start_sect + end, cluster_offset + (end << 9),
898 m->nb_available - end, s->cluster_sectors);
899 if (ret < 0)
900 goto err;
903 ret = -EIO;
904 /* update L2 table */
905 if (!get_cluster_table(bs, m->offset, &l2_table, &l2_offset, &l2_index))
906 goto err;
908 for (i = 0; i < m->nb_clusters; i++) {
909 if(l2_table[l2_index + i] != 0)
910 old_cluster[j++] = l2_table[l2_index + i];
912 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
913 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
916 if (bdrv_pwrite(s->hd, l2_offset + l2_index * sizeof(uint64_t),
917 l2_table + l2_index, m->nb_clusters * sizeof(uint64_t)) !=
918 m->nb_clusters * sizeof(uint64_t))
919 goto err;
921 for (i = 0; i < j; i++)
922 free_any_clusters(bs, old_cluster[i], 1);
924 ret = 0;
925 err:
926 qemu_free(old_cluster);
927 return ret;
931 * alloc_cluster_offset
933 * For a given offset of the disk image, return cluster offset in
934 * qcow2 file.
936 * If the offset is not found, allocate a new cluster.
938 * Return the cluster offset if successful,
939 * Return 0, otherwise.
943 static uint64_t alloc_cluster_offset(BlockDriverState *bs,
944 uint64_t offset,
945 int n_start, int n_end,
946 int *num, QCowL2Meta *m)
948 BDRVQcowState *s = bs->opaque;
949 int l2_index, ret;
950 uint64_t l2_offset, *l2_table, cluster_offset;
951 int nb_clusters, i = 0;
953 ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);
954 if (ret == 0)
955 return 0;
957 nb_clusters = size_to_clusters(s, n_end << 9);
959 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
961 cluster_offset = be64_to_cpu(l2_table[l2_index]);
963 /* We keep all QCOW_OFLAG_COPIED clusters */
965 if (cluster_offset & QCOW_OFLAG_COPIED) {
966 nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,
967 &l2_table[l2_index], 0, 0);
969 cluster_offset &= ~QCOW_OFLAG_COPIED;
970 m->nb_clusters = 0;
972 goto out;
975 /* for the moment, multiple compressed clusters are not managed */
977 if (cluster_offset & QCOW_OFLAG_COMPRESSED)
978 nb_clusters = 1;
980 /* how many available clusters ? */
982 while (i < nb_clusters) {
983 i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,
984 &l2_table[l2_index], i, 0);
986 if(be64_to_cpu(l2_table[l2_index + i]))
987 break;
989 i += count_contiguous_free_clusters(nb_clusters - i,
990 &l2_table[l2_index + i]);
992 cluster_offset = be64_to_cpu(l2_table[l2_index + i]);
994 if ((cluster_offset & QCOW_OFLAG_COPIED) ||
995 (cluster_offset & QCOW_OFLAG_COMPRESSED))
996 break;
998 nb_clusters = i;
1000 /* allocate a new cluster */
1002 cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);
1004 /* save info needed for meta data update */
1005 m->offset = offset;
1006 m->n_start = n_start;
1007 m->nb_clusters = nb_clusters;
1009 out:
1010 m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);
1012 *num = m->nb_available - n_start;
1014 return cluster_offset;
1017 static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
1018 int nb_sectors, int *pnum)
1020 uint64_t cluster_offset;
1022 *pnum = nb_sectors;
1023 cluster_offset = get_cluster_offset(bs, sector_num << 9, pnum);
1025 return (cluster_offset != 0);
1028 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1029 const uint8_t *buf, int buf_size)
1031 z_stream strm1, *strm = &strm1;
1032 int ret, out_len;
1034 memset(strm, 0, sizeof(*strm));
1036 strm->next_in = (uint8_t *)buf;
1037 strm->avail_in = buf_size;
1038 strm->next_out = out_buf;
1039 strm->avail_out = out_buf_size;
1041 ret = inflateInit2(strm, -12);
1042 if (ret != Z_OK)
1043 return -1;
1044 ret = inflate(strm, Z_FINISH);
1045 out_len = strm->next_out - out_buf;
1046 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1047 out_len != out_buf_size) {
1048 inflateEnd(strm);
1049 return -1;
1051 inflateEnd(strm);
1052 return 0;
1055 static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
1057 int ret, csize, nb_csectors, sector_offset;
1058 uint64_t coffset;
1060 coffset = cluster_offset & s->cluster_offset_mask;
1061 if (s->cluster_cache_offset != coffset) {
1062 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1063 sector_offset = coffset & 511;
1064 csize = nb_csectors * 512 - sector_offset;
1065 ret = bdrv_read(s->hd, coffset >> 9, s->cluster_data, nb_csectors);
1066 if (ret < 0) {
1067 return -1;
1069 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1070 s->cluster_data + sector_offset, csize) < 0) {
1071 return -1;
1073 s->cluster_cache_offset = coffset;
1075 return 0;
1078 /* handle reading after the end of the backing file */
1079 static int backing_read1(BlockDriverState *bs,
1080 int64_t sector_num, uint8_t *buf, int nb_sectors)
1082 int n1;
1083 if ((sector_num + nb_sectors) <= bs->total_sectors)
1084 return nb_sectors;
1085 if (sector_num >= bs->total_sectors)
1086 n1 = 0;
1087 else
1088 n1 = bs->total_sectors - sector_num;
1089 memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
1090 return n1;
1093 static int qcow_read(BlockDriverState *bs, int64_t sector_num,
1094 uint8_t *buf, int nb_sectors)
1096 BDRVQcowState *s = bs->opaque;
1097 int ret, index_in_cluster, n, n1;
1098 uint64_t cluster_offset;
1100 while (nb_sectors > 0) {
1101 n = nb_sectors;
1102 cluster_offset = get_cluster_offset(bs, sector_num << 9, &n);
1103 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1104 if (!cluster_offset) {
1105 if (bs->backing_hd) {
1106 /* read from the base image */
1107 n1 = backing_read1(bs->backing_hd, sector_num, buf, n);
1108 if (n1 > 0) {
1109 ret = bdrv_read(bs->backing_hd, sector_num, buf, n1);
1110 if (ret < 0)
1111 return -1;
1113 } else {
1114 memset(buf, 0, 512 * n);
1116 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
1117 if (decompress_cluster(s, cluster_offset) < 0)
1118 return -1;
1119 memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
1120 } else {
1121 ret = bdrv_pread(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1122 if (ret != n * 512)
1123 return -1;
1124 if (s->crypt_method) {
1125 encrypt_sectors(s, sector_num, buf, buf, n, 0,
1126 &s->aes_decrypt_key);
1129 nb_sectors -= n;
1130 sector_num += n;
1131 buf += n * 512;
1133 return 0;
1136 static int qcow_write(BlockDriverState *bs, int64_t sector_num,
1137 const uint8_t *buf, int nb_sectors)
1139 BDRVQcowState *s = bs->opaque;
1140 int ret, index_in_cluster, n;
1141 uint64_t cluster_offset;
1142 int n_end;
1143 QCowL2Meta l2meta;
1145 while (nb_sectors > 0) {
1146 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1147 n_end = index_in_cluster + nb_sectors;
1148 if (s->crypt_method &&
1149 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1150 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1151 cluster_offset = alloc_cluster_offset(bs, sector_num << 9,
1152 index_in_cluster,
1153 n_end, &n, &l2meta);
1154 if (!cluster_offset)
1155 return -1;
1156 if (s->crypt_method) {
1157 encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
1158 &s->aes_encrypt_key);
1159 ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512,
1160 s->cluster_data, n * 512);
1161 } else {
1162 ret = bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512);
1164 if (ret != n * 512 || alloc_cluster_link_l2(bs, cluster_offset, &l2meta) < 0) {
1165 free_any_clusters(bs, cluster_offset, l2meta.nb_clusters);
1166 return -1;
1168 nb_sectors -= n;
1169 sector_num += n;
1170 buf += n * 512;
1172 s->cluster_cache_offset = -1; /* disable compressed cache */
1173 return 0;
1176 typedef struct QCowAIOCB {
1177 BlockDriverAIOCB common;
1178 int64_t sector_num;
1179 uint8_t *buf;
1180 int nb_sectors;
1181 int n;
1182 uint64_t cluster_offset;
1183 uint8_t *cluster_data;
1184 BlockDriverAIOCB *hd_aiocb;
1185 QEMUBH *bh;
1186 QCowL2Meta l2meta;
1187 } QCowAIOCB;
1189 static void qcow_aio_read_cb(void *opaque, int ret);
1190 static void qcow_aio_read_bh(void *opaque)
1192 QCowAIOCB *acb = opaque;
1193 qemu_bh_delete(acb->bh);
1194 acb->bh = NULL;
1195 qcow_aio_read_cb(opaque, 0);
1198 static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
1200 if (acb->bh)
1201 return -EIO;
1203 acb->bh = qemu_bh_new(cb, acb);
1204 if (!acb->bh)
1205 return -EIO;
1207 qemu_bh_schedule(acb->bh);
1209 return 0;
1212 static void qcow_aio_read_cb(void *opaque, int ret)
1214 QCowAIOCB *acb = opaque;
1215 BlockDriverState *bs = acb->common.bs;
1216 BDRVQcowState *s = bs->opaque;
1217 int index_in_cluster, n1;
1219 acb->hd_aiocb = NULL;
1220 if (ret < 0) {
1221 fail:
1222 acb->common.cb(acb->common.opaque, ret);
1223 qemu_aio_release(acb);
1224 return;
1227 /* post process the read buffer */
1228 if (!acb->cluster_offset) {
1229 /* nothing to do */
1230 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1231 /* nothing to do */
1232 } else {
1233 if (s->crypt_method) {
1234 encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
1235 acb->n, 0,
1236 &s->aes_decrypt_key);
1240 acb->nb_sectors -= acb->n;
1241 acb->sector_num += acb->n;
1242 acb->buf += acb->n * 512;
1244 if (acb->nb_sectors == 0) {
1245 /* request completed */
1246 acb->common.cb(acb->common.opaque, 0);
1247 qemu_aio_release(acb);
1248 return;
1251 /* prepare next AIO request */
1252 acb->n = acb->nb_sectors;
1253 acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
1254 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1256 if (!acb->cluster_offset) {
1257 if (bs->backing_hd) {
1258 /* read from the base image */
1259 n1 = backing_read1(bs->backing_hd, acb->sector_num,
1260 acb->buf, acb->n);
1261 if (n1 > 0) {
1262 acb->hd_aiocb = bdrv_aio_read(bs->backing_hd, acb->sector_num,
1263 acb->buf, acb->n, qcow_aio_read_cb, acb);
1264 if (acb->hd_aiocb == NULL)
1265 goto fail;
1266 } else {
1267 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1268 if (ret < 0)
1269 goto fail;
1271 } else {
1272 /* Note: in this case, no need to wait */
1273 memset(acb->buf, 0, 512 * acb->n);
1274 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1275 if (ret < 0)
1276 goto fail;
1278 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
1279 /* add AIO support for compressed blocks ? */
1280 if (decompress_cluster(s, acb->cluster_offset) < 0)
1281 goto fail;
1282 memcpy(acb->buf,
1283 s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
1284 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
1285 if (ret < 0)
1286 goto fail;
1287 } else {
1288 if ((acb->cluster_offset & 511) != 0) {
1289 ret = -EIO;
1290 goto fail;
1292 acb->hd_aiocb = bdrv_aio_read(s->hd,
1293 (acb->cluster_offset >> 9) + index_in_cluster,
1294 acb->buf, acb->n, qcow_aio_read_cb, acb);
1295 if (acb->hd_aiocb == NULL)
1296 goto fail;
1300 static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
1301 int64_t sector_num, uint8_t *buf, int nb_sectors,
1302 BlockDriverCompletionFunc *cb, void *opaque)
1304 QCowAIOCB *acb;
1306 acb = qemu_aio_get(bs, cb, opaque);
1307 if (!acb)
1308 return NULL;
1309 acb->hd_aiocb = NULL;
1310 acb->sector_num = sector_num;
1311 acb->buf = buf;
1312 acb->nb_sectors = nb_sectors;
1313 acb->n = 0;
1314 acb->cluster_offset = 0;
1315 acb->l2meta.nb_clusters = 0;
1316 return acb;
1319 static BlockDriverAIOCB *qcow_aio_read(BlockDriverState *bs,
1320 int64_t sector_num, uint8_t *buf, int nb_sectors,
1321 BlockDriverCompletionFunc *cb, void *opaque)
1323 QCowAIOCB *acb;
1325 acb = qcow_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
1326 if (!acb)
1327 return NULL;
1329 qcow_aio_read_cb(acb, 0);
1330 return &acb->common;
1333 static void qcow_aio_write_cb(void *opaque, int ret)
1335 QCowAIOCB *acb = opaque;
1336 BlockDriverState *bs = acb->common.bs;
1337 BDRVQcowState *s = bs->opaque;
1338 int index_in_cluster;
1339 const uint8_t *src_buf;
1340 int n_end;
1342 acb->hd_aiocb = NULL;
1344 if (ret < 0) {
1345 fail:
1346 acb->common.cb(acb->common.opaque, ret);
1347 qemu_aio_release(acb);
1348 return;
1351 if (alloc_cluster_link_l2(bs, acb->cluster_offset, &acb->l2meta) < 0) {
1352 free_any_clusters(bs, acb->cluster_offset, acb->l2meta.nb_clusters);
1353 goto fail;
1356 acb->nb_sectors -= acb->n;
1357 acb->sector_num += acb->n;
1358 acb->buf += acb->n * 512;
1360 if (acb->nb_sectors == 0) {
1361 /* request completed */
1362 acb->common.cb(acb->common.opaque, 0);
1363 qemu_aio_release(acb);
1364 return;
1367 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
1368 n_end = index_in_cluster + acb->nb_sectors;
1369 if (s->crypt_method &&
1370 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
1371 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
1373 acb->cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,
1374 index_in_cluster,
1375 n_end, &acb->n, &acb->l2meta);
1376 if (!acb->cluster_offset || (acb->cluster_offset & 511) != 0) {
1377 ret = -EIO;
1378 goto fail;
1380 if (s->crypt_method) {
1381 if (!acb->cluster_data) {
1382 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
1383 s->cluster_size);
1385 encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
1386 acb->n, 1, &s->aes_encrypt_key);
1387 src_buf = acb->cluster_data;
1388 } else {
1389 src_buf = acb->buf;
1391 acb->hd_aiocb = bdrv_aio_write(s->hd,
1392 (acb->cluster_offset >> 9) + index_in_cluster,
1393 src_buf, acb->n,
1394 qcow_aio_write_cb, acb);
1395 if (acb->hd_aiocb == NULL)
1396 goto fail;
1399 static BlockDriverAIOCB *qcow_aio_write(BlockDriverState *bs,
1400 int64_t sector_num, const uint8_t *buf, int nb_sectors,
1401 BlockDriverCompletionFunc *cb, void *opaque)
1403 BDRVQcowState *s = bs->opaque;
1404 QCowAIOCB *acb;
1406 s->cluster_cache_offset = -1; /* disable compressed cache */
1408 acb = qcow_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
1409 if (!acb)
1410 return NULL;
1412 qcow_aio_write_cb(acb, 0);
1413 return &acb->common;
1416 static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
1418 QCowAIOCB *acb = (QCowAIOCB *)blockacb;
1419 if (acb->hd_aiocb)
1420 bdrv_aio_cancel(acb->hd_aiocb);
1421 qemu_aio_release(acb);
1424 static void qcow_close(BlockDriverState *bs)
1426 BDRVQcowState *s = bs->opaque;
1427 qemu_free(s->l1_table);
1428 qemu_free(s->l2_cache);
1429 qemu_free(s->cluster_cache);
1430 qemu_free(s->cluster_data);
1431 refcount_close(bs);
1432 bdrv_delete(s->hd);
1435 /* XXX: use std qcow open function ? */
1436 typedef struct QCowCreateState {
1437 int cluster_size;
1438 int cluster_bits;
1439 uint16_t *refcount_block;
1440 uint64_t *refcount_table;
1441 int64_t l1_table_offset;
1442 int64_t refcount_table_offset;
1443 int64_t refcount_block_offset;
1444 } QCowCreateState;
1446 static void create_refcount_update(QCowCreateState *s,
1447 int64_t offset, int64_t size)
1449 int refcount;
1450 int64_t start, last, cluster_offset;
1451 uint16_t *p;
1453 start = offset & ~(s->cluster_size - 1);
1454 last = (offset + size - 1) & ~(s->cluster_size - 1);
1455 for(cluster_offset = start; cluster_offset <= last;
1456 cluster_offset += s->cluster_size) {
1457 p = &s->refcount_block[cluster_offset >> s->cluster_bits];
1458 refcount = be16_to_cpu(*p);
1459 refcount++;
1460 *p = cpu_to_be16(refcount);
1464 static int qcow_create(const char *filename, int64_t total_size,
1465 const char *backing_file, int flags)
1467 int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
1468 QCowHeader header;
1469 uint64_t tmp, offset;
1470 QCowCreateState s1, *s = &s1;
1472 memset(s, 0, sizeof(*s));
1474 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1475 if (fd < 0)
1476 return -1;
1477 memset(&header, 0, sizeof(header));
1478 header.magic = cpu_to_be32(QCOW_MAGIC);
1479 header.version = cpu_to_be32(QCOW_VERSION);
1480 header.size = cpu_to_be64(total_size * 512);
1481 header_size = sizeof(header);
1482 backing_filename_len = 0;
1483 if (backing_file) {
1484 header.backing_file_offset = cpu_to_be64(header_size);
1485 backing_filename_len = strlen(backing_file);
1486 header.backing_file_size = cpu_to_be32(backing_filename_len);
1487 header_size += backing_filename_len;
1489 s->cluster_bits = 12; /* 4 KB clusters */
1490 s->cluster_size = 1 << s->cluster_bits;
1491 header.cluster_bits = cpu_to_be32(s->cluster_bits);
1492 header_size = (header_size + 7) & ~7;
1493 if (flags & BLOCK_FLAG_ENCRYPT) {
1494 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1495 } else {
1496 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1498 l2_bits = s->cluster_bits - 3;
1499 shift = s->cluster_bits + l2_bits;
1500 l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
1501 offset = align_offset(header_size, s->cluster_size);
1502 s->l1_table_offset = offset;
1503 header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
1504 header.l1_size = cpu_to_be32(l1_size);
1505 offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
1507 s->refcount_table = qemu_mallocz(s->cluster_size);
1508 s->refcount_block = qemu_mallocz(s->cluster_size);
1510 s->refcount_table_offset = offset;
1511 header.refcount_table_offset = cpu_to_be64(offset);
1512 header.refcount_table_clusters = cpu_to_be32(1);
1513 offset += s->cluster_size;
1515 s->refcount_table[0] = cpu_to_be64(offset);
1516 s->refcount_block_offset = offset;
1517 offset += s->cluster_size;
1519 /* update refcounts */
1520 create_refcount_update(s, 0, header_size);
1521 create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
1522 create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
1523 create_refcount_update(s, s->refcount_block_offset, s->cluster_size);
1525 /* write all the data */
1526 write(fd, &header, sizeof(header));
1527 if (backing_file) {
1528 write(fd, backing_file, backing_filename_len);
1530 lseek(fd, s->l1_table_offset, SEEK_SET);
1531 tmp = 0;
1532 for(i = 0;i < l1_size; i++) {
1533 write(fd, &tmp, sizeof(tmp));
1535 lseek(fd, s->refcount_table_offset, SEEK_SET);
1536 write(fd, s->refcount_table, s->cluster_size);
1538 lseek(fd, s->refcount_block_offset, SEEK_SET);
1539 write(fd, s->refcount_block, s->cluster_size);
1541 qemu_free(s->refcount_table);
1542 qemu_free(s->refcount_block);
1543 close(fd);
1544 return 0;
1547 static int qcow_make_empty(BlockDriverState *bs)
1549 #if 0
1550 /* XXX: not correct */
1551 BDRVQcowState *s = bs->opaque;
1552 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1553 int ret;
1555 memset(s->l1_table, 0, l1_length);
1556 if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1557 return -1;
1558 ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1559 if (ret < 0)
1560 return ret;
1562 l2_cache_reset(bs);
1563 #endif
1564 return 0;
1567 /* XXX: put compressed sectors first, then all the cluster aligned
1568 tables to avoid losing bytes in alignment */
1569 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1570 const uint8_t *buf, int nb_sectors)
1572 BDRVQcowState *s = bs->opaque;
1573 z_stream strm;
1574 int ret, out_len;
1575 uint8_t *out_buf;
1576 uint64_t cluster_offset;
1578 if (nb_sectors == 0) {
1579 /* align end of file to a sector boundary to ease reading with
1580 sector based I/Os */
1581 cluster_offset = bdrv_getlength(s->hd);
1582 cluster_offset = (cluster_offset + 511) & ~511;
1583 bdrv_truncate(s->hd, cluster_offset);
1584 return 0;
1587 if (nb_sectors != s->cluster_sectors)
1588 return -EINVAL;
1590 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1592 /* best compression, small window, no zlib header */
1593 memset(&strm, 0, sizeof(strm));
1594 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1595 Z_DEFLATED, -12,
1596 9, Z_DEFAULT_STRATEGY);
1597 if (ret != 0) {
1598 qemu_free(out_buf);
1599 return -1;
1602 strm.avail_in = s->cluster_size;
1603 strm.next_in = (uint8_t *)buf;
1604 strm.avail_out = s->cluster_size;
1605 strm.next_out = out_buf;
1607 ret = deflate(&strm, Z_FINISH);
1608 if (ret != Z_STREAM_END && ret != Z_OK) {
1609 qemu_free(out_buf);
1610 deflateEnd(&strm);
1611 return -1;
1613 out_len = strm.next_out - out_buf;
1615 deflateEnd(&strm);
1617 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1618 /* could not compress: write normal cluster */
1619 qcow_write(bs, sector_num, buf, s->cluster_sectors);
1620 } else {
1621 cluster_offset = alloc_compressed_cluster_offset(bs, sector_num << 9,
1622 out_len);
1623 if (!cluster_offset)
1624 return -1;
1625 cluster_offset &= s->cluster_offset_mask;
1626 if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1627 qemu_free(out_buf);
1628 return -1;
1632 qemu_free(out_buf);
1633 return 0;
1636 static void qcow_flush(BlockDriverState *bs)
1638 BDRVQcowState *s = bs->opaque;
1639 bdrv_flush(s->hd);
1642 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1644 BDRVQcowState *s = bs->opaque;
1645 bdi->cluster_size = s->cluster_size;
1646 bdi->vm_state_offset = (int64_t)s->l1_vm_state_index <<
1647 (s->cluster_bits + s->l2_bits);
1648 return 0;
1651 /*********************************************************/
1652 /* snapshot support */
1654 /* update the refcounts of snapshots and the copied flag */
1655 static int update_snapshot_refcount(BlockDriverState *bs,
1656 int64_t l1_table_offset,
1657 int l1_size,
1658 int addend)
1660 BDRVQcowState *s = bs->opaque;
1661 uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;
1662 int64_t old_offset, old_l2_offset;
1663 int l2_size, i, j, l1_modified, l2_modified, nb_csectors, refcount;
1665 l2_cache_reset(bs);
1667 l2_table = NULL;
1668 l1_table = NULL;
1669 l1_size2 = l1_size * sizeof(uint64_t);
1670 l1_allocated = 0;
1671 if (l1_table_offset != s->l1_table_offset) {
1672 l1_table = qemu_malloc(l1_size2);
1673 l1_allocated = 1;
1674 if (bdrv_pread(s->hd, l1_table_offset,
1675 l1_table, l1_size2) != l1_size2)
1676 goto fail;
1677 for(i = 0;i < l1_size; i++)
1678 be64_to_cpus(&l1_table[i]);
1679 } else {
1680 assert(l1_size == s->l1_size);
1681 l1_table = s->l1_table;
1682 l1_allocated = 0;
1685 l2_size = s->l2_size * sizeof(uint64_t);
1686 l2_table = qemu_malloc(l2_size);
1687 l1_modified = 0;
1688 for(i = 0; i < l1_size; i++) {
1689 l2_offset = l1_table[i];
1690 if (l2_offset) {
1691 old_l2_offset = l2_offset;
1692 l2_offset &= ~QCOW_OFLAG_COPIED;
1693 l2_modified = 0;
1694 if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
1695 goto fail;
1696 for(j = 0; j < s->l2_size; j++) {
1697 offset = be64_to_cpu(l2_table[j]);
1698 if (offset != 0) {
1699 old_offset = offset;
1700 offset &= ~QCOW_OFLAG_COPIED;
1701 if (offset & QCOW_OFLAG_COMPRESSED) {
1702 nb_csectors = ((offset >> s->csize_shift) &
1703 s->csize_mask) + 1;
1704 if (addend != 0)
1705 update_refcount(bs, (offset & s->cluster_offset_mask) & ~511,
1706 nb_csectors * 512, addend);
1707 /* compressed clusters are never modified */
1708 refcount = 2;
1709 } else {
1710 if (addend != 0) {
1711 refcount = update_cluster_refcount(bs, offset >> s->cluster_bits, addend);
1712 } else {
1713 refcount = get_refcount(bs, offset >> s->cluster_bits);
1717 if (refcount == 1) {
1718 offset |= QCOW_OFLAG_COPIED;
1720 if (offset != old_offset) {
1721 l2_table[j] = cpu_to_be64(offset);
1722 l2_modified = 1;
1726 if (l2_modified) {
1727 if (bdrv_pwrite(s->hd,
1728 l2_offset, l2_table, l2_size) != l2_size)
1729 goto fail;
1732 if (addend != 0) {
1733 refcount = update_cluster_refcount(bs, l2_offset >> s->cluster_bits, addend);
1734 } else {
1735 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1737 if (refcount == 1) {
1738 l2_offset |= QCOW_OFLAG_COPIED;
1740 if (l2_offset != old_l2_offset) {
1741 l1_table[i] = l2_offset;
1742 l1_modified = 1;
1746 if (l1_modified) {
1747 for(i = 0; i < l1_size; i++)
1748 cpu_to_be64s(&l1_table[i]);
1749 if (bdrv_pwrite(s->hd, l1_table_offset, l1_table,
1750 l1_size2) != l1_size2)
1751 goto fail;
1752 for(i = 0; i < l1_size; i++)
1753 be64_to_cpus(&l1_table[i]);
1755 if (l1_allocated)
1756 qemu_free(l1_table);
1757 qemu_free(l2_table);
1758 return 0;
1759 fail:
1760 if (l1_allocated)
1761 qemu_free(l1_table);
1762 qemu_free(l2_table);
1763 return -EIO;
1766 static void qcow_free_snapshots(BlockDriverState *bs)
1768 BDRVQcowState *s = bs->opaque;
1769 int i;
1771 for(i = 0; i < s->nb_snapshots; i++) {
1772 qemu_free(s->snapshots[i].name);
1773 qemu_free(s->snapshots[i].id_str);
1775 qemu_free(s->snapshots);
1776 s->snapshots = NULL;
1777 s->nb_snapshots = 0;
1780 static int qcow_read_snapshots(BlockDriverState *bs)
1782 BDRVQcowState *s = bs->opaque;
1783 QCowSnapshotHeader h;
1784 QCowSnapshot *sn;
1785 int i, id_str_size, name_size;
1786 int64_t offset;
1787 uint32_t extra_data_size;
1789 if (!s->nb_snapshots) {
1790 s->snapshots = NULL;
1791 s->snapshots_size = 0;
1792 return 0;
1795 offset = s->snapshots_offset;
1796 s->snapshots = qemu_mallocz(s->nb_snapshots * sizeof(QCowSnapshot));
1797 for(i = 0; i < s->nb_snapshots; i++) {
1798 offset = align_offset(offset, 8);
1799 if (bdrv_pread(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1800 goto fail;
1801 offset += sizeof(h);
1802 sn = s->snapshots + i;
1803 sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
1804 sn->l1_size = be32_to_cpu(h.l1_size);
1805 sn->vm_state_size = be32_to_cpu(h.vm_state_size);
1806 sn->date_sec = be32_to_cpu(h.date_sec);
1807 sn->date_nsec = be32_to_cpu(h.date_nsec);
1808 sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
1809 extra_data_size = be32_to_cpu(h.extra_data_size);
1811 id_str_size = be16_to_cpu(h.id_str_size);
1812 name_size = be16_to_cpu(h.name_size);
1814 offset += extra_data_size;
1816 sn->id_str = qemu_malloc(id_str_size + 1);
1817 if (bdrv_pread(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1818 goto fail;
1819 offset += id_str_size;
1820 sn->id_str[id_str_size] = '\0';
1822 sn->name = qemu_malloc(name_size + 1);
1823 if (bdrv_pread(s->hd, offset, sn->name, name_size) != name_size)
1824 goto fail;
1825 offset += name_size;
1826 sn->name[name_size] = '\0';
1828 s->snapshots_size = offset - s->snapshots_offset;
1829 return 0;
1830 fail:
1831 qcow_free_snapshots(bs);
1832 return -1;
1835 /* add at the end of the file a new list of snapshots */
1836 static int qcow_write_snapshots(BlockDriverState *bs)
1838 BDRVQcowState *s = bs->opaque;
1839 QCowSnapshot *sn;
1840 QCowSnapshotHeader h;
1841 int i, name_size, id_str_size, snapshots_size;
1842 uint64_t data64;
1843 uint32_t data32;
1844 int64_t offset, snapshots_offset;
1846 /* compute the size of the snapshots */
1847 offset = 0;
1848 for(i = 0; i < s->nb_snapshots; i++) {
1849 sn = s->snapshots + i;
1850 offset = align_offset(offset, 8);
1851 offset += sizeof(h);
1852 offset += strlen(sn->id_str);
1853 offset += strlen(sn->name);
1855 snapshots_size = offset;
1857 snapshots_offset = alloc_clusters(bs, snapshots_size);
1858 offset = snapshots_offset;
1860 for(i = 0; i < s->nb_snapshots; i++) {
1861 sn = s->snapshots + i;
1862 memset(&h, 0, sizeof(h));
1863 h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);
1864 h.l1_size = cpu_to_be32(sn->l1_size);
1865 h.vm_state_size = cpu_to_be32(sn->vm_state_size);
1866 h.date_sec = cpu_to_be32(sn->date_sec);
1867 h.date_nsec = cpu_to_be32(sn->date_nsec);
1868 h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);
1870 id_str_size = strlen(sn->id_str);
1871 name_size = strlen(sn->name);
1872 h.id_str_size = cpu_to_be16(id_str_size);
1873 h.name_size = cpu_to_be16(name_size);
1874 offset = align_offset(offset, 8);
1875 if (bdrv_pwrite(s->hd, offset, &h, sizeof(h)) != sizeof(h))
1876 goto fail;
1877 offset += sizeof(h);
1878 if (bdrv_pwrite(s->hd, offset, sn->id_str, id_str_size) != id_str_size)
1879 goto fail;
1880 offset += id_str_size;
1881 if (bdrv_pwrite(s->hd, offset, sn->name, name_size) != name_size)
1882 goto fail;
1883 offset += name_size;
1886 /* update the various header fields */
1887 data64 = cpu_to_be64(snapshots_offset);
1888 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, snapshots_offset),
1889 &data64, sizeof(data64)) != sizeof(data64))
1890 goto fail;
1891 data32 = cpu_to_be32(s->nb_snapshots);
1892 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, nb_snapshots),
1893 &data32, sizeof(data32)) != sizeof(data32))
1894 goto fail;
1896 /* free the old snapshot table */
1897 free_clusters(bs, s->snapshots_offset, s->snapshots_size);
1898 s->snapshots_offset = snapshots_offset;
1899 s->snapshots_size = snapshots_size;
1900 return 0;
1901 fail:
1902 return -1;
1905 static void find_new_snapshot_id(BlockDriverState *bs,
1906 char *id_str, int id_str_size)
1908 BDRVQcowState *s = bs->opaque;
1909 QCowSnapshot *sn;
1910 int i, id, id_max = 0;
1912 for(i = 0; i < s->nb_snapshots; i++) {
1913 sn = s->snapshots + i;
1914 id = strtoul(sn->id_str, NULL, 10);
1915 if (id > id_max)
1916 id_max = id;
1918 snprintf(id_str, id_str_size, "%d", id_max + 1);
1921 static int find_snapshot_by_id(BlockDriverState *bs, const char *id_str)
1923 BDRVQcowState *s = bs->opaque;
1924 int i;
1926 for(i = 0; i < s->nb_snapshots; i++) {
1927 if (!strcmp(s->snapshots[i].id_str, id_str))
1928 return i;
1930 return -1;
1933 static int find_snapshot_by_id_or_name(BlockDriverState *bs, const char *name)
1935 BDRVQcowState *s = bs->opaque;
1936 int i, ret;
1938 ret = find_snapshot_by_id(bs, name);
1939 if (ret >= 0)
1940 return ret;
1941 for(i = 0; i < s->nb_snapshots; i++) {
1942 if (!strcmp(s->snapshots[i].name, name))
1943 return i;
1945 return -1;
1948 /* if no id is provided, a new one is constructed */
1949 static int qcow_snapshot_create(BlockDriverState *bs,
1950 QEMUSnapshotInfo *sn_info)
1952 BDRVQcowState *s = bs->opaque;
1953 QCowSnapshot *snapshots1, sn1, *sn = &sn1;
1954 int i, ret;
1955 uint64_t *l1_table = NULL;
1957 memset(sn, 0, sizeof(*sn));
1959 if (sn_info->id_str[0] == '\0') {
1960 /* compute a new id */
1961 find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));
1964 /* check that the ID is unique */
1965 if (find_snapshot_by_id(bs, sn_info->id_str) >= 0)
1966 return -ENOENT;
1968 sn->id_str = qemu_strdup(sn_info->id_str);
1969 if (!sn->id_str)
1970 goto fail;
1971 sn->name = qemu_strdup(sn_info->name);
1972 if (!sn->name)
1973 goto fail;
1974 sn->vm_state_size = sn_info->vm_state_size;
1975 sn->date_sec = sn_info->date_sec;
1976 sn->date_nsec = sn_info->date_nsec;
1977 sn->vm_clock_nsec = sn_info->vm_clock_nsec;
1979 ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);
1980 if (ret < 0)
1981 goto fail;
1983 /* create the L1 table of the snapshot */
1984 sn->l1_table_offset = alloc_clusters(bs, s->l1_size * sizeof(uint64_t));
1985 sn->l1_size = s->l1_size;
1987 l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
1988 for(i = 0; i < s->l1_size; i++) {
1989 l1_table[i] = cpu_to_be64(s->l1_table[i]);
1991 if (bdrv_pwrite(s->hd, sn->l1_table_offset,
1992 l1_table, s->l1_size * sizeof(uint64_t)) !=
1993 (s->l1_size * sizeof(uint64_t)))
1994 goto fail;
1995 qemu_free(l1_table);
1996 l1_table = NULL;
1998 snapshots1 = qemu_malloc((s->nb_snapshots + 1) * sizeof(QCowSnapshot));
1999 if (s->snapshots) {
2000 memcpy(snapshots1, s->snapshots, s->nb_snapshots * sizeof(QCowSnapshot));
2001 qemu_free(s->snapshots);
2003 s->snapshots = snapshots1;
2004 s->snapshots[s->nb_snapshots++] = *sn;
2006 if (qcow_write_snapshots(bs) < 0)
2007 goto fail;
2008 #ifdef DEBUG_ALLOC
2009 check_refcounts(bs);
2010 #endif
2011 return 0;
2012 fail:
2013 qemu_free(sn->name);
2014 qemu_free(l1_table);
2015 return -1;
2018 /* copy the snapshot 'snapshot_name' into the current disk image */
2019 static int qcow_snapshot_goto(BlockDriverState *bs,
2020 const char *snapshot_id)
2022 BDRVQcowState *s = bs->opaque;
2023 QCowSnapshot *sn;
2024 int i, snapshot_index, l1_size2;
2026 snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2027 if (snapshot_index < 0)
2028 return -ENOENT;
2029 sn = &s->snapshots[snapshot_index];
2031 if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, -1) < 0)
2032 goto fail;
2034 if (grow_l1_table(bs, sn->l1_size) < 0)
2035 goto fail;
2037 s->l1_size = sn->l1_size;
2038 l1_size2 = s->l1_size * sizeof(uint64_t);
2039 /* copy the snapshot l1 table to the current l1 table */
2040 if (bdrv_pread(s->hd, sn->l1_table_offset,
2041 s->l1_table, l1_size2) != l1_size2)
2042 goto fail;
2043 if (bdrv_pwrite(s->hd, s->l1_table_offset,
2044 s->l1_table, l1_size2) != l1_size2)
2045 goto fail;
2046 for(i = 0;i < s->l1_size; i++) {
2047 be64_to_cpus(&s->l1_table[i]);
2050 if (update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1) < 0)
2051 goto fail;
2053 #ifdef DEBUG_ALLOC
2054 check_refcounts(bs);
2055 #endif
2056 return 0;
2057 fail:
2058 return -EIO;
2061 static int qcow_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2063 BDRVQcowState *s = bs->opaque;
2064 QCowSnapshot *sn;
2065 int snapshot_index, ret;
2067 snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);
2068 if (snapshot_index < 0)
2069 return -ENOENT;
2070 sn = &s->snapshots[snapshot_index];
2072 ret = update_snapshot_refcount(bs, sn->l1_table_offset, sn->l1_size, -1);
2073 if (ret < 0)
2074 return ret;
2075 /* must update the copied flag on the current cluster offsets */
2076 ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);
2077 if (ret < 0)
2078 return ret;
2079 free_clusters(bs, sn->l1_table_offset, sn->l1_size * sizeof(uint64_t));
2081 qemu_free(sn->id_str);
2082 qemu_free(sn->name);
2083 memmove(sn, sn + 1, (s->nb_snapshots - snapshot_index - 1) * sizeof(*sn));
2084 s->nb_snapshots--;
2085 ret = qcow_write_snapshots(bs);
2086 if (ret < 0) {
2087 /* XXX: restore snapshot if error ? */
2088 return ret;
2090 #ifdef DEBUG_ALLOC
2091 check_refcounts(bs);
2092 #endif
2093 return 0;
2096 static int qcow_snapshot_list(BlockDriverState *bs,
2097 QEMUSnapshotInfo **psn_tab)
2099 BDRVQcowState *s = bs->opaque;
2100 QEMUSnapshotInfo *sn_tab, *sn_info;
2101 QCowSnapshot *sn;
2102 int i;
2104 sn_tab = qemu_mallocz(s->nb_snapshots * sizeof(QEMUSnapshotInfo));
2105 for(i = 0; i < s->nb_snapshots; i++) {
2106 sn_info = sn_tab + i;
2107 sn = s->snapshots + i;
2108 pstrcpy(sn_info->id_str, sizeof(sn_info->id_str),
2109 sn->id_str);
2110 pstrcpy(sn_info->name, sizeof(sn_info->name),
2111 sn->name);
2112 sn_info->vm_state_size = sn->vm_state_size;
2113 sn_info->date_sec = sn->date_sec;
2114 sn_info->date_nsec = sn->date_nsec;
2115 sn_info->vm_clock_nsec = sn->vm_clock_nsec;
2117 *psn_tab = sn_tab;
2118 return s->nb_snapshots;
2121 /*********************************************************/
2122 /* refcount handling */
2124 static int refcount_init(BlockDriverState *bs)
2126 BDRVQcowState *s = bs->opaque;
2127 int ret, refcount_table_size2, i;
2129 s->refcount_block_cache = qemu_malloc(s->cluster_size);
2130 refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
2131 s->refcount_table = qemu_malloc(refcount_table_size2);
2132 if (s->refcount_table_size > 0) {
2133 ret = bdrv_pread(s->hd, s->refcount_table_offset,
2134 s->refcount_table, refcount_table_size2);
2135 if (ret != refcount_table_size2)
2136 goto fail;
2137 for(i = 0; i < s->refcount_table_size; i++)
2138 be64_to_cpus(&s->refcount_table[i]);
2140 return 0;
2141 fail:
2142 return -ENOMEM;
2145 static void refcount_close(BlockDriverState *bs)
2147 BDRVQcowState *s = bs->opaque;
2148 qemu_free(s->refcount_block_cache);
2149 qemu_free(s->refcount_table);
2153 static int load_refcount_block(BlockDriverState *bs,
2154 int64_t refcount_block_offset)
2156 BDRVQcowState *s = bs->opaque;
2157 int ret;
2158 ret = bdrv_pread(s->hd, refcount_block_offset, s->refcount_block_cache,
2159 s->cluster_size);
2160 if (ret != s->cluster_size)
2161 return -EIO;
2162 s->refcount_block_cache_offset = refcount_block_offset;
2163 return 0;
2166 static void scan_refcount(BlockDriverState *bs, int64_t *high)
2168 BDRVQcowState *s = bs->opaque;
2169 int64_t refcnt_index, cluster_index, cluster_end, h = 0;
2171 for (refcnt_index=0; refcnt_index < s->refcount_table_size; refcnt_index++){
2172 if (s->refcount_table[refcnt_index] == 0) {
2173 continue;
2175 cluster_index = refcnt_index << (s->cluster_bits - REFCOUNT_SHIFT);
2176 cluster_end = (refcnt_index + 1) << (s->cluster_bits - REFCOUNT_SHIFT);
2177 for ( ; cluster_index < cluster_end; cluster_index++) {
2178 if (get_refcount(bs, cluster_index) == 0)
2179 /* do nothing -- reserved for free counting */;
2180 else
2181 h = cluster_index;
2185 if (high)
2186 *high = (h+1);
2189 static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
2191 BDRVQcowState *s = bs->opaque;
2192 int refcount_table_index, block_index;
2193 int64_t refcount_block_offset;
2195 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2196 if (refcount_table_index >= s->refcount_table_size)
2197 return 0;
2198 refcount_block_offset = s->refcount_table[refcount_table_index];
2199 if (!refcount_block_offset)
2200 return 0;
2201 if (refcount_block_offset != s->refcount_block_cache_offset) {
2202 /* better than nothing: return allocated if read error */
2203 if (load_refcount_block(bs, refcount_block_offset) < 0)
2204 return 1;
2206 block_index = cluster_index &
2207 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2208 return be16_to_cpu(s->refcount_block_cache[block_index]);
2211 /* return < 0 if error */
2212 static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)
2214 BDRVQcowState *s = bs->opaque;
2215 int i, nb_clusters;
2217 nb_clusters = size_to_clusters(s, size);
2218 retry:
2219 for(i = 0; i < nb_clusters; i++) {
2220 int64_t i = s->free_cluster_index++;
2221 if (get_refcount(bs, i) != 0)
2222 goto retry;
2224 #ifdef DEBUG_ALLOC2
2225 printf("alloc_clusters: size=%lld -> %lld\n",
2226 size,
2227 (s->free_cluster_index - nb_clusters) << s->cluster_bits);
2228 #endif
2230 if (s->highest_alloc < s->free_cluster_index)
2231 s->highest_alloc = s->free_cluster_index;
2233 return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
2236 static int64_t alloc_clusters(BlockDriverState *bs, int64_t size)
2238 int64_t offset;
2240 offset = alloc_clusters_noref(bs, size);
2241 update_refcount(bs, offset, size, 1);
2242 return offset;
2245 /* only used to allocate compressed sectors. We try to allocate
2246 contiguous sectors. size must be <= cluster_size */
2247 static int64_t alloc_bytes(BlockDriverState *bs, int size)
2249 BDRVQcowState *s = bs->opaque;
2250 int64_t offset, cluster_offset;
2251 int free_in_cluster;
2253 assert(size > 0 && size <= s->cluster_size);
2254 if (s->free_byte_offset == 0) {
2255 s->free_byte_offset = alloc_clusters(bs, s->cluster_size);
2257 redo:
2258 free_in_cluster = s->cluster_size -
2259 (s->free_byte_offset & (s->cluster_size - 1));
2260 if (size <= free_in_cluster) {
2261 /* enough space in current cluster */
2262 offset = s->free_byte_offset;
2263 s->free_byte_offset += size;
2264 free_in_cluster -= size;
2265 if (free_in_cluster == 0)
2266 s->free_byte_offset = 0;
2267 if ((offset & (s->cluster_size - 1)) != 0)
2268 update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2269 } else {
2270 offset = alloc_clusters(bs, s->cluster_size);
2271 cluster_offset = s->free_byte_offset & ~(s->cluster_size - 1);
2272 if ((cluster_offset + s->cluster_size) == offset) {
2273 /* we are lucky: contiguous data */
2274 offset = s->free_byte_offset;
2275 update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
2276 s->free_byte_offset += size;
2277 } else {
2278 s->free_byte_offset = offset;
2279 goto redo;
2282 return offset;
2285 static void free_clusters(BlockDriverState *bs,
2286 int64_t offset, int64_t size)
2288 update_refcount(bs, offset, size, -1);
2291 static int grow_refcount_table(BlockDriverState *bs, int min_size)
2293 BDRVQcowState *s = bs->opaque;
2294 int new_table_size, new_table_size2, refcount_table_clusters, i, ret;
2295 uint64_t *new_table;
2296 int64_t table_offset;
2297 uint8_t data[12];
2298 int old_table_size;
2299 int64_t old_table_offset;
2301 if (min_size <= s->refcount_table_size)
2302 return 0;
2303 /* compute new table size */
2304 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2305 for(;;) {
2306 if (refcount_table_clusters == 0) {
2307 refcount_table_clusters = 1;
2308 } else {
2309 refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
2311 new_table_size = refcount_table_clusters << (s->cluster_bits - 3);
2312 if (min_size <= new_table_size)
2313 break;
2315 #ifdef DEBUG_ALLOC2
2316 printf("grow_refcount_table from %d to %d\n",
2317 s->refcount_table_size,
2318 new_table_size);
2319 #endif
2320 new_table_size2 = new_table_size * sizeof(uint64_t);
2321 new_table = qemu_mallocz(new_table_size2);
2322 memcpy(new_table, s->refcount_table,
2323 s->refcount_table_size * sizeof(uint64_t));
2324 for(i = 0; i < s->refcount_table_size; i++)
2325 cpu_to_be64s(&new_table[i]);
2326 /* Note: we cannot update the refcount now to avoid recursion */
2327 table_offset = alloc_clusters_noref(bs, new_table_size2);
2328 ret = bdrv_pwrite(s->hd, table_offset, new_table, new_table_size2);
2329 if (ret != new_table_size2)
2330 goto fail;
2331 for(i = 0; i < s->refcount_table_size; i++)
2332 be64_to_cpus(&new_table[i]);
2334 cpu_to_be64w((uint64_t*)data, table_offset);
2335 cpu_to_be32w((uint32_t*)(data + 8), refcount_table_clusters);
2336 if (bdrv_pwrite(s->hd, offsetof(QCowHeader, refcount_table_offset),
2337 data, sizeof(data)) != sizeof(data))
2338 goto fail;
2339 qemu_free(s->refcount_table);
2340 old_table_offset = s->refcount_table_offset;
2341 old_table_size = s->refcount_table_size;
2342 s->refcount_table = new_table;
2343 s->refcount_table_size = new_table_size;
2344 s->refcount_table_offset = table_offset;
2346 update_refcount(bs, table_offset, new_table_size2, 1);
2347 free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));
2348 return 0;
2349 fail:
2350 free_clusters(bs, table_offset, new_table_size2);
2351 qemu_free(new_table);
2352 return -EIO;
2355 /* addend must be 1 or -1 */
2356 /* XXX: cache several refcount block clusters ? */
2357 static int update_cluster_refcount(BlockDriverState *bs,
2358 int64_t cluster_index,
2359 int addend)
2361 BDRVQcowState *s = bs->opaque;
2362 int64_t offset, refcount_block_offset;
2363 int ret, refcount_table_index, block_index, refcount;
2364 uint64_t data64;
2366 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
2367 if (refcount_table_index >= s->refcount_table_size) {
2368 if (addend < 0)
2369 return -EINVAL;
2370 ret = grow_refcount_table(bs, refcount_table_index + 1);
2371 if (ret < 0)
2372 return ret;
2374 refcount_block_offset = s->refcount_table[refcount_table_index];
2375 if (!refcount_block_offset) {
2376 if (addend < 0)
2377 return -EINVAL;
2378 /* create a new refcount block */
2379 /* Note: we cannot update the refcount now to avoid recursion */
2380 offset = alloc_clusters_noref(bs, s->cluster_size);
2381 memset(s->refcount_block_cache, 0, s->cluster_size);
2382 ret = bdrv_pwrite(s->hd, offset, s->refcount_block_cache, s->cluster_size);
2383 if (ret != s->cluster_size)
2384 return -EINVAL;
2385 s->refcount_table[refcount_table_index] = offset;
2386 data64 = cpu_to_be64(offset);
2387 ret = bdrv_pwrite(s->hd, s->refcount_table_offset +
2388 refcount_table_index * sizeof(uint64_t),
2389 &data64, sizeof(data64));
2390 if (ret != sizeof(data64))
2391 return -EINVAL;
2393 refcount_block_offset = offset;
2394 s->refcount_block_cache_offset = offset;
2395 update_refcount(bs, offset, s->cluster_size, 1);
2396 } else {
2397 if (refcount_block_offset != s->refcount_block_cache_offset) {
2398 if (load_refcount_block(bs, refcount_block_offset) < 0)
2399 return -EIO;
2402 /* we can update the count and save it */
2403 block_index = cluster_index &
2404 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
2405 refcount = be16_to_cpu(s->refcount_block_cache[block_index]);
2406 refcount += addend;
2407 if (refcount < 0 || refcount > 0xffff)
2408 return -EINVAL;
2409 if (refcount == 0 && cluster_index < s->free_cluster_index) {
2410 s->free_cluster_index = cluster_index;
2412 s->refcount_block_cache[block_index] = cpu_to_be16(refcount);
2413 if (bdrv_pwrite(s->hd,
2414 refcount_block_offset + (block_index << REFCOUNT_SHIFT),
2415 &s->refcount_block_cache[block_index], 2) != 2)
2416 return -EIO;
2417 return refcount;
2420 static void update_refcount(BlockDriverState *bs,
2421 int64_t offset, int64_t length,
2422 int addend)
2424 BDRVQcowState *s = bs->opaque;
2425 int64_t start, last, cluster_offset;
2427 #ifdef DEBUG_ALLOC2
2428 printf("update_refcount: offset=%lld size=%lld addend=%d\n",
2429 offset, length, addend);
2430 #endif
2431 if (length <= 0)
2432 return;
2433 start = offset & ~(s->cluster_size - 1);
2434 last = (offset + length - 1) & ~(s->cluster_size - 1);
2435 for(cluster_offset = start; cluster_offset <= last;
2436 cluster_offset += s->cluster_size) {
2437 update_cluster_refcount(bs, cluster_offset >> s->cluster_bits, addend);
2441 #ifdef DEBUG_ALLOC
2442 static void inc_refcounts(BlockDriverState *bs,
2443 uint16_t *refcount_table,
2444 int refcount_table_size,
2445 int64_t offset, int64_t size)
2447 BDRVQcowState *s = bs->opaque;
2448 int64_t start, last, cluster_offset;
2449 int k;
2451 if (size <= 0)
2452 return;
2454 start = offset & ~(s->cluster_size - 1);
2455 last = (offset + size - 1) & ~(s->cluster_size - 1);
2456 for(cluster_offset = start; cluster_offset <= last;
2457 cluster_offset += s->cluster_size) {
2458 k = cluster_offset >> s->cluster_bits;
2459 if (k < 0 || k >= refcount_table_size) {
2460 printf("ERROR: invalid cluster offset=0x%llx\n", cluster_offset);
2461 } else {
2462 if (++refcount_table[k] == 0) {
2463 printf("ERROR: overflow cluster offset=0x%llx\n", cluster_offset);
2469 static int check_refcounts_l1(BlockDriverState *bs,
2470 uint16_t *refcount_table,
2471 int refcount_table_size,
2472 int64_t l1_table_offset, int l1_size,
2473 int check_copied)
2475 BDRVQcowState *s = bs->opaque;
2476 uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2;
2477 int l2_size, i, j, nb_csectors, refcount;
2479 l2_table = NULL;
2480 l1_size2 = l1_size * sizeof(uint64_t);
2482 inc_refcounts(bs, refcount_table, refcount_table_size,
2483 l1_table_offset, l1_size2);
2485 l1_table = qemu_malloc(l1_size2);
2486 if (bdrv_pread(s->hd, l1_table_offset,
2487 l1_table, l1_size2) != l1_size2)
2488 goto fail;
2489 for(i = 0;i < l1_size; i++)
2490 be64_to_cpus(&l1_table[i]);
2492 l2_size = s->l2_size * sizeof(uint64_t);
2493 l2_table = qemu_malloc(l2_size);
2494 for(i = 0; i < l1_size; i++) {
2495 l2_offset = l1_table[i];
2496 if (l2_offset) {
2497 if (check_copied) {
2498 refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
2499 if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
2500 printf("ERROR OFLAG_COPIED: l2_offset=%llx refcount=%d\n",
2501 l2_offset, refcount);
2504 l2_offset &= ~QCOW_OFLAG_COPIED;
2505 if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
2506 goto fail;
2507 for(j = 0; j < s->l2_size; j++) {
2508 offset = be64_to_cpu(l2_table[j]);
2509 if (offset != 0) {
2510 if (offset & QCOW_OFLAG_COMPRESSED) {
2511 if (offset & QCOW_OFLAG_COPIED) {
2512 printf("ERROR: cluster %lld: copied flag must never be set for compressed clusters\n",
2513 offset >> s->cluster_bits);
2514 offset &= ~QCOW_OFLAG_COPIED;
2516 nb_csectors = ((offset >> s->csize_shift) &
2517 s->csize_mask) + 1;
2518 offset &= s->cluster_offset_mask;
2519 inc_refcounts(bs, refcount_table,
2520 refcount_table_size,
2521 offset & ~511, nb_csectors * 512);
2522 } else {
2523 if (check_copied) {
2524 refcount = get_refcount(bs, (offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
2525 if ((refcount == 1) != ((offset & QCOW_OFLAG_COPIED) != 0)) {
2526 printf("ERROR OFLAG_COPIED: offset=%llx refcount=%d\n",
2527 offset, refcount);
2530 offset &= ~QCOW_OFLAG_COPIED;
2531 inc_refcounts(bs, refcount_table,
2532 refcount_table_size,
2533 offset, s->cluster_size);
2537 inc_refcounts(bs, refcount_table,
2538 refcount_table_size,
2539 l2_offset,
2540 s->cluster_size);
2543 qemu_free(l1_table);
2544 qemu_free(l2_table);
2545 return 0;
2546 fail:
2547 printf("ERROR: I/O error in check_refcounts_l1\n");
2548 qemu_free(l1_table);
2549 qemu_free(l2_table);
2550 return -EIO;
2553 static void check_refcounts(BlockDriverState *bs)
2555 BDRVQcowState *s = bs->opaque;
2556 int64_t size;
2557 int nb_clusters, refcount1, refcount2, i;
2558 QCowSnapshot *sn;
2559 uint16_t *refcount_table;
2561 size = bdrv_getlength(s->hd);
2562 nb_clusters = size_to_clusters(s, size);
2563 refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));
2565 /* header */
2566 inc_refcounts(bs, refcount_table, nb_clusters,
2567 0, s->cluster_size);
2569 check_refcounts_l1(bs, refcount_table, nb_clusters,
2570 s->l1_table_offset, s->l1_size, 1);
2572 /* snapshots */
2573 for(i = 0; i < s->nb_snapshots; i++) {
2574 sn = s->snapshots + i;
2575 check_refcounts_l1(bs, refcount_table, nb_clusters,
2576 sn->l1_table_offset, sn->l1_size, 0);
2578 inc_refcounts(bs, refcount_table, nb_clusters,
2579 s->snapshots_offset, s->snapshots_size);
2581 /* refcount data */
2582 inc_refcounts(bs, refcount_table, nb_clusters,
2583 s->refcount_table_offset,
2584 s->refcount_table_size * sizeof(uint64_t));
2585 for(i = 0; i < s->refcount_table_size; i++) {
2586 int64_t offset;
2587 offset = s->refcount_table[i];
2588 if (offset != 0) {
2589 inc_refcounts(bs, refcount_table, nb_clusters,
2590 offset, s->cluster_size);
2594 /* compare ref counts */
2595 for(i = 0; i < nb_clusters; i++) {
2596 refcount1 = get_refcount(bs, i);
2597 refcount2 = refcount_table[i];
2598 if (refcount1 != refcount2)
2599 printf("ERROR cluster %d refcount=%d reference=%d\n",
2600 i, refcount1, refcount2);
2603 qemu_free(refcount_table);
2606 #if 0
2607 static void dump_refcounts(BlockDriverState *bs)
2609 BDRVQcowState *s = bs->opaque;
2610 int64_t nb_clusters, k, k1, size;
2611 int refcount;
2613 size = bdrv_getlength(s->hd);
2614 nb_clusters = size_to_clusters(s, size);
2615 for(k = 0; k < nb_clusters;) {
2616 k1 = k;
2617 refcount = get_refcount(bs, k);
2618 k++;
2619 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2620 k++;
2621 printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
2624 #endif
2625 #endif
2627 BlockDriver bdrv_qcow2 = {
2628 .format_name = "qcow2",
2629 .instance_size = sizeof(BDRVQcowState),
2630 .bdrv_probe = qcow_probe,
2631 .bdrv_open = qcow_open,
2632 .bdrv_close = qcow_close,
2633 .bdrv_create = qcow_create,
2634 .bdrv_flush = qcow_flush,
2635 .bdrv_is_allocated = qcow_is_allocated,
2636 .bdrv_set_key = qcow_set_key,
2637 .bdrv_make_empty = qcow_make_empty,
2639 .bdrv_aio_read = qcow_aio_read,
2640 .bdrv_aio_write = qcow_aio_write,
2641 .bdrv_aio_cancel = qcow_aio_cancel,
2642 .aiocb_size = sizeof(QCowAIOCB),
2643 .bdrv_write_compressed = qcow_write_compressed,
2645 .bdrv_snapshot_create = qcow_snapshot_create,
2646 .bdrv_snapshot_goto = qcow_snapshot_goto,
2647 .bdrv_snapshot_delete = qcow_snapshot_delete,
2648 .bdrv_snapshot_list = qcow_snapshot_list,
2649 .bdrv_get_info = qcow_get_info,