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