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