ia64/xen-unstable

changeset 17097:221b2680ffe5

blktap: qcow2 image format support

This patch adds support for the qcow2 image format to blktap. It
consists mostly of qemu code, adapted to the blktap interfaces.
Snapshots and compressed images are supported.

The qcow2 driver may be used by either specifying tap:qcow2 or by
using tap:qcow which will detect that you have a version 2 image and
will call the qcow2 driver.

Signed-off-by: Kevin Wolf <kwolf@suse.de>
author Keir Fraser <keir.fraser@citrix.com>
date Thu Feb 21 10:30:57 2008 +0000 (2008-02-21)
parents ea1dc85d7122
children f1a107ec62b6
files tools/blktap/drivers/Makefile tools/blktap/drivers/aes.h tools/blktap/drivers/blktapctrl.c tools/blktap/drivers/block-qcow.c tools/blktap/drivers/block-qcow2.c tools/blktap/drivers/tapdisk.h tools/python/xen/xend/server/BlktapController.py
line diff
     1.1 --- a/tools/blktap/drivers/Makefile	Wed Feb 20 18:18:03 2008 +0000
     1.2 +++ b/tools/blktap/drivers/Makefile	Thu Feb 21 10:30:57 2008 +0000
     1.3 @@ -27,6 +27,7 @@ BLK-OBJS-y  += block-sync.o
     1.4  BLK-OBJS-y  += block-vmdk.o
     1.5  BLK-OBJS-y  += block-ram.o
     1.6  BLK-OBJS-y  += block-qcow.o
     1.7 +BLK-OBJS-y  += block-qcow2.o
     1.8  BLK-OBJS-y  += aes.o
     1.9  BLK-OBJS-y  += tapaio.o
    1.10  BLK-OBJS-$(CONFIG_Linux) += blk_linux.c
     2.1 --- a/tools/blktap/drivers/aes.h	Wed Feb 20 18:18:03 2008 +0000
     2.2 +++ b/tools/blktap/drivers/aes.h	Thu Feb 21 10:30:57 2008 +0000
     2.3 @@ -1,6 +1,8 @@
     2.4  #ifndef QEMU_AES_H
     2.5  #define QEMU_AES_H
     2.6  
     2.7 +#include <stdint.h>
     2.8 +
     2.9  #define AES_MAXNR 14
    2.10  #define AES_BLOCK_SIZE 16
    2.11  
     3.1 --- a/tools/blktap/drivers/blktapctrl.c	Wed Feb 20 18:18:03 2008 +0000
     3.2 +++ b/tools/blktap/drivers/blktapctrl.c	Thu Feb 21 10:30:57 2008 +0000
     3.3 @@ -181,27 +181,29 @@ static int test_path(char *path, char **
     3.4  {
     3.5  	char *ptr, handle[10];
     3.6  	int i, size, found = 0;
     3.7 +	size_t handle_len;
     3.8  
     3.9  	size = sizeof(dtypes)/sizeof(disk_info_t *);
    3.10  	*type = MAX_DISK_TYPES + 1;
    3.11          *blkif = NULL;
    3.12  
    3.13  	if ( (ptr = strstr(path, ":"))!=NULL) {
    3.14 -		memcpy(handle, path, (ptr - path));
    3.15 +		handle_len = (ptr - path);
    3.16 +		memcpy(handle, path, handle_len);
    3.17  		*dev = ptr + 1;
    3.18 -		ptr = handle + (ptr - path);
    3.19 +		ptr = handle + handle_len;
    3.20  		*ptr = '\0';
    3.21  		DPRINTF("Detected handle: [%s]\n",handle);
    3.22  
    3.23 -		for (i = 0; i < size; i++) 
    3.24 -			if (strncmp(handle, dtypes[i]->handle, 
    3.25 -                                    (ptr - path)) ==0) {
    3.26 +		for (i = 0; i < size; i++) {
    3.27 +			if ((strlen(dtypes[i]->handle) == handle_len) &&
    3.28 +					strncmp(handle, dtypes[i]->handle,
    3.29 +					handle_len) == 0) {
    3.30                                  found = 1;
    3.31 -                                break;
    3.32                          }
    3.33  
    3.34 -                if (found) {
    3.35 -                        *type = dtypes[i]->idnum;
    3.36 +			if (found) {
    3.37 +				*type = dtypes[i]->idnum;
    3.38                          
    3.39                          if (dtypes[i]->single_handler == 1) {
    3.40                                  /* Check whether tapdisk process 
    3.41 @@ -214,6 +216,7 @@ static int test_path(char *path, char **
    3.42                          }
    3.43                          return 0;
    3.44                  }
    3.45 +            }
    3.46          }
    3.47  
    3.48          /* Fall-through case, we didn't find a disk driver. */
     4.1 --- a/tools/blktap/drivers/block-qcow.c	Wed Feb 20 18:18:03 2008 +0000
     4.2 +++ b/tools/blktap/drivers/block-qcow.c	Thu Feb 21 10:30:57 2008 +0000
     4.3 @@ -890,8 +890,20 @@ int tdqcow_open (struct disk_driver *dd,
     4.4  	be32_to_cpus(&header->crypt_method);
     4.5  	be64_to_cpus(&header->l1_table_offset);
     4.6  
     4.7 -	if (header->magic != QCOW_MAGIC || header->version > QCOW_VERSION)
     4.8 +	if (header->magic != QCOW_MAGIC)
     4.9  		goto fail;
    4.10 +
    4.11 +	switch (header->version) {
    4.12 +	case QCOW_VERSION:
    4.13 +		break;
    4.14 +	case 2:
    4.15 +		close(fd);
    4.16 +		dd->drv = &tapdisk_qcow2;
    4.17 +		return dd->drv->td_open(dd, name, flags);
    4.18 +	default:
    4.19 +		goto fail;
    4.20 +	}
    4.21 +
    4.22  	if (header->size <= 1 || header->cluster_bits < 9)
    4.23  		goto fail;
    4.24  	if (header->crypt_method > QCOW_CRYPT_AES)
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/tools/blktap/drivers/block-qcow2.c	Thu Feb 21 10:30:57 2008 +0000
     5.3 @@ -0,0 +1,2327 @@
     5.4 +/*
     5.5 + * Block driver for the QCOW version 2 format
     5.6 + *
     5.7 + * Copyright (c) 2004-2006 Fabrice Bellard
     5.8 + *
     5.9 + * Permission is hereby granted, free of charge, to any person obtaining a copy
    5.10 + * of this software and associated documentation files (the "Software"), to deal
    5.11 + * in the Software without restriction, including without limitation the rights
    5.12 + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    5.13 + * copies of the Software, and to permit persons to whom the Software is
    5.14 + * furnished to do so, subject to the following conditions:
    5.15 + *
    5.16 + * The above copyright notice and this permission notice shall be included in
    5.17 + * all copies or substantial portions of the Software.
    5.18 + *
    5.19 + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    5.20 + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    5.21 + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    5.22 + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    5.23 + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    5.24 + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    5.25 + * THE SOFTWARE.
    5.26 + */
    5.27 +
    5.28 +#include <zlib.h>
    5.29 +#include "aes.h"
    5.30 +#include <assert.h>
    5.31 +#include <stdint.h>
    5.32 +#include <fcntl.h>
    5.33 +#include <stdio.h>
    5.34 +#include <stdlib.h>
    5.35 +#include <string.h>
    5.36 +
    5.37 +#include "tapdisk.h"
    5.38 +#include "tapaio.h"
    5.39 +#include "bswap.h"
    5.40 +
    5.41 +#define USE_AIO
    5.42 +
    5.43 +#define qemu_malloc malloc
    5.44 +#define qemu_mallocz(size) calloc(1, size)
    5.45 +#define qemu_free free
    5.46 +
    5.47 +#ifndef O_BINARY
    5.48 +#define O_BINARY 0
    5.49 +#endif
    5.50 +
    5.51 +#define BLOCK_FLAG_ENCRYPT 1
    5.52 +
    5.53 +/*
    5.54 +  Differences with QCOW:
    5.55 +
    5.56 +  - Support for multiple incremental snapshots.
    5.57 +  - Memory management by reference counts.
    5.58 +  - Clusters which have a reference count of one have the bit
    5.59 +	QCOW_OFLAG_COPIED to optimize write performance.
    5.60 +  - Size of compressed clusters is stored in sectors to reduce bit usage
    5.61 +	in the cluster offsets.
    5.62 +  - Support for storing additional data (such as the VM state) in the
    5.63 +	snapshots.
    5.64 +  - If a backing store is used, the cluster size is not constrained
    5.65 +	(could be backported to QCOW).
    5.66 +  - L2 tables have always a size of one cluster.
    5.67 +*/
    5.68 +
    5.69 +//#define DEBUG_ALLOC
    5.70 +//#define DEBUG_ALLOC2
    5.71 +
    5.72 +#define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
    5.73 +#define QCOW_VERSION 2
    5.74 +
    5.75 +#define QCOW_CRYPT_NONE 0
    5.76 +#define QCOW_CRYPT_AES	1
    5.77 +
    5.78 +/* indicate that the refcount of the referenced cluster is exactly one. */
    5.79 +#define QCOW_OFLAG_COPIED	  (1LL << 63)
    5.80 +/* indicate that the cluster is compressed (they never have the copied flag) */
    5.81 +#define QCOW_OFLAG_COMPRESSED (1LL << 62)
    5.82 +
    5.83 +#define REFCOUNT_SHIFT 1 /* refcount size is 2 bytes */
    5.84 +
    5.85 +#ifndef offsetof
    5.86 +#define offsetof(type, field) ((size_t) &((type *)0)->field)
    5.87 +#endif
    5.88 +
    5.89 +typedef struct QCowHeader {
    5.90 +	uint32_t magic;
    5.91 +	uint32_t version;
    5.92 +	uint64_t backing_file_offset;
    5.93 +	uint32_t backing_file_size;
    5.94 +	uint32_t cluster_bits;
    5.95 +	uint64_t size; /* in bytes */
    5.96 +
    5.97 +	uint32_t crypt_method;
    5.98 +	uint32_t l1_size; /* XXX: save number of clusters instead ? */
    5.99 +	uint64_t l1_table_offset;
   5.100 +	uint64_t refcount_table_offset;
   5.101 +	uint32_t refcount_table_clusters;
   5.102 +	uint32_t nb_snapshots;
   5.103 +	uint64_t snapshots_offset;
   5.104 +} QCowHeader;
   5.105 +
   5.106 +typedef struct __attribute__((packed)) QCowSnapshotHeader {
   5.107 +	/* header is 8 byte aligned */
   5.108 +	uint64_t l1_table_offset;
   5.109 +
   5.110 +	uint32_t l1_size;
   5.111 +	uint16_t id_str_size;
   5.112 +	uint16_t name_size;
   5.113 +
   5.114 +	uint32_t date_sec;
   5.115 +	uint32_t date_nsec;
   5.116 +
   5.117 +	uint64_t vm_clock_nsec;
   5.118 +
   5.119 +	uint32_t vm_state_size;
   5.120 +	uint32_t extra_data_size; /* for extension */
   5.121 +	/* extra data follows */
   5.122 +	/* id_str follows */
   5.123 +	/* name follows  */
   5.124 +} QCowSnapshotHeader;
   5.125 +
   5.126 +#define L2_CACHE_SIZE 16
   5.127 +
   5.128 +typedef struct QCowSnapshot {
   5.129 +	uint64_t l1_table_offset;
   5.130 +	uint32_t l1_size;
   5.131 +	char *id_str;
   5.132 +	char *name;
   5.133 +	uint32_t vm_state_size;
   5.134 +	uint32_t date_sec;
   5.135 +	uint32_t date_nsec;
   5.136 +	uint64_t vm_clock_nsec;
   5.137 +} QCowSnapshot;
   5.138 +
   5.139 +typedef struct BDRVQcowState {
   5.140 +
   5.141 +	/* blktap additions */
   5.142 +	int fd;
   5.143 +	int poll_pipe[2]; /* dummy fd for polling on */
   5.144 +	char* name;
   5.145 +	int encrypted;
   5.146 +	char backing_file[1024];
   5.147 +	struct disk_driver* backing_hd;
   5.148 +
   5.149 +	int64_t total_sectors;
   5.150 +
   5.151 +
   5.152 +	struct {
   5.153 +		tap_aio_context_t    aio_ctx;
   5.154 +		int                  max_aio_reqs;
   5.155 +		struct iocb         *iocb_list;
   5.156 +		struct iocb        **iocb_free;
   5.157 +		struct pending_aio  *pending_aio;
   5.158 +		int                  iocb_free_count;
   5.159 +		struct iocb        **iocb_queue;
   5.160 +		int	             iocb_queued;
   5.161 +		struct io_event     *aio_events;
   5.162 +		
   5.163 +		uint8_t *sector_lock;		   /*Locking bitmap for AIO reads/writes*/
   5.164 +	} async;
   5.165 +
   5.166 +	/* Original qemu variables */
   5.167 +	int cluster_bits;
   5.168 +	int cluster_size;
   5.169 +	int cluster_sectors;
   5.170 +	int l2_bits;
   5.171 +	int l2_size;
   5.172 +	int l1_size;
   5.173 +	int l1_vm_state_index;
   5.174 +	int csize_shift;
   5.175 +	int csize_mask;
   5.176 +	uint64_t cluster_offset_mask;
   5.177 +	uint64_t l1_table_offset;
   5.178 +	uint64_t *l1_table;
   5.179 +	uint64_t *l2_cache;
   5.180 +	uint64_t l2_cache_offsets[L2_CACHE_SIZE];
   5.181 +	uint32_t l2_cache_counts[L2_CACHE_SIZE];
   5.182 +	uint8_t *cluster_cache;
   5.183 +	uint8_t *cluster_data;
   5.184 +	uint64_t cluster_cache_offset;
   5.185 +
   5.186 +	uint64_t *refcount_table;
   5.187 +	uint64_t refcount_table_offset;
   5.188 +	uint32_t refcount_table_size;
   5.189 +	uint64_t refcount_block_cache_offset;
   5.190 +	uint16_t *refcount_block_cache;
   5.191 +	int64_t free_cluster_index;
   5.192 +	int64_t free_byte_offset;
   5.193 +
   5.194 +	uint32_t crypt_method; /* current crypt method, 0 if no key yet */
   5.195 +	uint32_t crypt_method_header;
   5.196 +	AES_KEY aes_encrypt_key;
   5.197 +	AES_KEY aes_decrypt_key;
   5.198 +	uint64_t snapshots_offset;
   5.199 +	int snapshots_size;
   5.200 +	int nb_snapshots;
   5.201 +	QCowSnapshot *snapshots;
   5.202 +} BDRVQcowState;
   5.203 +
   5.204 +static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset);
   5.205 +static int qcow_read(struct disk_driver *bs, uint64_t sector_num,
   5.206 +		uint8_t *buf, int nb_sectors);
   5.207 +
   5.208 +static int qcow_read_snapshots(struct disk_driver *bs);
   5.209 +static void qcow_free_snapshots(struct disk_driver *bs);
   5.210 +
   5.211 +static int refcount_init(struct disk_driver *bs);
   5.212 +static void refcount_close(struct disk_driver *bs);
   5.213 +static int get_refcount(struct disk_driver *bs, int64_t cluster_index);
   5.214 +static int update_cluster_refcount(struct disk_driver *bs,
   5.215 +		int64_t cluster_index,
   5.216 +		int addend);
   5.217 +static void update_refcount(struct disk_driver *bs,
   5.218 +		int64_t offset, int64_t length,
   5.219 +		int addend);
   5.220 +static int64_t alloc_clusters(struct disk_driver *bs, int64_t size);
   5.221 +static int64_t alloc_bytes(struct disk_driver *bs, int size);
   5.222 +static void free_clusters(struct disk_driver *bs,
   5.223 +		int64_t offset, int64_t size);
   5.224 +#ifdef DEBUG_ALLOC
   5.225 +static void check_refcounts(struct disk_driver *bs);
   5.226 +#endif
   5.227 +
   5.228 +static int init_aio_state(struct disk_driver *bs);
   5.229 +static void free_aio_state(struct disk_driver *bs);
   5.230 +
   5.231 +static int qcow_sync_read(struct disk_driver *dd, uint64_t sector,
   5.232 +		int nb_sectors, char *buf, td_callback_t cb,
   5.233 +		int id, void *prv);
   5.234 +
   5.235 +/**
   5.236 + * Read with byte offsets
   5.237 + */
   5.238 +static int bdrv_pread(int fd, int64_t offset, void *buf, int count)
   5.239 +{
   5.240 +	int ret;
   5.241 +
   5.242 +	if (lseek(fd, offset, SEEK_SET) == -1) {
   5.243 +		DPRINTF("bdrv_pread failed seek (%#"PRIx64").\n", offset);
   5.244 +		return -1;
   5.245 +	}
   5.246 +
   5.247 +	ret =  read(fd, buf, count);
   5.248 +	if (ret < 0) {
   5.249 +		if (lseek(fd, 0, SEEK_END) >= offset) {
   5.250 +			DPRINTF("bdrv_pread read failed (%#"PRIx64", END = %#"PRIx64").\n", 
   5.251 +					offset, lseek(fd, 0, SEEK_END));
   5.252 +			return -1;
   5.253 +		}
   5.254 +
   5.255 +		/* Read beyond end of file. Reading zeros. */
   5.256 +		memset(buf, 0, count);
   5.257 +		ret = count;
   5.258 +	} else if (ret < count) {
   5.259 +		/* Read beyond end of file. Filling up with zeros. */
   5.260 +		memset(buf + ret, 0, count - ret);
   5.261 +		ret = count;
   5.262 +	}
   5.263 +	return ret;
   5.264 +}
   5.265 +
   5.266 +/**
   5.267 + * Write with byte offsets
   5.268 + */
   5.269 +static int bdrv_pwrite(int fd, int64_t offset, const void *buf, int count)
   5.270 +{
   5.271 +	int ret;
   5.272 +	
   5.273 +	ret = lseek(fd, offset, SEEK_SET);
   5.274 +	if (ret != offset) {
   5.275 +		DPRINTF("bdrv_pwrite failed seek (%#"PRIx64").\n", offset);
   5.276 +		return -1;
   5.277 +	}
   5.278 +
   5.279 +	return write(fd, buf, count);
   5.280 +}
   5.281 +
   5.282 +
   5.283 +/**
   5.284 + * Read with sector offsets
   5.285 + */
   5.286 +static int bdrv_read(int fd, int64_t offset, void *buf, int count)
   5.287 +{
   5.288 +	return bdrv_pread(fd, 512 * offset, buf, 512 * count);
   5.289 +}
   5.290 +
   5.291 +/**
   5.292 + * Write with sector offsets
   5.293 + */
   5.294 +static int bdrv_write(int fd, int64_t offset, const void *buf, int count)
   5.295 +{
   5.296 +	return bdrv_pwrite(fd, 512 * offset, buf, count);
   5.297 +}
   5.298 +
   5.299 +
   5.300 +static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
   5.301 +{
   5.302 +	const QCowHeader *cow_header = (const void *)buf;
   5.303 +
   5.304 +	if (buf_size >= sizeof(QCowHeader) &&
   5.305 +		be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
   5.306 +		be32_to_cpu(cow_header->version) == QCOW_VERSION)
   5.307 +		return 100;
   5.308 +	else
   5.309 +		return 0;
   5.310 +}
   5.311 +
   5.312 +static int qcow_open(struct disk_driver *bs, const char *filename, td_flag_t flags)
   5.313 +{
   5.314 +	BDRVQcowState *s = bs->private;
   5.315 +	int len, i, shift, ret;
   5.316 +	QCowHeader header;
   5.317 +
   5.318 +	int fd, o_flags;
   5.319 +	
   5.320 +	o_flags = O_LARGEFILE | ((flags == TD_RDONLY) ? O_RDONLY : O_RDWR);
   5.321 +
   5.322 +	DPRINTF("Opening %s\n", filename);
   5.323 +	fd = open(filename, o_flags);
   5.324 +	if (fd < 0) {
   5.325 +		DPRINTF("Unable to open %s (%d)\n", filename, 0 - errno);
   5.326 +		return -1;
   5.327 +	}
   5.328 +
   5.329 +	s->fd = fd;
   5.330 +	if (asprintf(&s->name,"%s", filename) == -1) {
   5.331 +		close(fd);
   5.332 +		return -1;
   5.333 +	}
   5.334 +
   5.335 +	ret = read(fd, &header, sizeof(header));
   5.336 +	if (ret != sizeof(header)) {
   5.337 +		DPRINTF("  ret = %d, errno = %d\n", ret, errno);
   5.338 +		goto fail;
   5.339 +	}
   5.340 +
   5.341 +	be32_to_cpus(&header.magic);
   5.342 +	be32_to_cpus(&header.version);
   5.343 +	be64_to_cpus(&header.backing_file_offset);
   5.344 +	be32_to_cpus(&header.backing_file_size);
   5.345 +	be64_to_cpus(&header.size);
   5.346 +	be32_to_cpus(&header.cluster_bits);
   5.347 +	be32_to_cpus(&header.crypt_method);
   5.348 +	be64_to_cpus(&header.l1_table_offset);
   5.349 +	be32_to_cpus(&header.l1_size);
   5.350 +	be64_to_cpus(&header.refcount_table_offset);
   5.351 +	be32_to_cpus(&header.refcount_table_clusters);
   5.352 +	be64_to_cpus(&header.snapshots_offset);
   5.353 +	be32_to_cpus(&header.nb_snapshots);
   5.354 +
   5.355 +	if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
   5.356 +		goto fail;
   5.357 +
   5.358 +	if (header.size <= 1 ||
   5.359 +		header.cluster_bits < 9 ||
   5.360 +		header.cluster_bits > 16)
   5.361 +		goto fail;
   5.362 +	
   5.363 +	s->crypt_method = 0;
   5.364 +	if (header.crypt_method > QCOW_CRYPT_AES)
   5.365 +		goto fail;
   5.366 +	s->crypt_method_header = header.crypt_method;
   5.367 +	if (s->crypt_method_header)
   5.368 +		s->encrypted = 1;
   5.369 +	s->cluster_bits = header.cluster_bits;
   5.370 +	s->cluster_size = 1 << s->cluster_bits;
   5.371 +	s->cluster_sectors = 1 << (s->cluster_bits - 9);
   5.372 +	s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
   5.373 +	s->l2_size = 1 << s->l2_bits;
   5.374 +	s->total_sectors = header.size / 512;
   5.375 +	s->csize_shift = (62 - (s->cluster_bits - 8));
   5.376 +	s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
   5.377 +	s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
   5.378 +	s->refcount_table_offset = header.refcount_table_offset;
   5.379 +	s->refcount_table_size =
   5.380 +		header.refcount_table_clusters << (s->cluster_bits - 3);
   5.381 +
   5.382 +	s->snapshots_offset = header.snapshots_offset;
   5.383 +	s->nb_snapshots = header.nb_snapshots;
   5.384 +
   5.385 +//	  DPRINTF("-- cluster_bits/size/sectors = %d/%d/%d\n",
   5.386 +//		  s->cluster_bits, s->cluster_size, s->cluster_sectors);
   5.387 +//	  DPRINTF("-- l2_bits/sizes = %d/%d\n",
   5.388 +//		  s->l2_bits, s->l2_size);
   5.389 +
   5.390 +	/* Set sector size and number */
   5.391 +	bs->td_state->sector_size = 512;
   5.392 +	bs->td_state->size = header.size / 512;
   5.393 +	bs->td_state->info = 0;
   5.394 +
   5.395 +	/* read the level 1 table */
   5.396 +	s->l1_size = header.l1_size;
   5.397 +	shift = s->cluster_bits + s->l2_bits;
   5.398 +	s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
   5.399 +	/* the L1 table must contain at least enough entries to put
   5.400 +	   header.size bytes */
   5.401 +	if (s->l1_size < s->l1_vm_state_index) {
   5.402 +		DPRINTF("L1 table tooo small\n");
   5.403 +		goto fail;
   5.404 +	}
   5.405 +	s->l1_table_offset = header.l1_table_offset;
   5.406 +
   5.407 +	s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
   5.408 +	if (!s->l1_table)
   5.409 +		goto fail;
   5.410 +
   5.411 +
   5.412 +	if (lseek(fd, s->l1_table_offset, SEEK_SET) == -1)
   5.413 +		goto fail;
   5.414 +
   5.415 +	if (read(fd, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
   5.416 +			s->l1_size * sizeof(uint64_t)) {
   5.417 +
   5.418 +		DPRINTF("Could not read L1 table\n");
   5.419 +		goto fail;
   5.420 +	}
   5.421 +
   5.422 +	for(i = 0;i < s->l1_size; i++) {
   5.423 +		be64_to_cpus(&s->l1_table[i]);
   5.424 +	}
   5.425 +	/* alloc L2 cache */
   5.426 +	s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
   5.427 +	if (!s->l2_cache)
   5.428 +		goto fail;
   5.429 +	s->cluster_cache = qemu_malloc(s->cluster_size);
   5.430 +	if (!s->cluster_cache)
   5.431 +		goto fail;
   5.432 +	/* one more sector for decompressed data alignment */
   5.433 +	s->cluster_data = qemu_malloc(s->cluster_size + 512);
   5.434 +	if (!s->cluster_data)
   5.435 +		goto fail;
   5.436 +	s->cluster_cache_offset = -1;
   5.437 +
   5.438 +	if (refcount_init(bs) < 0)
   5.439 +		goto fail;
   5.440 +		
   5.441 +	/* read the backing file name */
   5.442 +	s->backing_file[0] = '\0';
   5.443 +	if (header.backing_file_offset != 0) {
   5.444 +		len = header.backing_file_size;
   5.445 +		if (len > 1023)
   5.446 +			len = 1023;
   5.447 +
   5.448 +		if (lseek(fd, header.backing_file_offset, SEEK_SET) == -1) {
   5.449 +			DPRINTF("Could not lseek to %#"PRIx64"\n", header.backing_file_offset);
   5.450 +			goto fail;
   5.451 +		}
   5.452 +
   5.453 +		if (read(fd, s->backing_file, len) != len) {
   5.454 +			DPRINTF("Could not read %#x bytes from %#"PRIx64": %s\n",
   5.455 +				len, header.backing_file_offset,
   5.456 +				strerror(errno));
   5.457 +			goto fail;
   5.458 +		}
   5.459 +
   5.460 +		s->backing_file[len] = '\0';
   5.461 +	}
   5.462 +
   5.463 +#if 0
   5.464 +	s->backing_hd = NULL;
   5.465 +	if (qcow_read_snapshots(bs) < 0) {
   5.466 +		DPRINTF("Could not read backing files\n");
   5.467 +		goto fail;
   5.468 +	}
   5.469 +#endif
   5.470 +
   5.471 +#ifdef DEBUG_ALLOC
   5.472 +	check_refcounts(bs);
   5.473 +#endif
   5.474 +	
   5.475 +	/* Initialize fds */
   5.476 +	for(i = 0; i < MAX_IOFD; i++)
   5.477 +		bs->io_fd[i] = 0;
   5.478 +
   5.479 +#ifdef USE_AIO
   5.480 +	/* Initialize AIO */
   5.481 +	if (init_aio_state(bs)!=0) {
   5.482 +		DPRINTF("Unable to initialise AIO state\n");
   5.483 +		free_aio_state(bs);
   5.484 +		goto fail;
   5.485 +	}
   5.486 +
   5.487 +	bs->io_fd[0] = s->async.aio_ctx.pollfd; 
   5.488 +#else	
   5.489 +	/* Synchronous IO */
   5.490 +	if (pipe(s->poll_pipe)) 
   5.491 +		goto fail;
   5.492 +
   5.493 +	bs->io_fd[0] = s->poll_pipe[0];
   5.494 +#endif
   5.495 +
   5.496 +	return 0;
   5.497 +
   5.498 + fail:
   5.499 +	DPRINTF("qcow_open failed\n");
   5.500 +
   5.501 +#ifdef USE_AIO	
   5.502 +	free_aio_state(bs);
   5.503 +#endif
   5.504 +
   5.505 +	qcow_free_snapshots(bs);
   5.506 +	refcount_close(bs);
   5.507 +	qemu_free(s->l1_table);
   5.508 +	qemu_free(s->l2_cache);
   5.509 +	qemu_free(s->cluster_cache);
   5.510 +	qemu_free(s->cluster_data);
   5.511 +	close(fd);
   5.512 +	return -1;
   5.513 +}
   5.514 +
   5.515 +static int qcow_set_key(struct disk_driver *bs, const char *key)
   5.516 +{
   5.517 +	BDRVQcowState *s = bs->private;
   5.518 +	uint8_t keybuf[16];
   5.519 +	int len, i;
   5.520 +
   5.521 +	memset(keybuf, 0, 16);
   5.522 +	len = strlen(key);
   5.523 +	if (len > 16)
   5.524 +		len = 16;
   5.525 +	/* XXX: we could compress the chars to 7 bits to increase
   5.526 +	   entropy */
   5.527 +	for(i = 0;i < len;i++) {
   5.528 +		keybuf[i] = key[i];
   5.529 +	}
   5.530 +	s->crypt_method = s->crypt_method_header;
   5.531 +
   5.532 +	if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
   5.533 +		return -1;
   5.534 +	if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
   5.535 +		return -1;
   5.536 +#if 0
   5.537 +	/* test */
   5.538 +	{
   5.539 +		uint8_t in[16];
   5.540 +		uint8_t out[16];
   5.541 +		uint8_t tmp[16];
   5.542 +		for(i=0;i<16;i++)
   5.543 +			in[i] = i;
   5.544 +		AES_encrypt(in, tmp, &s->aes_encrypt_key);
   5.545 +		AES_decrypt(tmp, out, &s->aes_decrypt_key);
   5.546 +		for(i = 0; i < 16; i++)
   5.547 +			printf(" %02x", tmp[i]);
   5.548 +		printf("\n");
   5.549 +		for(i = 0; i < 16; i++)
   5.550 +			printf(" %02x", out[i]);
   5.551 +		printf("\n");
   5.552 +	}
   5.553 +#endif
   5.554 +	return 0;
   5.555 +}
   5.556 +
   5.557 +/* The crypt function is compatible with the linux cryptoloop
   5.558 +   algorithm for < 4 GB images. NOTE: out_buf == in_buf is
   5.559 +   supported */
   5.560 +static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
   5.561 +		uint8_t *out_buf, const uint8_t *in_buf,
   5.562 +		int nb_sectors, int enc,
   5.563 +		const AES_KEY *key)
   5.564 +{
   5.565 +	union {
   5.566 +		uint64_t ll[2];
   5.567 +		uint8_t b[16];
   5.568 +	} ivec;
   5.569 +	int i;
   5.570 +
   5.571 +	for(i = 0; i < nb_sectors; i++) {
   5.572 +		ivec.ll[0] = cpu_to_le64(sector_num);
   5.573 +		ivec.ll[1] = 0;
   5.574 +		AES_cbc_encrypt(in_buf, out_buf, 512, key,
   5.575 +						ivec.b, enc);
   5.576 +		sector_num++;
   5.577 +		in_buf += 512;
   5.578 +		out_buf += 512;
   5.579 +	}
   5.580 +}
   5.581 +
   5.582 +static int copy_sectors(struct disk_driver *bs, uint64_t start_sect,
   5.583 +		uint64_t cluster_offset, int n_start, int n_end)
   5.584 +{
   5.585 +	BDRVQcowState *s = bs->private;
   5.586 +	int n, ret;
   5.587 +	
   5.588 +	n = n_end - n_start;
   5.589 +	if (n <= 0)
   5.590 +		return 0;
   5.591 +
   5.592 +	ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);
   5.593 +
   5.594 +	if (ret < 0)
   5.595 +		return ret;
   5.596 +	if (s->crypt_method) {
   5.597 +		encrypt_sectors(s, start_sect + n_start,
   5.598 +				s->cluster_data,
   5.599 +				s->cluster_data, n, 1,
   5.600 +				&s->aes_encrypt_key);
   5.601 +	}
   5.602 +
   5.603 +
   5.604 +	ret = bdrv_pwrite(s->fd, cluster_offset + 512*n_start, s->cluster_data, n*512);
   5.605 +
   5.606 +	if (ret < 0)
   5.607 +		return ret;
   5.608 +	return 0;
   5.609 +}
   5.610 +
   5.611 +static void l2_cache_reset(struct disk_driver *bs)
   5.612 +{
   5.613 +	BDRVQcowState *s = bs->private;
   5.614 +
   5.615 +	memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
   5.616 +	memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
   5.617 +	memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
   5.618 +}
   5.619 +
   5.620 +static inline int l2_cache_new_entry(struct disk_driver *bs)
   5.621 +{
   5.622 +	BDRVQcowState *s = bs->private;
   5.623 +	uint32_t min_count;
   5.624 +	int min_index, i;
   5.625 +
   5.626 +	/* find a new entry in the least used one */
   5.627 +	min_index = 0;
   5.628 +	min_count = 0xffffffff;
   5.629 +	for(i = 0; i < L2_CACHE_SIZE; i++) {
   5.630 +		if (s->l2_cache_counts[i] < min_count) {
   5.631 +			min_count = s->l2_cache_counts[i];
   5.632 +			min_index = i;
   5.633 +		}
   5.634 +	}
   5.635 +	return min_index;
   5.636 +}
   5.637 +
   5.638 +static int64_t align_offset(int64_t offset, int n)
   5.639 +{
   5.640 +	offset = (offset + n - 1) & ~(n - 1);
   5.641 +	return offset;
   5.642 +}
   5.643 +
   5.644 +static int grow_l1_table(struct disk_driver *bs, int min_size)
   5.645 +{
   5.646 +	BDRVQcowState *s = bs->private;
   5.647 +	int new_l1_size, new_l1_size2, ret, i;
   5.648 +	uint64_t *new_l1_table;
   5.649 +	uint64_t new_l1_table_offset;
   5.650 +	uint64_t data64;
   5.651 +	uint32_t data32;
   5.652 +
   5.653 +	new_l1_size = s->l1_size;
   5.654 +	if (min_size <= new_l1_size)
   5.655 +		return 0;
   5.656 +	while (min_size > new_l1_size) {
   5.657 +		new_l1_size = (new_l1_size * 3 + 1) / 2;
   5.658 +	}
   5.659 +
   5.660 +#ifdef DEBUG_ALLOC2
   5.661 +	DPRINTF("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);
   5.662 +#endif
   5.663 +
   5.664 +	new_l1_size2 = sizeof(uint64_t) * new_l1_size;
   5.665 +	new_l1_table = qemu_mallocz(new_l1_size2);
   5.666 +	if (!new_l1_table)
   5.667 +		return -ENOMEM;
   5.668 +	memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
   5.669 +
   5.670 +	/* write new table (align to cluster) */
   5.671 +	new_l1_table_offset = alloc_clusters(bs, new_l1_size2);
   5.672 +
   5.673 +	for(i = 0; i < s->l1_size; i++)
   5.674 +		new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
   5.675 +
   5.676 +
   5.677 +	if (lseek(s->fd, new_l1_table_offset, SEEK_SET) == -1)
   5.678 +		goto fail;
   5.679 +
   5.680 +	ret = write(s->fd, new_l1_table, new_l1_size2);
   5.681 +	if (ret != new_l1_size2)
   5.682 +		goto fail;
   5.683 +
   5.684 +
   5.685 +	for(i = 0; i < s->l1_size; i++)
   5.686 +		new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
   5.687 +
   5.688 +	/* set new table */
   5.689 +	data64 = cpu_to_be64(new_l1_table_offset);
   5.690 +
   5.691 +	if (lseek(s->fd, offsetof(QCowHeader, l1_table_offset), SEEK_SET) == -1)
   5.692 +		goto fail;
   5.693 +
   5.694 +	if (write(s->fd, &data64, sizeof(data64)) != sizeof(data64))
   5.695 +		goto fail;
   5.696 +
   5.697 +	data32 = cpu_to_be32(new_l1_size);
   5.698 +
   5.699 +	if (bdrv_pwrite(s->fd, offsetof(QCowHeader, l1_size),
   5.700 +					&data32, sizeof(data32)) != sizeof(data32))
   5.701 +		goto fail;
   5.702 +	qemu_free(s->l1_table);
   5.703 +	free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));
   5.704 +	s->l1_table_offset = new_l1_table_offset;
   5.705 +	s->l1_table = new_l1_table;
   5.706 +	s->l1_size = new_l1_size;
   5.707 +	return 0;
   5.708 + fail:
   5.709 +	qemu_free(s->l1_table);
   5.710 +	return -EIO;
   5.711 +}
   5.712 +
   5.713 +/* 'allocate' is:
   5.714 + *
   5.715 + * 0 not to allocate.
   5.716 + *
   5.717 + * 1 to allocate a normal cluster (for sector indexes 'n_start' to
   5.718 + * 'n_end')
   5.719 + *
   5.720 + * 2 to allocate a compressed cluster of size
   5.721 + * 'compressed_size'. 'compressed_size' must be > 0 and <
   5.722 + * cluster_size
   5.723 + *
   5.724 + * return 0 if not allocated.
   5.725 + */
   5.726 +static uint64_t get_cluster_offset(struct disk_driver *bs,
   5.727 +		uint64_t offset, int allocate,
   5.728 +		int compressed_size,
   5.729 +		int n_start, int n_end)
   5.730 +{
   5.731 +	BDRVQcowState *s = bs->private;
   5.732 +	int min_index, i, j, l1_index, l2_index, ret;
   5.733 +	uint64_t l2_offset, *l2_table, cluster_offset, tmp, old_l2_offset;
   5.734 +
   5.735 +	l1_index = offset >> (s->l2_bits + s->cluster_bits);
   5.736 +	if (l1_index >= s->l1_size) {
   5.737 +		/* outside l1 table is allowed: we grow the table if needed */
   5.738 +		if (!allocate)
   5.739 +			return 0;
   5.740 +
   5.741 +		if (grow_l1_table(bs, l1_index + 1) < 0) {
   5.742 +			DPRINTF("Could not grow L1 table");
   5.743 +			return 0;
   5.744 +		}
   5.745 +	}
   5.746 +
   5.747 +	l2_offset = s->l1_table[l1_index];
   5.748 +	if (!l2_offset) {
   5.749 +		if (!allocate)
   5.750 +			return 0;
   5.751 +
   5.752 +	l2_allocate:
   5.753 +		old_l2_offset = l2_offset;
   5.754 +		/* allocate a new l2 entry */
   5.755 +		l2_offset = alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
   5.756 +		
   5.757 +		/* update the L1 entry */
   5.758 +		s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
   5.759 +		tmp = cpu_to_be64(l2_offset | QCOW_OFLAG_COPIED);
   5.760 +		if (bdrv_pwrite(s->fd, s->l1_table_offset + l1_index * sizeof(tmp),
   5.761 +						&tmp, sizeof(tmp)) != sizeof(tmp))
   5.762 +			return 0;
   5.763 +		min_index = l2_cache_new_entry(bs);
   5.764 +		l2_table = s->l2_cache + (min_index << s->l2_bits);
   5.765 +
   5.766 +		if (old_l2_offset == 0) {
   5.767 +			memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
   5.768 +		} else {
   5.769 +			if (bdrv_pread(s->fd, old_l2_offset,
   5.770 +						   l2_table, s->l2_size * sizeof(uint64_t)) !=
   5.771 +				s->l2_size * sizeof(uint64_t))
   5.772 +				return 0;
   5.773 +		}
   5.774 +		if (bdrv_pwrite(s->fd, l2_offset,
   5.775 +						l2_table, s->l2_size * sizeof(uint64_t)) !=
   5.776 +			s->l2_size * sizeof(uint64_t))
   5.777 +			return 0;
   5.778 +	} else {
   5.779 +		if (!(l2_offset & QCOW_OFLAG_COPIED)) {
   5.780 +			if (allocate) {
   5.781 +				free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t));
   5.782 +				goto l2_allocate;
   5.783 +			}
   5.784 +		} else {
   5.785 +			l2_offset &= ~QCOW_OFLAG_COPIED;
   5.786 +		}
   5.787 +		for(i = 0; i < L2_CACHE_SIZE; i++) {
   5.788 +			if (l2_offset == s->l2_cache_offsets[i]) {
   5.789 +				/* increment the hit count */
   5.790 +				if (++s->l2_cache_counts[i] == 0xffffffff) {
   5.791 +					for(j = 0; j < L2_CACHE_SIZE; j++) {
   5.792 +						s->l2_cache_counts[j] >>= 1;
   5.793 +					}
   5.794 +				}
   5.795 +				l2_table = s->l2_cache + (i << s->l2_bits);
   5.796 +				goto found;
   5.797 +			}
   5.798 +		}
   5.799 +		/* not found: load a new entry in the least used one */
   5.800 +		min_index = l2_cache_new_entry(bs);
   5.801 +		l2_table = s->l2_cache + (min_index << s->l2_bits);
   5.802 +
   5.803 +		if (bdrv_pread(s->fd, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
   5.804 +			s->l2_size * sizeof(uint64_t))
   5.805 +		{
   5.806 +			DPRINTF("Could not read L2 table");
   5.807 +			return 0;
   5.808 +		}
   5.809 +	}
   5.810 +	s->l2_cache_offsets[min_index] = l2_offset;
   5.811 +	s->l2_cache_counts[min_index] = 1;
   5.812 +found:
   5.813 +	l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
   5.814 +
   5.815 +	cluster_offset = be64_to_cpu(l2_table[l2_index]);
   5.816 +	if (!cluster_offset) {
   5.817 +		if (!allocate) {
   5.818 +			return cluster_offset;
   5.819 +		}
   5.820 +	} else if (!(cluster_offset & QCOW_OFLAG_COPIED)) {
   5.821 +		if (!allocate)
   5.822 +			return cluster_offset;
   5.823 +		/* free the cluster */
   5.824 +		if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
   5.825 +			int nb_csectors;
   5.826 +			nb_csectors = ((cluster_offset >> s->csize_shift) &
   5.827 +					s->csize_mask) + 1;
   5.828 +			free_clusters(bs, (cluster_offset & s->cluster_offset_mask) & ~511,
   5.829 +					nb_csectors * 512);
   5.830 +		} else {
   5.831 +			free_clusters(bs, cluster_offset, s->cluster_size);
   5.832 +		}
   5.833 +	} else {
   5.834 +		cluster_offset &= ~QCOW_OFLAG_COPIED;
   5.835 +		return cluster_offset;
   5.836 +	}
   5.837 +	if (allocate == 1) {
   5.838 +		/* allocate a new cluster */
   5.839 +		cluster_offset = alloc_clusters(bs, s->cluster_size);
   5.840 +
   5.841 +		/* we must initialize the cluster content which won't be
   5.842 +		   written */
   5.843 +		if ((n_end - n_start) < s->cluster_sectors) {
   5.844 +			uint64_t start_sect;
   5.845 +
   5.846 +			start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
   5.847 +			ret = copy_sectors(bs, start_sect,
   5.848 +					cluster_offset, 0, n_start);
   5.849 +			if (ret < 0)
   5.850 +				return 0;
   5.851 +			ret = copy_sectors(bs, start_sect,
   5.852 +					cluster_offset, n_end, s->cluster_sectors);
   5.853 +			if (ret < 0)
   5.854 +				return 0;
   5.855 +		}
   5.856 +		tmp = cpu_to_be64(cluster_offset | QCOW_OFLAG_COPIED);
   5.857 +	} else {
   5.858 +		int nb_csectors;
   5.859 +		cluster_offset = alloc_bytes(bs, compressed_size);
   5.860 +		nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
   5.861 +			(cluster_offset >> 9);
   5.862 +		cluster_offset |= QCOW_OFLAG_COMPRESSED |
   5.863 +			((uint64_t)nb_csectors << s->csize_shift);
   5.864 +		/* compressed clusters never have the copied flag */
   5.865 +		tmp = cpu_to_be64(cluster_offset);
   5.866 +	}
   5.867 +	/* update L2 table */
   5.868 +	l2_table[l2_index] = tmp;
   5.869 +
   5.870 +	if (bdrv_pwrite(s->fd, l2_offset + l2_index * sizeof(tmp), &tmp, sizeof(tmp)) != sizeof(tmp))
   5.871 +		return 0;
   5.872 +	return cluster_offset;
   5.873 +}
   5.874 +
   5.875 +static int qcow_is_allocated(struct disk_driver *bs, int64_t sector_num,
   5.876 +		int nb_sectors, int *pnum)
   5.877 +{
   5.878 +	BDRVQcowState *s = bs->private;
   5.879 +	int index_in_cluster, n;
   5.880 +	uint64_t cluster_offset;
   5.881 +
   5.882 +	cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
   5.883 +	index_in_cluster = sector_num & (s->cluster_sectors - 1);
   5.884 +	n = s->cluster_sectors - index_in_cluster;
   5.885 +	if (n > nb_sectors)
   5.886 +		n = nb_sectors;
   5.887 +	*pnum = n;
   5.888 +	return (cluster_offset != 0);
   5.889 +}
   5.890 +
   5.891 +static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
   5.892 +		const uint8_t *buf, int buf_size)
   5.893 +{
   5.894 +	z_stream strm1, *strm = &strm1;
   5.895 +	int ret, out_len;
   5.896 +
   5.897 +	memset(strm, 0, sizeof(*strm));
   5.898 +
   5.899 +	strm->next_in = (uint8_t *)buf;
   5.900 +	strm->avail_in = buf_size;
   5.901 +	strm->next_out = out_buf;
   5.902 +	strm->avail_out = out_buf_size;
   5.903 +
   5.904 +	ret = inflateInit2(strm, -12);
   5.905 +	if (ret != Z_OK)
   5.906 +		return -1;
   5.907 +	ret = inflate(strm, Z_FINISH);
   5.908 +	out_len = strm->next_out - out_buf;
   5.909 +	if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
   5.910 +		out_len != out_buf_size) {
   5.911 +		inflateEnd(strm);
   5.912 +		return -1;
   5.913 +	}
   5.914 +	inflateEnd(strm);
   5.915 +	return 0;
   5.916 +}
   5.917 +
   5.918 +static int decompress_cluster(BDRVQcowState *s, uint64_t cluster_offset)
   5.919 +{
   5.920 +	int ret, csize, nb_csectors, sector_offset;
   5.921 +	uint64_t coffset;
   5.922 +
   5.923 +	coffset = cluster_offset & s->cluster_offset_mask;
   5.924 +	if (s->cluster_cache_offset != coffset) {
   5.925 +		nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
   5.926 +		sector_offset = coffset & 511;
   5.927 +		csize = nb_csectors * 512 - sector_offset;
   5.928 +		ret = bdrv_read(s->fd, coffset >> 9, s->cluster_data, nb_csectors);
   5.929 +		if (ret < 0) {
   5.930 +			return -1;
   5.931 +		}
   5.932 +		if (decompress_buffer(s->cluster_cache, s->cluster_size,
   5.933 +							  s->cluster_data + sector_offset, csize) < 0) {
   5.934 +			return -1;
   5.935 +		}
   5.936 +		s->cluster_cache_offset = coffset;
   5.937 +	}
   5.938 +	return 0;
   5.939 +}
   5.940 +
   5.941 +/* handle reading after the end of the backing file */
   5.942 +static int backing_read1(struct disk_driver *bs,
   5.943 +		int64_t sector_num, uint8_t *buf, int nb_sectors)
   5.944 +{
   5.945 +	int n1;
   5.946 +	BDRVQcowState* s = bs->private;
   5.947 +
   5.948 +	if ((sector_num + nb_sectors) <= s->total_sectors)
   5.949 +		return nb_sectors;
   5.950 +	if (sector_num >= s->total_sectors)
   5.951 +		n1 = 0;
   5.952 +	else
   5.953 +		n1 = s->total_sectors - sector_num;
   5.954 +	memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
   5.955 +	return n1;
   5.956 +}
   5.957 +
   5.958 +/**
   5.959 + * Reads a number of sectors from the image (synchronous)
   5.960 + */
   5.961 +static int qcow_read(struct disk_driver *bs, uint64_t sector_num,
   5.962 +		uint8_t *buf, int nb_sectors)
   5.963 +{
   5.964 +	BDRVQcowState *s = bs->private;
   5.965 +	int ret, index_in_cluster, n, n1;
   5.966 +	uint64_t cluster_offset;
   5.967 +
   5.968 +	while (nb_sectors > 0) {
   5.969 +		cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
   5.970 +		index_in_cluster = sector_num & (s->cluster_sectors - 1);
   5.971 +		n = s->cluster_sectors - index_in_cluster;
   5.972 +		if (n > nb_sectors)
   5.973 +			n = nb_sectors;
   5.974 +		if (!cluster_offset) {
   5.975 +
   5.976 +			if (bs->next) {
   5.977 +
   5.978 +				/* Read from backing file */
   5.979 +				struct disk_driver *parent = bs->next;
   5.980 +
   5.981 +				ret = qcow_sync_read(parent, sector_num, 
   5.982 +						nb_sectors, (char*) buf, NULL, 0, NULL);
   5.983 +
   5.984 +#if 0		
   5.985 +				/* read from the base image */
   5.986 +				n1 = backing_read1(s->backing_hd, sector_num, buf, n);
   5.987 +				if (n1 > 0) {
   5.988 +					ret = bdrv_read(((BDRVQcowState*) s->backing_hd)->fd, sector_num, buf, n1);
   5.989 +					if (ret < 0) {
   5.990 +						DPRINTF("read from backing file failed: ret = %d; errno = %d\n", ret, errno);
   5.991 +						return -1;
   5.992 +					}
   5.993 +				}
   5.994 +#endif
   5.995 +			} else {
   5.996 +				memset(buf, 0, 512 * n);
   5.997 +			}
   5.998 +		} else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
   5.999 +			if (decompress_cluster(s, cluster_offset) < 0) {
  5.1000 +				DPRINTF("read/decompression failed: errno = %d\n", errno);
  5.1001 +				return -1;
  5.1002 +			}
  5.1003 +			memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
  5.1004 +		} else {
  5.1005 +			ret = bdrv_pread(s->fd, cluster_offset + index_in_cluster * 512, buf, n * 512);
  5.1006 +			if (ret != n * 512) {
  5.1007 +				DPRINTF("read failed: ret = %d != n * 512 = %d; errno = %d\n", ret, n * 512, errno);
  5.1008 +				DPRINTF("  cluster_offset = %"PRIx64", index = %d; sector_num = %"PRId64"", cluster_offset, index_in_cluster, sector_num);
  5.1009 +				return -1;
  5.1010 +			}
  5.1011 +
  5.1012 +			if (s->crypt_method) {
  5.1013 +				encrypt_sectors(s, sector_num, buf, buf, n, 0,
  5.1014 +						&s->aes_decrypt_key);
  5.1015 +			}
  5.1016 +		}
  5.1017 +		nb_sectors -= n;
  5.1018 +		sector_num += n;
  5.1019 +		buf += n * 512;
  5.1020 +	}
  5.1021 +	return 0;
  5.1022 +}
  5.1023 +
  5.1024 +/**
  5.1025 + * Writes a number of sectors to the image (synchronous)
  5.1026 + */
  5.1027 +static int qcow_write(struct disk_driver *bs, uint64_t sector_num,
  5.1028 +		const uint8_t *buf, int nb_sectors)
  5.1029 +{
  5.1030 +	BDRVQcowState *s = bs->private;
  5.1031 +	int ret, index_in_cluster, n;
  5.1032 +	uint64_t cluster_offset;
  5.1033 +
  5.1034 +	while (nb_sectors > 0) {
  5.1035 +		index_in_cluster = sector_num & (s->cluster_sectors - 1);
  5.1036 +		n = s->cluster_sectors - index_in_cluster;
  5.1037 +		if (n > nb_sectors)
  5.1038 +			n = nb_sectors;
  5.1039 +		cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
  5.1040 +											index_in_cluster,
  5.1041 +											index_in_cluster + n);
  5.1042 +		if (!cluster_offset) {
  5.1043 +			DPRINTF("qcow_write: cluster_offset == 0\n");
  5.1044 +			DPRINTF("  index = %d; sector_num = %"PRId64"\n", 
  5.1045 +				index_in_cluster, sector_num);
  5.1046 +			return -1;
  5.1047 +		}
  5.1048 +
  5.1049 +		if (s->crypt_method) {
  5.1050 +			encrypt_sectors(s, sector_num, s->cluster_data, buf, n, 1,
  5.1051 +					&s->aes_encrypt_key);
  5.1052 +			ret = bdrv_pwrite(s->fd, cluster_offset + index_in_cluster * 512,
  5.1053 +					s->cluster_data, n * 512);
  5.1054 +		} else {
  5.1055 +			ret = bdrv_pwrite(s->fd, cluster_offset + index_in_cluster * 512, buf, n * 512);
  5.1056 +		}
  5.1057 +		if (ret != n * 512) {
  5.1058 +			DPRINTF("write failed: ret = %d != n * 512 = %d; errno = %d\n", ret, n * 512, errno);
  5.1059 +			DPRINTF("  cluster_offset = %"PRIx64", index = %d; sector_num = %"PRId64"\n", cluster_offset, index_in_cluster, sector_num);
  5.1060 +			return -1;
  5.1061 +		}
  5.1062 +
  5.1063 +		nb_sectors -= n;
  5.1064 +		sector_num += n;
  5.1065 +		buf += n * 512;
  5.1066 +	}
  5.1067 +	s->cluster_cache_offset = -1; /* disable compressed cache */
  5.1068 +	return 0;
  5.1069 +}
  5.1070 +
  5.1071 +
  5.1072 +
  5.1073 +#ifdef USE_AIO
  5.1074 +
  5.1075 +/*
  5.1076 + * General AIO helper functions
  5.1077 + */
  5.1078 +
  5.1079 +#define IOCB_IDX(_s, _io) ((_io) - (_s)->async.iocb_list)
  5.1080 +
  5.1081 +struct pending_aio {
  5.1082 +	td_callback_t cb;
  5.1083 +	int id;
  5.1084 +	void *private;
  5.1085 +	int nb_sectors;
  5.1086 +	char *buf;
  5.1087 +	uint64_t sector;
  5.1088 +};
  5.1089 +
  5.1090 +
  5.1091 +static int init_aio_state(struct disk_driver *dd)
  5.1092 +{
  5.1093 +	int i, ret;
  5.1094 +	struct td_state *bs = dd->td_state;
  5.1095 +	struct BDRVQcowState *s = (struct BDRVQcowState*) dd->private;
  5.1096 +	long ioidx;
  5.1097 +
  5.1098 +	s->async.iocb_list = NULL;
  5.1099 +	s->async.pending_aio = NULL;
  5.1100 +	s->async.aio_events = NULL;
  5.1101 +	s->async.iocb_free = NULL;
  5.1102 +	s->async.iocb_queue = NULL;
  5.1103 +
  5.1104 +	/*Initialize Locking bitmap*/
  5.1105 +	s->async.sector_lock = calloc(1, bs->size);
  5.1106 +		
  5.1107 +	if (!s->async.sector_lock) {
  5.1108 +		DPRINTF("Failed to allocate sector lock\n");
  5.1109 +		goto fail;
  5.1110 +	}
  5.1111 +
  5.1112 +	/* A segment (i.e. a page) can span multiple clusters */
  5.1113 +	s->async.max_aio_reqs = ((getpagesize() / s->cluster_size) + 1) *
  5.1114 +		MAX_SEGMENTS_PER_REQ * MAX_REQUESTS;
  5.1115 +
  5.1116 +	/* Initialize AIO */
  5.1117 +	s->async.iocb_free_count = s->async.max_aio_reqs;
  5.1118 +	s->async.iocb_queued	 = 0;
  5.1119 +
  5.1120 +	if (!(s->async.iocb_list = malloc(sizeof(struct iocb) * s->async.max_aio_reqs)) ||
  5.1121 +		!(s->async.pending_aio = malloc(sizeof(struct pending_aio) * s->async.max_aio_reqs)) ||
  5.1122 +		!(s->async.aio_events = malloc(sizeof(struct io_event) * s->async.max_aio_reqs)) ||
  5.1123 +		!(s->async.iocb_free = malloc(sizeof(struct iocb *) * s->async.max_aio_reqs)) ||
  5.1124 +		!(s->async.iocb_queue = malloc(sizeof(struct iocb *) * s->async.max_aio_reqs))) 
  5.1125 +	{
  5.1126 +		DPRINTF("Failed to allocate AIO structs (max_aio_reqs = %d)\n",
  5.1127 +				s->async.max_aio_reqs);
  5.1128 +		goto fail;
  5.1129 +	}
  5.1130 +
  5.1131 +	ret = tap_aio_setup(&s->async.aio_ctx, s->async.aio_events, s->async.max_aio_reqs);
  5.1132 +	if (ret < 0) {
  5.1133 +		if (ret == -EAGAIN) {
  5.1134 +			DPRINTF("Couldn't setup AIO context.  If you are "
  5.1135 +				"trying to concurrently use a large number "
  5.1136 +				"of blktap-based disks, you may need to "
  5.1137 +				"increase the system-wide aio request limit. "
  5.1138 +				"(e.g. 'echo echo 1048576 > /proc/sys/fs/"
  5.1139 +				"aio-max-nr')\n");
  5.1140 +		} else {
  5.1141 +			DPRINTF("Couldn't setup AIO context.\n");
  5.1142 +		}
  5.1143 +		goto fail;
  5.1144 +	}
  5.1145 +
  5.1146 +	for (i=0;i<s->async.max_aio_reqs;i++)
  5.1147 +			s->async.iocb_free[i] = &s->async.iocb_list[i];
  5.1148 +
  5.1149 +	DPRINTF("AIO state initialised\n");
  5.1150 +
  5.1151 +	return 0;
  5.1152 +
  5.1153 +fail:
  5.1154 +	return -1;
  5.1155 +}
  5.1156 +
  5.1157 +static void free_aio_state(struct disk_driver *dd)
  5.1158 +{
  5.1159 +	struct BDRVQcowState *s = (struct BDRVQcowState*) dd->private;
  5.1160 +
  5.1161 +	if (s->async.sector_lock)
  5.1162 +		free(s->async.sector_lock);
  5.1163 +	if (s->async.iocb_list)
  5.1164 +		free(s->async.iocb_list);
  5.1165 +	if (s->async.pending_aio)
  5.1166 +		free(s->async.pending_aio);
  5.1167 +	if (s->async.aio_events)
  5.1168 +		free(s->async.aio_events);
  5.1169 +	if (s->async.iocb_free)
  5.1170 +		free(s->async.iocb_free);
  5.1171 +	if (s->async.iocb_queue)
  5.1172 +		free(s->async.iocb_queue);
  5.1173 +}
  5.1174 +
  5.1175 +static int async_read(struct BDRVQcowState *s, int size, 
  5.1176 +		uint64_t offset, char *buf, td_callback_t cb,
  5.1177 +		int id, uint64_t sector, void *private)
  5.1178 +{
  5.1179 +	struct	 iocb *io;
  5.1180 +	struct	 pending_aio *pio;
  5.1181 +	long	 ioidx;
  5.1182 +
  5.1183 +	io = s->async.iocb_free[--s->async.iocb_free_count];
  5.1184 +
  5.1185 +	ioidx = IOCB_IDX(s, io);
  5.1186 +	pio = &s->async.pending_aio[ioidx];
  5.1187 +	pio->cb = cb;
  5.1188 +	pio->id = id;
  5.1189 +	pio->private = private;
  5.1190 +	pio->nb_sectors = size/512;
  5.1191 +	pio->buf = buf;
  5.1192 +	pio->sector = sector;
  5.1193 +
  5.1194 +	io_prep_pread(io, s->fd, buf, size, offset);
  5.1195 +	io->data = (void *)ioidx;
  5.1196 +
  5.1197 +	s->async.iocb_queue[s->async.iocb_queued++] = io;
  5.1198 +
  5.1199 +	return 1;
  5.1200 +}
  5.1201 +
  5.1202 +static int async_write(struct BDRVQcowState *s, int size,
  5.1203 +		uint64_t offset, char *buf, td_callback_t cb,
  5.1204 +		int id, uint64_t sector, void *private)
  5.1205 +{
  5.1206 +	struct	 iocb *io;
  5.1207 +	struct	 pending_aio *pio;
  5.1208 +	long	 ioidx;
  5.1209 +
  5.1210 +	io = s->async.iocb_free[--s->async.iocb_free_count];
  5.1211 +
  5.1212 +	ioidx = IOCB_IDX(s, io);
  5.1213 +	pio = &s->async.pending_aio[ioidx];
  5.1214 +	pio->cb = cb;
  5.1215 +	pio->id = id;
  5.1216 +	pio->private = private;
  5.1217 +	pio->nb_sectors = size/512;
  5.1218 +	pio->buf = buf;
  5.1219 +	pio->sector = sector;
  5.1220 +
  5.1221 +	io_prep_pwrite(io, s->fd, buf, size, offset);
  5.1222 +	io->data = (void *)ioidx;
  5.1223 +
  5.1224 +	s->async.iocb_queue[s->async.iocb_queued++] = io;
  5.1225 +
  5.1226 +	return 1;
  5.1227 +}
  5.1228 +
  5.1229 +static int async_submit(struct disk_driver *dd)
  5.1230 +{
  5.1231 +	int ret;
  5.1232 +	struct BDRVQcowState *prv = (struct BDRVQcowState*) dd->private;
  5.1233 +
  5.1234 +	if (!prv->async.iocb_queued)
  5.1235 +		return 0;
  5.1236 +
  5.1237 +	ret = io_submit(prv->async.aio_ctx.aio_ctx, prv->async.iocb_queued, prv->async.iocb_queue);
  5.1238 +
  5.1239 +	/* XXX: TODO: Handle error conditions here. */
  5.1240 +
  5.1241 +	/* Success case: */
  5.1242 +	prv->async.iocb_queued = 0;
  5.1243 +
  5.1244 +	return 0;
  5.1245 +}
  5.1246 +
  5.1247 +/*TODO: Fix sector span!*/
  5.1248 +static int aio_can_lock(struct BDRVQcowState *s, uint64_t sector)
  5.1249 +{
  5.1250 +	return (s->async.sector_lock[sector] ? 0 : 1);
  5.1251 +}
  5.1252 +
  5.1253 +static int aio_lock(struct BDRVQcowState *s, uint64_t sector)
  5.1254 +{
  5.1255 +	return ++s->async.sector_lock[sector];
  5.1256 +}
  5.1257 +
  5.1258 +static void aio_unlock(struct BDRVQcowState *s, uint64_t sector)
  5.1259 +{
  5.1260 +	if (!s->async.sector_lock[sector]) return;
  5.1261 +
  5.1262 +	--s->async.sector_lock[sector];
  5.1263 +	return;
  5.1264 +}
  5.1265 +
  5.1266 +
  5.1267 +
  5.1268 +
  5.1269 +/*
  5.1270 + * QCOW2 specific AIO functions
  5.1271 + */
  5.1272 +
  5.1273 +static int qcow_queue_read(struct disk_driver *bs, uint64_t sector,
  5.1274 +		int nb_sectors, char *buf, td_callback_t cb,
  5.1275 +		int id, void *private)
  5.1276 +{
  5.1277 +	BDRVQcowState *s = bs->private;
  5.1278 +	int i, index_in_cluster, n, ret;
  5.1279 +	int rsp = 0;
  5.1280 +	uint64_t cluster_offset;
  5.1281 +
  5.1282 +	/*Check we can get a lock*/
  5.1283 +	for (i = 0; i < nb_sectors; i++) 
  5.1284 +		if (!aio_can_lock(s, sector + i)) 
  5.1285 +			return cb(bs, -EBUSY, sector, nb_sectors, id, private);
  5.1286 +
  5.1287 +	while (nb_sectors > 0) {
  5.1288 +		
  5.1289 +		cluster_offset = get_cluster_offset(bs, sector << 9, 0, 0, 0, 0);
  5.1290 +				
  5.1291 +		index_in_cluster = sector & (s->cluster_sectors - 1);
  5.1292 +		n = s->cluster_sectors - index_in_cluster;
  5.1293 +		if (n > nb_sectors)
  5.1294 +			n = nb_sectors;
  5.1295 +
  5.1296 +		if (s->async.iocb_free_count == 0 || !aio_lock(s, sector)) 
  5.1297 +			return cb(bs, -EBUSY, sector, nb_sectors, id, private);
  5.1298 +
  5.1299 +		if (!cluster_offset) {
  5.1300 +
  5.1301 +			/* The requested sector is not allocated */
  5.1302 +			aio_unlock(s, sector);
  5.1303 +			ret = cb(bs, BLK_NOT_ALLOCATED, 
  5.1304 +					sector, n, id, private);
  5.1305 +			if (ret == -EBUSY) {
  5.1306 +				/* mark remainder of request
  5.1307 +				 * as busy and try again later */
  5.1308 +				return cb(bs, -EBUSY, sector + n,
  5.1309 +						nb_sectors - n, id, private);
  5.1310 +			} else {
  5.1311 +				rsp += ret;
  5.1312 +			}
  5.1313 +
  5.1314 +		} else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
  5.1315 +
  5.1316 +			/* sync read for compressed clusters */
  5.1317 +			aio_unlock(s, sector);
  5.1318 +			if (decompress_cluster(s, cluster_offset) < 0) {
  5.1319 +				rsp += cb(bs, -EIO, sector, nb_sectors, id, private);
  5.1320 +				goto done;
  5.1321 +			}
  5.1322 +			memcpy(buf, s->cluster_cache + index_in_cluster * 512, 
  5.1323 +					512 * n);
  5.1324 +			rsp += cb(bs, 0, sector, n, id, private);
  5.1325 +
  5.1326 +		} else {
  5.1327 +
  5.1328 +			/* async read */
  5.1329 +			async_read(s, n * 512, 
  5.1330 +					(cluster_offset + index_in_cluster * 512),
  5.1331 +					buf, cb, id, sector, private);
  5.1332 +		}
  5.1333 +
  5.1334 +		/* Prepare for next sector to read */
  5.1335 +		nb_sectors -= n;
  5.1336 +		sector += n;
  5.1337 +		buf += n * 512;
  5.1338 +	}
  5.1339 +
  5.1340 +done:
  5.1341 +	return rsp;
  5.1342 +
  5.1343 +}
  5.1344 +
  5.1345 +static int qcow_queue_write(struct disk_driver *bs, uint64_t sector,
  5.1346 +		int nb_sectors, char *buf, td_callback_t cb,
  5.1347 +		int id, void *private)
  5.1348 +{
  5.1349 +	BDRVQcowState *s = bs->private;
  5.1350 +	int i, n, index_in_cluster;
  5.1351 +	uint64_t cluster_offset;
  5.1352 +	const uint8_t *src_buf;
  5.1353 +		
  5.1354 +	
  5.1355 +	/*Check we can get a lock*/
  5.1356 +	for (i = 0; i < nb_sectors; i++) 
  5.1357 +		if (!aio_can_lock(s, sector + i)) 
  5.1358 +			return cb(bs, -EBUSY, sector, nb_sectors, id, private);
  5.1359 +
  5.1360 +
  5.1361 +	while (nb_sectors > 0) {
  5.1362 +				
  5.1363 +		index_in_cluster = sector & (s->cluster_sectors - 1);
  5.1364 +		n = s->cluster_sectors - index_in_cluster;
  5.1365 +		if (n > nb_sectors)
  5.1366 +			n = nb_sectors;
  5.1367 +
  5.1368 +		if (s->async.iocb_free_count == 0 || !aio_lock(s, sector))
  5.1369 +			return cb(bs, -EBUSY, sector, nb_sectors, id, private);
  5.1370 +
  5.1371 +
  5.1372 +		cluster_offset = get_cluster_offset(bs, sector << 9, 1, 0,
  5.1373 +				index_in_cluster, 
  5.1374 +				index_in_cluster+n);
  5.1375 +
  5.1376 +		if (!cluster_offset) {
  5.1377 +			DPRINTF("Ooops, no write cluster offset!\n");
  5.1378 +			aio_unlock(s, sector);
  5.1379 +			return cb(bs, -EIO, sector, nb_sectors, id, private);
  5.1380 +		}
  5.1381 +
  5.1382 +
  5.1383 +		// TODO Encryption
  5.1384 +
  5.1385 +		async_write(s, n * 512, 
  5.1386 +				(cluster_offset + index_in_cluster*512),
  5.1387 +				buf, cb, id, sector, private);
  5.1388 +
  5.1389 +		/* Prepare for next sector to write */
  5.1390 +		nb_sectors -= n;
  5.1391 +		sector += n;
  5.1392 +		buf += n * 512;
  5.1393 +	}
  5.1394 +
  5.1395 +		
  5.1396 +	s->cluster_cache_offset = -1; /* disable compressed cache */
  5.1397 +
  5.1398 +	return 0;
  5.1399 +}
  5.1400 +
  5.1401 +
  5.1402 +#endif /* USE_AIO */
  5.1403 +
  5.1404 +
  5.1405 +static int qcow_close(struct disk_driver *bs)
  5.1406 +{
  5.1407 +	BDRVQcowState *s = bs->private;
  5.1408 +		
  5.1409 +	close(s->poll_pipe[0]);
  5.1410 +		close(s->poll_pipe[1]);
  5.1411 +
  5.1412 +	qemu_free(s->l1_table);
  5.1413 +	qemu_free(s->l2_cache);
  5.1414 +	qemu_free(s->cluster_cache);
  5.1415 +	qemu_free(s->cluster_data);
  5.1416 +	refcount_close(bs);
  5.1417 +	return close(s->fd);
  5.1418 +}
  5.1419 +
  5.1420 +/* XXX: use std qcow open function ? */
  5.1421 +typedef struct QCowCreateState {
  5.1422 +	int cluster_size;
  5.1423 +	int cluster_bits;
  5.1424 +	uint16_t *refcount_block;
  5.1425 +	uint64_t *refcount_table;
  5.1426 +	int64_t l1_table_offset;
  5.1427 +	int64_t refcount_table_offset;
  5.1428 +	int64_t refcount_block_offset;
  5.1429 +} QCowCreateState;
  5.1430 +
  5.1431 +static void create_refcount_update(QCowCreateState *s,
  5.1432 +		int64_t offset, int64_t size)
  5.1433 +{
  5.1434 +	int refcount;
  5.1435 +	int64_t start, last, cluster_offset;
  5.1436 +	uint16_t *p;
  5.1437 +
  5.1438 +	start = offset & ~(s->cluster_size - 1);
  5.1439 +	last = (offset + size - 1)	& ~(s->cluster_size - 1);
  5.1440 +	for(cluster_offset = start; cluster_offset <= last;
  5.1441 +		cluster_offset += s->cluster_size) {
  5.1442 +		p = &s->refcount_block[cluster_offset >> s->cluster_bits];
  5.1443 +		refcount = be16_to_cpu(*p);
  5.1444 +		refcount++;
  5.1445 +		*p = cpu_to_be16(refcount);
  5.1446 +	}
  5.1447 +}
  5.1448 +
  5.1449 +static int qcow2_create(const char *filename, int64_t total_size,
  5.1450 +		const char *backing_file, int flags)
  5.1451 +{
  5.1452 +	int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
  5.1453 +	QCowHeader header;
  5.1454 +	uint64_t tmp, offset;
  5.1455 +	QCowCreateState s1, *s = &s1;
  5.1456 +
  5.1457 +	memset(s, 0, sizeof(*s));
  5.1458 +
  5.1459 +	fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
  5.1460 +	if (fd < 0)
  5.1461 +		return -1;
  5.1462 +	memset(&header, 0, sizeof(header));
  5.1463 +	header.magic = cpu_to_be32(QCOW_MAGIC);
  5.1464 +	header.version = cpu_to_be32(QCOW_VERSION);
  5.1465 +	header.size = cpu_to_be64(total_size * 512);
  5.1466 +	header_size = sizeof(header);
  5.1467 +	backing_filename_len = 0;
  5.1468 +	if (backing_file) {
  5.1469 +		header.backing_file_offset = cpu_to_be64(header_size);
  5.1470 +		backing_filename_len = strlen(backing_file);
  5.1471 +		header.backing_file_size = cpu_to_be32(backing_filename_len);
  5.1472 +		header_size += backing_filename_len;
  5.1473 +	}
  5.1474 +	s->cluster_bits = 12;  /* 4 KB clusters */
  5.1475 +	s->cluster_size = 1 << s->cluster_bits;
  5.1476 +	header.cluster_bits = cpu_to_be32(s->cluster_bits);
  5.1477 +	header_size = (header_size + 7) & ~7;
  5.1478 +	if (flags & BLOCK_FLAG_ENCRYPT) {
  5.1479 +		header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
  5.1480 +	} else {
  5.1481 +		header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
  5.1482 +	}
  5.1483 +	l2_bits = s->cluster_bits - 3;
  5.1484 +	shift = s->cluster_bits + l2_bits;
  5.1485 +	l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
  5.1486 +	offset = align_offset(header_size, s->cluster_size);
  5.1487 +	s->l1_table_offset = offset;
  5.1488 +	header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
  5.1489 +	header.l1_size = cpu_to_be32(l1_size);
  5.1490 +	offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
  5.1491 +
  5.1492 +	s->refcount_table = qemu_mallocz(s->cluster_size);
  5.1493 +	if (!s->refcount_table)
  5.1494 +		goto fail;
  5.1495 +	s->refcount_block = qemu_mallocz(s->cluster_size);
  5.1496 +	if (!s->refcount_block)
  5.1497 +		goto fail;
  5.1498 +
  5.1499 +	s->refcount_table_offset = offset;
  5.1500 +	header.refcount_table_offset = cpu_to_be64(offset);
  5.1501 +	header.refcount_table_clusters = cpu_to_be32(1);
  5.1502 +	offset += s->cluster_size;
  5.1503 +
  5.1504 +	s->refcount_table[0] = cpu_to_be64(offset);
  5.1505 +	s->refcount_block_offset = offset;
  5.1506 +	offset += s->cluster_size;
  5.1507 +
  5.1508 +	/* update refcounts */
  5.1509 +	create_refcount_update(s, 0, header_size);
  5.1510 +	create_refcount_update(s, s->l1_table_offset, l1_size * sizeof(uint64_t));
  5.1511 +	create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
  5.1512 +	create_refcount_update(s, s->refcount_block_offset, s->cluster_size);
  5.1513 +
  5.1514 +	/* write all the data */
  5.1515 +	write(fd, &header, sizeof(header));
  5.1516 +	if (backing_file) {
  5.1517 +		write(fd, backing_file, backing_filename_len);
  5.1518 +	}
  5.1519 +	lseek(fd, s->l1_table_offset, SEEK_SET);
  5.1520 +	tmp = 0;
  5.1521 +	for(i = 0;i < l1_size; i++) {
  5.1522 +		write(fd, &tmp, sizeof(tmp));
  5.1523 +	}
  5.1524 +	lseek(fd, s->refcount_table_offset, SEEK_SET);
  5.1525 +	write(fd, s->refcount_table, s->cluster_size);
  5.1526 +
  5.1527 +	lseek(fd, s->refcount_block_offset, SEEK_SET);
  5.1528 +	write(fd, s->refcount_block, s->cluster_size);
  5.1529 +
  5.1530 +	qemu_free(s->refcount_table);
  5.1531 +	qemu_free(s->refcount_block);
  5.1532 +	close(fd);
  5.1533 +	return 0;
  5.1534 +fail:
  5.1535 +	qemu_free(s->refcount_table);
  5.1536 +	qemu_free(s->refcount_block);
  5.1537 +	close(fd);
  5.1538 +	return -ENOMEM;
  5.1539 +}
  5.1540 +
  5.1541 +/* XXX: put compressed sectors first, then all the cluster aligned
  5.1542 +   tables to avoid losing bytes in alignment */
  5.1543 +static int qcow_write_compressed(struct disk_driver *bs, int64_t sector_num,
  5.1544 +		const uint8_t *buf, int nb_sectors)
  5.1545 +{
  5.1546 +	BDRVQcowState *s = bs->private;
  5.1547 +	z_stream strm;
  5.1548 +	int ret, out_len;
  5.1549 +	uint8_t *out_buf;
  5.1550 +	uint64_t cluster_offset;
  5.1551 +
  5.1552 +	if (nb_sectors == 0) {
  5.1553 +		/* align end of file to a sector boundary to ease reading with
  5.1554 +		   sector based I/Os */
  5.1555 +		cluster_offset = 512 * s->total_sectors;
  5.1556 +		cluster_offset = (cluster_offset + 511) & ~511;
  5.1557 +		ftruncate(s->fd, cluster_offset);
  5.1558 +		return 0;
  5.1559 +	}
  5.1560 +
  5.1561 +	if (nb_sectors != s->cluster_sectors)
  5.1562 +		return -EINVAL;
  5.1563 +
  5.1564 +	out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
  5.1565 +	if (!out_buf)
  5.1566 +		return -ENOMEM;
  5.1567 +
  5.1568 +	/* best compression, small window, no zlib header */
  5.1569 +	memset(&strm, 0, sizeof(strm));
  5.1570 +	ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
  5.1571 +			Z_DEFLATED, -12,
  5.1572 +			9, Z_DEFAULT_STRATEGY);
  5.1573 +	if (ret != 0) {
  5.1574 +		qemu_free(out_buf);
  5.1575 +		return -1;
  5.1576 +	}
  5.1577 +
  5.1578 +	strm.avail_in = s->cluster_size;
  5.1579 +	strm.next_in = (uint8_t *)buf;
  5.1580 +	strm.avail_out = s->cluster_size;
  5.1581 +	strm.next_out = out_buf;
  5.1582 +
  5.1583 +	ret = deflate(&strm, Z_FINISH);
  5.1584 +	if (ret != Z_STREAM_END && ret != Z_OK) {
  5.1585 +		qemu_free(out_buf);
  5.1586 +		deflateEnd(&strm);
  5.1587 +		return -1;
  5.1588 +	}
  5.1589 +	out_len = strm.next_out - out_buf;
  5.1590 +
  5.1591 +	deflateEnd(&strm);
  5.1592 +
  5.1593 +	if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
  5.1594 +		/* could not compress: write normal cluster */
  5.1595 +		qcow_write(bs, sector_num, buf, s->cluster_sectors);
  5.1596 +	} else {
  5.1597 +		cluster_offset = get_cluster_offset(bs, sector_num << 9, 2,
  5.1598 +											out_len, 0, 0);
  5.1599 +		cluster_offset &= s->cluster_offset_mask;
  5.1600 +		if (bdrv_pwrite(s->fd, cluster_offset, out_buf, out_len) != out_len) {
  5.1601 +			qemu_free(out_buf);
  5.1602 +			return -1;
  5.1603 +		}
  5.1604 +	}
  5.1605 +
  5.1606 +	qemu_free(out_buf);
  5.1607 +	return 0;
  5.1608 +}
  5.1609 +
  5.1610 +static int qcow_submit(struct disk_driver *bs)
  5.1611 +{
  5.1612 +	int ret;
  5.1613 +	struct	 BDRVQcowState *prv = (struct BDRVQcowState*)bs->private;
  5.1614 +
  5.1615 +
  5.1616 +	fsync(prv->fd);
  5.1617 +
  5.1618 +	if (!prv->async.iocb_queued)
  5.1619 +		return 0;
  5.1620 +
  5.1621 +	ret = io_submit(prv->async.aio_ctx.aio_ctx, prv->async.iocb_queued, prv->async.iocb_queue);
  5.1622 +
  5.1623 +	/* XXX: TODO: Handle error conditions here. */
  5.1624 +
  5.1625 +	/* Success case: */
  5.1626 +	prv->async.iocb_queued = 0;
  5.1627 +
  5.1628 +	return 0;
  5.1629 +}
  5.1630 +
  5.1631 +
  5.1632 +/*********************************************************/
  5.1633 +/* snapshot support */
  5.1634 +
  5.1635 +
  5.1636 +static void qcow_free_snapshots(struct disk_driver *bs)
  5.1637 +{
  5.1638 +	BDRVQcowState *s = bs->private;
  5.1639 +	int i;
  5.1640 +
  5.1641 +	for(i = 0; i < s->nb_snapshots; i++) {
  5.1642 +		qemu_free(s->snapshots[i].name);
  5.1643 +		qemu_free(s->snapshots[i].id_str);
  5.1644 +	}
  5.1645 +	qemu_free(s->snapshots);
  5.1646 +	s->snapshots = NULL;
  5.1647 +	s->nb_snapshots = 0;
  5.1648 +}
  5.1649 +
  5.1650 +static int qcow_read_snapshots(struct disk_driver *bs)
  5.1651 +{
  5.1652 +	BDRVQcowState *s = bs->private;
  5.1653 +	QCowSnapshotHeader h;
  5.1654 +	QCowSnapshot *sn;
  5.1655 +	int i, id_str_size, name_size;
  5.1656 +	int64_t offset;
  5.1657 +	uint32_t extra_data_size;
  5.1658 +
  5.1659 +	offset = s->snapshots_offset;
  5.1660 +	s->snapshots = qemu_mallocz(s->nb_snapshots * sizeof(QCowSnapshot));
  5.1661 +	if (!s->snapshots)
  5.1662 +		goto fail;
  5.1663 +	for(i = 0; i < s->nb_snapshots; i++) {
  5.1664 +		offset = align_offset(offset, 8);
  5.1665 +		if (bdrv_pread(s->fd, offset, &h, sizeof(h)) != sizeof(h))
  5.1666 +			goto fail;
  5.1667 +		offset += sizeof(h);
  5.1668 +		sn = s->snapshots + i;
  5.1669 +		sn->l1_table_offset = be64_to_cpu(h.l1_table_offset);
  5.1670 +		sn->l1_size = be32_to_cpu(h.l1_size);
  5.1671 +		sn->vm_state_size = be32_to_cpu(h.vm_state_size);
  5.1672 +		sn->date_sec = be32_to_cpu(h.date_sec);
  5.1673 +		sn->date_nsec = be32_to_cpu(h.date_nsec);
  5.1674 +		sn->vm_clock_nsec = be64_to_cpu(h.vm_clock_nsec);
  5.1675 +		extra_data_size = be32_to_cpu(h.extra_data_size);
  5.1676 +
  5.1677 +		id_str_size = be16_to_cpu(h.id_str_size);
  5.1678 +		name_size = be16_to_cpu(h.name_size);
  5.1679 +
  5.1680 +		offset += extra_data_size;
  5.1681 +
  5.1682 +		sn->id_str = qemu_malloc(id_str_size + 1);
  5.1683 +		if (!sn->id_str)
  5.1684 +			goto fail;
  5.1685 +		if (bdrv_pread(s->fd, offset, sn->id_str, id_str_size) != id_str_size)
  5.1686 +			goto fail;
  5.1687 +		offset += id_str_size;
  5.1688 +		sn->id_str[id_str_size] = '\0';
  5.1689 +
  5.1690 +		sn->name = qemu_malloc(name_size + 1);
  5.1691 +		if (!sn->name)
  5.1692 +			goto fail;
  5.1693 +		if (bdrv_pread(s->fd, offset, sn->name, name_size) != name_size)
  5.1694 +			goto fail;
  5.1695 +		offset += name_size;
  5.1696 +		sn->name[name_size] = '\0';
  5.1697 +	}
  5.1698 +	s->snapshots_size = offset - s->snapshots_offset;
  5.1699 +	return 0;
  5.1700 +fail:
  5.1701 +	qcow_free_snapshots(bs);
  5.1702 +	return -1;
  5.1703 +}
  5.1704 +
  5.1705 +
  5.1706 +/*********************************************************/
  5.1707 +/* refcount handling */
  5.1708 +
  5.1709 +static int refcount_init(struct disk_driver *bs)
  5.1710 +{
  5.1711 +	BDRVQcowState *s = bs->private;
  5.1712 +	int ret, refcount_table_size2, i;
  5.1713 +
  5.1714 +	s->refcount_block_cache = qemu_malloc(s->cluster_size);
  5.1715 +	if (!s->refcount_block_cache)
  5.1716 +		goto fail;
  5.1717 +	refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
  5.1718 +	s->refcount_table = qemu_malloc(refcount_table_size2);
  5.1719 +	if (!s->refcount_table)
  5.1720 +		goto fail;
  5.1721 +	if (s->refcount_table_size > 0) {
  5.1722 +		ret = bdrv_pread(s->fd, s->refcount_table_offset,
  5.1723 +				s->refcount_table, refcount_table_size2);
  5.1724 +		if (ret != refcount_table_size2)
  5.1725 +			goto fail;
  5.1726 +		for(i = 0; i < s->refcount_table_size; i++)
  5.1727 +			be64_to_cpus(&s->refcount_table[i]);
  5.1728 +	}
  5.1729 +	return 0;
  5.1730 + fail:
  5.1731 +	return -ENOMEM;
  5.1732 +}
  5.1733 +
  5.1734 +static void refcount_close(struct disk_driver *bs)
  5.1735 +{
  5.1736 +	BDRVQcowState *s = bs->private;
  5.1737 +	qemu_free(s->refcount_block_cache);
  5.1738 +	qemu_free(s->refcount_table);
  5.1739 +}
  5.1740 +
  5.1741 +
  5.1742 +static int load_refcount_block(struct disk_driver *bs,
  5.1743 +		int64_t refcount_block_offset)
  5.1744 +{
  5.1745 +	BDRVQcowState *s = bs->private;
  5.1746 +	int ret;
  5.1747 +	ret = bdrv_pread(s->fd, refcount_block_offset, s->refcount_block_cache,
  5.1748 +			s->cluster_size);
  5.1749 +	if (ret != s->cluster_size)
  5.1750 +		return -EIO;
  5.1751 +	s->refcount_block_cache_offset = refcount_block_offset;
  5.1752 +	return 0;
  5.1753 +}
  5.1754 +
  5.1755 +static int get_refcount(struct disk_driver *bs, int64_t cluster_index)
  5.1756 +{
  5.1757 +	BDRVQcowState *s = bs->private;
  5.1758 +	int refcount_table_index, block_index;
  5.1759 +	int64_t refcount_block_offset;
  5.1760 +
  5.1761 +	refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
  5.1762 +	if (refcount_table_index >= s->refcount_table_size)
  5.1763 +		return 0;
  5.1764 +	refcount_block_offset = s->refcount_table[refcount_table_index];
  5.1765 +	if (!refcount_block_offset)
  5.1766 +		return 0;
  5.1767 +	if (refcount_block_offset != s->refcount_block_cache_offset) {
  5.1768 +		/* better than nothing: return allocated if read error */
  5.1769 +		if (load_refcount_block(bs, refcount_block_offset) < 0)
  5.1770 +			return 1;
  5.1771 +	}
  5.1772 +	block_index = cluster_index &
  5.1773 +		((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
  5.1774 +	return be16_to_cpu(s->refcount_block_cache[block_index]);
  5.1775 +}
  5.1776 +
  5.1777 +/* return < 0 if error */
  5.1778 +static int64_t alloc_clusters_noref(struct disk_driver *bs, int64_t size)
  5.1779 +{
  5.1780 +	BDRVQcowState *s = bs->private;
  5.1781 +	int i, nb_clusters;
  5.1782 +
  5.1783 +	nb_clusters = (size + s->cluster_size - 1) >> s->cluster_bits;
  5.1784 +	for(;;) {
  5.1785 +		if (get_refcount(bs, s->free_cluster_index) == 0) {
  5.1786 +			s->free_cluster_index++;
  5.1787 +			for(i = 1; i < nb_clusters; i++) {
  5.1788 +				if (get_refcount(bs, s->free_cluster_index) != 0)
  5.1789 +					goto not_found;
  5.1790 +				s->free_cluster_index++;
  5.1791 +			}
  5.1792 +
  5.1793 +#ifdef DEBUG_ALLOC2
  5.1794 +			DPRINTF("alloc_clusters: size=%ld -> %ld\n",
  5.1795 +				   size,
  5.1796 +				   (s->free_cluster_index - nb_clusters) << s->cluster_bits);
  5.1797 +#endif
  5.1798 +
  5.1799 +			return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
  5.1800 +		} else {
  5.1801 +		not_found:
  5.1802 +			s->free_cluster_index++;
  5.1803 +		}
  5.1804 +	}
  5.1805 +}
  5.1806 +
  5.1807 +static int64_t alloc_clusters(struct disk_driver *bs, int64_t size)
  5.1808 +{
  5.1809 +	int64_t offset;
  5.1810 +
  5.1811 +	offset = alloc_clusters_noref(bs, size);
  5.1812 +	update_refcount(bs, offset, size, 1);
  5.1813 +	return offset;
  5.1814 +}
  5.1815 +
  5.1816 +/* only used to allocate compressed sectors. We try to allocate
  5.1817 +   contiguous sectors. size must be <= cluster_size */
  5.1818 +static int64_t alloc_bytes(struct disk_driver *bs, int size)
  5.1819 +{
  5.1820 +	BDRVQcowState *s = bs->private;
  5.1821 +	int64_t offset, cluster_offset;
  5.1822 +	int free_in_cluster;
  5.1823 +
  5.1824 +	assert(size > 0 && size <= s->cluster_size);
  5.1825 +	if (s->free_byte_offset == 0) {
  5.1826 +		s->free_byte_offset = alloc_clusters(bs, s->cluster_size);
  5.1827 +	}
  5.1828 +redo:
  5.1829 +	free_in_cluster = s->cluster_size -
  5.1830 +		(s->free_byte_offset & (s->cluster_size - 1));
  5.1831 +	if (size <= free_in_cluster) {
  5.1832 +		/* enough space in current cluster */
  5.1833 +		offset = s->free_byte_offset;
  5.1834 +		s->free_byte_offset += size;
  5.1835 +		free_in_cluster -= size;
  5.1836 +		if (free_in_cluster == 0)
  5.1837 +			s->free_byte_offset = 0;
  5.1838 +		if ((offset & (s->cluster_size - 1)) != 0)
  5.1839 +			update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
  5.1840 +	} else {
  5.1841 +		offset = alloc_clusters(bs, s->cluster_size);
  5.1842 +		cluster_offset = s->free_byte_offset & ~(s->cluster_size - 1);
  5.1843 +		if ((cluster_offset + s->cluster_size) == offset) {
  5.1844 +			/* we are lucky: contiguous data */
  5.1845 +			offset = s->free_byte_offset;
  5.1846 +			update_cluster_refcount(bs, offset >> s->cluster_bits, 1);
  5.1847 +			s->free_byte_offset += size;
  5.1848 +		} else {
  5.1849 +			s->free_byte_offset = offset;
  5.1850 +			goto redo;
  5.1851 +		}
  5.1852 +	}
  5.1853 +	return offset;
  5.1854 +}
  5.1855 +
  5.1856 +static void free_clusters(struct disk_driver *bs,
  5.1857 +		int64_t offset, int64_t size)
  5.1858 +{
  5.1859 +	update_refcount(bs, offset, size, -1);
  5.1860 +}
  5.1861 +
  5.1862 +static int grow_refcount_table(struct disk_driver *bs, int min_size)
  5.1863 +{
  5.1864 +	BDRVQcowState *s = bs->private;
  5.1865 +	int new_table_size, new_table_size2, refcount_table_clusters, i, ret;
  5.1866 +	uint64_t *new_table;
  5.1867 +	int64_t table_offset;
  5.1868 +	uint64_t data64;
  5.1869 +	uint32_t data32;
  5.1870 +	int old_table_size;
  5.1871 +	int64_t old_table_offset;
  5.1872 +
  5.1873 +	if (min_size <= s->refcount_table_size)
  5.1874 +		return 0;
  5.1875 +	
  5.1876 +	/* compute new table size */
  5.1877 +	refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
  5.1878 +	for(;;) {
  5.1879 +		if (refcount_table_clusters == 0) {
  5.1880 +			refcount_table_clusters = 1;
  5.1881 +		} else {
  5.1882 +			refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
  5.1883 +		}
  5.1884 +		new_table_size = refcount_table_clusters << (s->cluster_bits - 3);
  5.1885 +		if (min_size <= new_table_size)
  5.1886 +			break;
  5.1887 +	}
  5.1888 +
  5.1889 +#ifdef DEBUG_ALLOC2
  5.1890 +	printf("grow_refcount_table from %d to %d\n",
  5.1891 +		   s->refcount_table_size,
  5.1892 +		   new_table_size);
  5.1893 +#endif
  5.1894 +	new_table_size2 = new_table_size * sizeof(uint64_t);
  5.1895 +	new_table = qemu_mallocz(new_table_size2);
  5.1896 +	if (!new_table)
  5.1897 +		return -ENOMEM;
  5.1898 +	memcpy(new_table, s->refcount_table,
  5.1899 +		   s->refcount_table_size * sizeof(uint64_t));
  5.1900 +	for(i = 0; i < s->refcount_table_size; i++)
  5.1901 +		cpu_to_be64s(&new_table[i]);
  5.1902 +	/* Note: we cannot update the refcount now to avoid recursion */
  5.1903 +	table_offset = alloc_clusters_noref(bs, new_table_size2);
  5.1904 +	ret = bdrv_pwrite(s->fd, table_offset, new_table, new_table_size2);
  5.1905 +	if (ret != new_table_size2)
  5.1906 +		goto fail;
  5.1907 +	for(i = 0; i < s->refcount_table_size; i++)
  5.1908 +		be64_to_cpus(&new_table[i]);
  5.1909 +
  5.1910 +	data64 = cpu_to_be64(table_offset);
  5.1911 +	if (bdrv_pwrite(s->fd, offsetof(QCowHeader, refcount_table_offset),
  5.1912 +					&data64, sizeof(data64)) != sizeof(data64))
  5.1913 +		goto fail;
  5.1914 +	data32 = cpu_to_be32(refcount_table_clusters);
  5.1915 +	if (bdrv_pwrite(s->fd, offsetof(QCowHeader, refcount_table_clusters),
  5.1916 +					&data32, sizeof(data32)) != sizeof(data32))
  5.1917 +		goto fail;
  5.1918 +	qemu_free(s->refcount_table);
  5.1919 +	old_table_offset = s->refcount_table_offset;
  5.1920 +	old_table_size = s->refcount_table_size;
  5.1921 +	s->refcount_table = new_table;
  5.1922 +	s->refcount_table_size = new_table_size;
  5.1923 +	s->refcount_table_offset = table_offset;
  5.1924 +
  5.1925 +	update_refcount(bs, table_offset, new_table_size2, 1);
  5.1926 +	free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));
  5.1927 +	return 0;
  5.1928 + fail:
  5.1929 +	free_clusters(bs, table_offset, new_table_size2);
  5.1930 +	qemu_free(new_table);
  5.1931 +	return -EIO;
  5.1932 +}
  5.1933 +
  5.1934 +/* addend must be 1 or -1 */
  5.1935 +/* XXX: cache several refcount block clusters ? */
  5.1936 +static int update_cluster_refcount(struct disk_driver *bs,
  5.1937 +		int64_t cluster_index,
  5.1938 +		int addend)
  5.1939 +{
  5.1940 +	BDRVQcowState *s = bs->private;
  5.1941 +	int64_t offset, refcount_block_offset;
  5.1942 +	int ret, refcount_table_index, block_index, refcount;
  5.1943 +	uint64_t data64;
  5.1944 +
  5.1945 +	refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
  5.1946 +	if (refcount_table_index >= s->refcount_table_size) {
  5.1947 +		if (addend < 0)
  5.1948 +			return -EINVAL;
  5.1949 +		ret = grow_refcount_table(bs, refcount_table_index + 1);
  5.1950 +		if (ret < 0)
  5.1951 +			return ret;
  5.1952 +	}
  5.1953 +	refcount_block_offset = s->refcount_table[refcount_table_index];
  5.1954 +	if (!refcount_block_offset) {
  5.1955 +		if (addend < 0)
  5.1956 +			return -EINVAL;
  5.1957 +		/* create a new refcount block */
  5.1958 +		/* Note: we cannot update the refcount now to avoid recursion */
  5.1959 +		offset = alloc_clusters_noref(bs, s->cluster_size);
  5.1960 +		memset(s->refcount_block_cache, 0, s->cluster_size);
  5.1961 +		ret = bdrv_pwrite(s->fd, offset, s->refcount_block_cache, s->cluster_size);
  5.1962 +		if (ret != s->cluster_size)
  5.1963 +			return -EINVAL;
  5.1964 +		s->refcount_table[refcount_table_index] = offset;
  5.1965 +		data64 = cpu_to_be64(offset);
  5.1966 +		ret = bdrv_pwrite(s->fd, s->refcount_table_offset +
  5.1967 +						  refcount_table_index * sizeof(uint64_t),
  5.1968 +						  &data64, sizeof(data64));
  5.1969 +		if (ret != sizeof(data64))
  5.1970 +			return -EINVAL;
  5.1971 +
  5.1972 +		refcount_block_offset = offset;
  5.1973 +		s->refcount_block_cache_offset = offset;
  5.1974 +		update_refcount(bs, offset, s->cluster_size, 1);
  5.1975 +	} else {
  5.1976 +		if (refcount_block_offset != s->refcount_block_cache_offset) {
  5.1977 +			if (load_refcount_block(bs, refcount_block_offset) < 0)
  5.1978 +				return -EIO;
  5.1979 +		}
  5.1980 +	}
  5.1981 +	/* we can update the count and save it */
  5.1982 +	block_index = cluster_index &
  5.1983 +		((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
  5.1984 +	refcount = be16_to_cpu(s->refcount_block_cache[block_index]);
  5.1985 +	refcount += addend;
  5.1986 +	if (refcount < 0 || refcount > 0xffff)
  5.1987 +		return -EINVAL;
  5.1988 +	if (refcount == 0 && cluster_index < s->free_cluster_index) {
  5.1989 +		s->free_cluster_index = cluster_index;
  5.1990 +	}
  5.1991 +	s->refcount_block_cache[block_index] = cpu_to_be16(refcount);
  5.1992 +	if (bdrv_pwrite(s->fd,
  5.1993 +					refcount_block_offset + (block_index << REFCOUNT_SHIFT),
  5.1994 +					&s->refcount_block_cache[block_index], 2) != 2)
  5.1995 +		return -EIO;
  5.1996 +	return refcount;
  5.1997 +}
  5.1998 +
  5.1999 +static void update_refcount(struct disk_driver *bs,
  5.2000 +		int64_t offset, int64_t length,
  5.2001 +		int addend)
  5.2002 +{
  5.2003 +	BDRVQcowState *s = bs->private;
  5.2004 +	int64_t start, last, cluster_offset;
  5.2005 +
  5.2006 +#ifdef DEBUG_ALLOC2
  5.2007 +	printf("update_refcount: offset=%lld size=%lld addend=%d\n",
  5.2008 +		   offset, length, addend);
  5.2009 +#endif
  5.2010 +	if (length <= 0)
  5.2011 +		return;
  5.2012 +	start = offset & ~(s->cluster_size - 1);
  5.2013 +	last = (offset + length - 1) & ~(s->cluster_size - 1);
  5.2014 +	for(cluster_offset = start; cluster_offset <= last;
  5.2015 +		cluster_offset += s->cluster_size) {
  5.2016 +		update_cluster_refcount(bs, cluster_offset >> s->cluster_bits, addend);
  5.2017 +	}
  5.2018 +}
  5.2019 +
  5.2020 +#ifdef DEBUG_ALLOC
  5.2021 +static void inc_refcounts(struct disk_driver *bs,
  5.2022 +		uint16_t *refcount_table,
  5.2023 +		int refcount_table_size,
  5.2024 +		int64_t offset, int64_t size)
  5.2025 +{
  5.2026 +	BDRVQcowState *s = bs->private;
  5.2027 +	int64_t start, last, cluster_offset;
  5.2028 +	int k;
  5.2029 +
  5.2030 +	if (size <= 0)
  5.2031 +		return;
  5.2032 +
  5.2033 +	start = offset & ~(s->cluster_size - 1);
  5.2034 +	last = (offset + size - 1) & ~(s->cluster_size - 1);
  5.2035 +	for(cluster_offset = start; cluster_offset <= last;
  5.2036 +		cluster_offset += s->cluster_size) {
  5.2037 +		k = cluster_offset >> s->cluster_bits;
  5.2038 +		if (k < 0 || k >= refcount_table_size) {
  5.2039 +			printf("ERROR: invalid cluster offset=0x%llx\n", cluster_offset);
  5.2040 +		} else {
  5.2041 +			if (++refcount_table[k] == 0) {
  5.2042 +				printf("ERROR: overflow cluster offset=0x%llx\n", cluster_offset);
  5.2043 +			}
  5.2044 +		}
  5.2045 +	}
  5.2046 +}
  5.2047 +
  5.2048 +static int check_refcounts_l1(struct disk_driver *bs,
  5.2049 +		uint16_t *refcount_table,
  5.2050 +		int refcount_table_size,
  5.2051 +		int64_t l1_table_offset, int l1_size,
  5.2052 +		int check_copied)
  5.2053 +{
  5.2054 +	BDRVQcowState *s = bs->private;
  5.2055 +	uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2;
  5.2056 +	int l2_size, i, j, nb_csectors, refcount;
  5.2057 +
  5.2058 +	l2_table = NULL;
  5.2059 +	l1_size2 = l1_size * sizeof(uint64_t);
  5.2060 +
  5.2061 +	inc_refcounts(bs, refcount_table, refcount_table_size,
  5.2062 +				  l1_table_offset, l1_size2);
  5.2063 +
  5.2064 +	l1_table = qemu_malloc(l1_size2);
  5.2065 +	if (!l1_table)
  5.2066 +		goto fail;
  5.2067 +	if (bdrv_pread(s->fd, l1_table_offset,
  5.2068 +				   l1_table, l1_size2) != l1_size2)
  5.2069 +		goto fail;
  5.2070 +	for(i = 0;i < l1_size; i++)
  5.2071 +		be64_to_cpus(&l1_table[i]);
  5.2072 +
  5.2073 +	l2_size = s->l2_size * sizeof(uint64_t);
  5.2074 +	l2_table = qemu_malloc(l2_size);
  5.2075 +	if (!l2_table)
  5.2076 +		goto fail;
  5.2077 +	for(i = 0; i < l1_size; i++) {
  5.2078 +		l2_offset = l1_table[i];
  5.2079 +		if (l2_offset) {
  5.2080 +			if (check_copied) {
  5.2081 +				refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
  5.2082 +				if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
  5.2083 +					printf("ERROR OFLAG_COPIED: l2_offset=%llx refcount=%d\n",
  5.2084 +						   l2_offset, refcount);
  5.2085 +				}
  5.2086 +			}
  5.2087 +			l2_offset &= ~QCOW_OFLAG_COPIED;
  5.2088 +			if (bdrv_pread(s->fd, l2_offset, l2_table, l2_size) != l2_size)
  5.2089 +				goto fail;
  5.2090 +			for(j = 0; j < s->l2_size; j++) {
  5.2091 +				offset = be64_to_cpu(l2_table[j]);
  5.2092 +				if (offset != 0) {
  5.2093 +					if (offset & QCOW_OFLAG_COMPRESSED) {
  5.2094 +						if (offset & QCOW_OFLAG_COPIED) {
  5.2095 +							printf("ERROR: cluster %lld: copied flag must never be set for compressed clusters\n",
  5.2096 +								   offset >> s->cluster_bits);
  5.2097 +							offset &= ~QCOW_OFLAG_COPIED;
  5.2098 +						}
  5.2099 +						nb_csectors = ((offset >> s->csize_shift) &
  5.2100 +									   s->csize_mask) + 1;
  5.2101 +						offset &= s->cluster_offset_mask;
  5.2102 +						inc_refcounts(bs, refcount_table,
  5.2103 +								refcount_table_size,
  5.2104 +								offset & ~511, nb_csectors * 512);
  5.2105 +					} else {
  5.2106 +						if (check_copied) {
  5.2107 +							refcount = get_refcount(bs, (offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);
  5.2108 +							if ((refcount == 1) != ((offset & QCOW_OFLAG_COPIED) != 0)) {
  5.2109 +								printf("ERROR OFLAG_COPIED: offset=%llx refcount=%d\n",
  5.2110 +									   offset, refcount);
  5.2111 +							}
  5.2112 +						}
  5.2113 +						offset &= ~QCOW_OFLAG_COPIED;
  5.2114 +						inc_refcounts(bs, refcount_table,
  5.2115 +								refcount_table_size,
  5.2116 +								offset, s->cluster_size);
  5.2117 +					}
  5.2118 +				}
  5.2119 +			}
  5.2120 +			inc_refcounts(bs, refcount_table,
  5.2121 +					refcount_table_size,
  5.2122 +					l2_offset,
  5.2123 +					s->cluster_size);
  5.2124 +		}
  5.2125 +	}
  5.2126 +	qemu_free(l1_table);
  5.2127 +	qemu_free(l2_table);
  5.2128 +	return 0;
  5.2129 + fail:
  5.2130 +	printf("ERROR: I/O error in check_refcounts_l1\n");
  5.2131 +	qemu_free(l1_table);
  5.2132 +	qemu_free(l2_table);
  5.2133 +	return -EIO;
  5.2134 +}
  5.2135 +
  5.2136 +static void check_refcounts(struct disk_driver *bs)
  5.2137 +{
  5.2138 +	BDRVQcowState *s = bs->private;
  5.2139 +	int64_t size;
  5.2140 +	int nb_clusters, refcount1, refcount2, i;
  5.2141 +	QCowSnapshot *sn;
  5.2142 +	uint16_t *refcount_table;
  5.2143 +
  5.2144 +	size = bdrv_getlength(s->fd);
  5.2145 +	nb_clusters = (size + s->cluster_size - 1) >> s->cluster_bits;
  5.2146 +	refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));
  5.2147 +
  5.2148 +	/* header */
  5.2149 +	inc_refcounts(bs, refcount_table, nb_clusters,
  5.2150 +			0, s->cluster_size);
  5.2151 +
  5.2152 +	check_refcounts_l1(bs, refcount_table, nb_clusters,
  5.2153 +			s->l1_table_offset, s->l1_size, 1);
  5.2154 +
  5.2155 +	/* snapshots */
  5.2156 +	for(i = 0; i < s->nb_snapshots; i++) {
  5.2157 +		sn = s->snapshots + i;
  5.2158 +		check_refcounts_l1(bs, refcount_table, nb_clusters,
  5.2159 +						   sn->l1_table_offset, sn->l1_size, 0);
  5.2160 +	}
  5.2161 +	inc_refcounts(bs, refcount_table, nb_clusters,
  5.2162 +				  s->snapshots_offset, s->snapshots_size);
  5.2163 +
  5.2164 +	/* refcount data */
  5.2165 +	inc_refcounts(bs, refcount_table, nb_clusters,
  5.2166 +			s->refcount_table_offset,
  5.2167 +			s->refcount_table_size * sizeof(uint64_t));
  5.2168 +
  5.2169 +	for(i = 0; i < s->refcount_table_size; i++) {
  5.2170 +		int64_t offset;
  5.2171 +		offset = s->refcount_table[i];
  5.2172 +		if (offset != 0) {
  5.2173 +			inc_refcounts(bs, refcount_table, nb_clusters,
  5.2174 +					offset, s->cluster_size);
  5.2175 +		}
  5.2176 +	}
  5.2177 +
  5.2178 +	/* compare ref counts */
  5.2179 +	for(i = 0; i < nb_clusters; i++) {
  5.2180 +		refcount1 = get_refcount(bs, i);
  5.2181 +		refcount2 = refcount_table[i];
  5.2182 +		if (refcount1 != refcount2)
  5.2183 +			printf("ERROR cluster %d refcount=%d reference=%d\n",
  5.2184 +				   i, refcount1, refcount2);
  5.2185 +	}
  5.2186 +
  5.2187 +	qemu_free(refcount_table);
  5.2188 +}
  5.2189 +#endif
  5.2190 +
  5.2191 +
  5.2192 +/**
  5.2193 + * Wrapper for synchronous read.
  5.2194 + * This function is called when not using AIO at all (#undef USE_AIO) or
  5.2195 + * for accessing the backing file.
  5.2196 + */
  5.2197 +static int qcow_sync_read(struct disk_driver *dd, uint64_t sector,
  5.2198 +		int nb_sectors, char *buf, td_callback_t cb,
  5.2199 +		int id, void *prv)
  5.2200 +{
  5.2201 +	int ret = qcow_read(dd, sector, (uint8_t*) buf, nb_sectors);
  5.2202 +
  5.2203 +	if (cb != NULL) {
  5.2204 +		return cb(dd, (ret < 0) ? ret : 0, sector, nb_sectors, id, prv);
  5.2205 +	} else {
  5.2206 +		return ret;
  5.2207 +	}
  5.2208 +}
  5.2209 +
  5.2210 +#ifndef USE_AIO
  5.2211 +/**
  5.2212 + * Wrapper for synchronous write
  5.2213 + */
  5.2214 +static int qcow_sync_write(struct disk_driver *dd, uint64_t sector,
  5.2215 +		int nb_sectors, char *buf, td_callback_t cb,
  5.2216 +		int id, void *prv)
  5.2217 +{
  5.2218 +	int ret = qcow_write(dd, sector, (uint8_t*) buf, nb_sectors);
  5.2219 +	
  5.2220 +	return cb(dd, (ret < 0) ? ret : 0, sector, nb_sectors, id, prv);
  5.2221 +}
  5.2222 +#endif
  5.2223 +
  5.2224 +
  5.2225 +
  5.2226 +#ifndef USE_AIO
  5.2227 +
  5.2228 +static int qcow_do_callbacks(struct disk_driver *dd, int sid)
  5.2229 +{
  5.2230 +	return 1;
  5.2231 +}
  5.2232 +
  5.2233 +#else
  5.2234 +
  5.2235 +static int qcow_do_callbacks(struct disk_driver *dd, int sid)
  5.2236 +{
  5.2237 +	int ret, i, nr_events, rsp = 0,*ptr;
  5.2238 +	struct io_event *ep;
  5.2239 +	struct BDRVQcowState *prv = (struct BDRVQcowState*)dd->private;
  5.2240 +
  5.2241 +	if (sid > MAX_IOFD) return 1;
  5.2242 +
  5.2243 +	nr_events = tap_aio_get_events(&prv->async.aio_ctx);
  5.2244 +
  5.2245 +repeat:
  5.2246 +	for (ep = prv->async.aio_events, i = nr_events; i-- > 0; ep++) {
  5.2247 +		struct iocb		   *io	= ep->obj;
  5.2248 +		struct pending_aio *pio;
  5.2249 +
  5.2250 +		pio = &prv->async.pending_aio[(long)io->data];
  5.2251 +
  5.2252 +		aio_unlock(prv, pio->sector);
  5.2253 +
  5.2254 +		if (prv->crypt_method)
  5.2255 +			encrypt_sectors(prv, pio->sector, 
  5.2256 +					(unsigned char *)pio->buf, 
  5.2257 +					(unsigned char *)pio->buf, 
  5.2258 +					pio->nb_sectors, 0, 
  5.2259 +					&prv->aes_decrypt_key);
  5.2260 +
  5.2261 +		rsp += pio->cb(dd, ep->res == io->u.c.nbytes ? 0 : 1, 
  5.2262 +			pio->sector, pio->nb_sectors,
  5.2263 +			pio->id, pio->private);
  5.2264 +
  5.2265 +		prv->async.iocb_free[prv->async.iocb_free_count++] = io;
  5.2266 +	}
  5.2267 +
  5.2268 +	if (nr_events) {
  5.2269 +		nr_events = tap_aio_more_events(&prv->async.aio_ctx);
  5.2270 +		goto repeat;
  5.2271 +	}
  5.2272 +
  5.2273 +	tap_aio_continue(&prv->async.aio_ctx);
  5.2274 +
  5.2275 +	return rsp;
  5.2276 +}
  5.2277 +
  5.2278 +#endif	
  5.2279 +
  5.2280 +/**
  5.2281 + * @return 
  5.2282 + *	   0 if parent id successfully retrieved;
  5.2283 + *	   TD_NO_PARENT if no parent exists;
  5.2284 + *	   -errno on error
  5.2285 + */
  5.2286 +static int qcow_get_parent_id(struct disk_driver *dd, struct disk_id *id)
  5.2287 +{
  5.2288 +	struct BDRVQcowState* s = (struct BDRVQcowState*) dd->private;
  5.2289 +
  5.2290 +	if (s->backing_file[0] == '\0')
  5.2291 +		return TD_NO_PARENT;
  5.2292 +
  5.2293 +	id->name = strdup(s->backing_file);
  5.2294 +	id->drivertype = DISK_TYPE_QCOW2;
  5.2295 +
  5.2296 +	return 0;
  5.2297 +}
  5.2298 +
  5.2299 +static int qcow_validate_parent(struct disk_driver *child, 
  5.2300 +		struct disk_driver *parent, td_flag_t flags)
  5.2301 +{
  5.2302 +	struct BDRVQcowState *cs = (struct BDRVQcowState*) child->private;
  5.2303 +	struct BDRVQcowState *ps = (struct BDRVQcowState*) parent->private;
  5.2304 +
  5.2305 +	if (ps->total_sectors != cs->total_sectors) {
  5.2306 +		DPRINTF("qcow_validate_parent(): %#"PRIx64" != %#"PRIx64"\n",
  5.2307 +			ps->total_sectors, cs->total_sectors);
  5.2308 +		return -EINVAL;
  5.2309 +	}
  5.2310 +	
  5.2311 +	return 0;
  5.2312 +}
  5.2313 +
  5.2314 +struct tap_disk tapdisk_qcow2 = {
  5.2315 +	"qcow2",
  5.2316 +	sizeof(BDRVQcowState),
  5.2317 +	qcow_open,
  5.2318 +#ifdef USE_AIO
  5.2319 +	qcow_queue_read,
  5.2320 +	qcow_queue_write,
  5.2321 +#else
  5.2322 +	qcow_sync_read,
  5.2323 +	qcow_sync_write,
  5.2324 +#endif
  5.2325 +	qcow_submit,
  5.2326 +	qcow_close,
  5.2327 +	qcow_do_callbacks,
  5.2328 +	qcow_get_parent_id,
  5.2329 +	qcow_validate_parent
  5.2330 +};
     6.1 --- a/tools/blktap/drivers/tapdisk.h	Wed Feb 20 18:18:03 2008 +0000
     6.2 +++ b/tools/blktap/drivers/tapdisk.h	Thu Feb 21 10:30:57 2008 +0000
     6.3 @@ -58,11 +58,12 @@
     6.4  
     6.5  #include <stdint.h>
     6.6  #include <syslog.h>
     6.7 +#include <stdio.h>
     6.8  #include "blktaplib.h"
     6.9  
    6.10  /*If enabled, log all debug messages to syslog*/
    6.11  #if 1
    6.12 -#define DPRINTF(_f, _a...) syslog( LOG_DEBUG, _f , ## _a )
    6.13 +#define DPRINTF(_f, _a...) syslog( LOG_DEBUG, __FILE__ ":%d: " _f , __LINE__, ## _a )
    6.14  #else
    6.15  #define DPRINTF(_f, _a...) ((void)0)
    6.16  #endif
    6.17 @@ -156,6 +157,7 @@ extern struct tap_disk tapdisk_sync;
    6.18  extern struct tap_disk tapdisk_vmdk;
    6.19  extern struct tap_disk tapdisk_ram;
    6.20  extern struct tap_disk tapdisk_qcow;
    6.21 +extern struct tap_disk tapdisk_qcow2;
    6.22  
    6.23  #define MAX_DISK_TYPES     20
    6.24  
    6.25 @@ -164,6 +166,7 @@ extern struct tap_disk tapdisk_qcow;
    6.26  #define DISK_TYPE_VMDK     2
    6.27  #define DISK_TYPE_RAM      3
    6.28  #define DISK_TYPE_QCOW     4
    6.29 +#define DISK_TYPE_QCOW2    5
    6.30  
    6.31  
    6.32  /*Define Individual Disk Parameters here */
    6.33 @@ -217,6 +220,16 @@ static disk_info_t qcow_disk = {
    6.34  #endif
    6.35  };
    6.36  
    6.37 +static disk_info_t qcow2_disk = {
    6.38 +	DISK_TYPE_QCOW2,
    6.39 +	"qcow2 disk (qcow2)",
    6.40 +	"qcow2",
    6.41 +	0,
    6.42 +#ifdef TAPDISK
    6.43 +	&tapdisk_qcow2,
    6.44 +#endif
    6.45 +};
    6.46 +
    6.47  /*Main disk info array */
    6.48  static disk_info_t *dtypes[] = {
    6.49  	&aio_disk,
    6.50 @@ -224,6 +237,7 @@ static disk_info_t *dtypes[] = {
    6.51  	&vmdk_disk,
    6.52  	&ram_disk,
    6.53  	&qcow_disk,
    6.54 +	&qcow2_disk,
    6.55  };
    6.56  
    6.57  typedef struct driver_list_entry {
     7.1 --- a/tools/python/xen/xend/server/BlktapController.py	Wed Feb 20 18:18:03 2008 +0000
     7.2 +++ b/tools/python/xen/xend/server/BlktapController.py	Thu Feb 21 10:30:57 2008 +0000
     7.3 @@ -12,7 +12,8 @@ blktap_disk_types = [
     7.4      'sync',
     7.5      'vmdk',
     7.6      'ram',
     7.7 -    'qcow'
     7.8 +    'qcow',
     7.9 +    'qcow2'
    7.10      ]
    7.11  
    7.12  class BlktapController(BlkifController):