]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow.c
cow: Use bdrv_(p)write_sync for metadata writes
[mirror_qemu.git] / block / qcow.c
CommitLineData
ea2384d3
FB
1/*
2 * Block driver for the QCOW format
5fafdf24 3 *
83f64091 4 * Copyright (c) 2004-2006 Fabrice Bellard
5fafdf24 5 *
ea2384d3
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"
ea2384d3 25#include "block_int.h"
5efa9d5a 26#include "module.h"
28d34b82 27#include <zlib.h>
ea2384d3
FB
28#include "aes.h"
29
30/**************************************************************/
31/* QEMU COW block driver with compression and encryption support */
32
33#define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
34#define QCOW_VERSION 1
35
36#define QCOW_CRYPT_NONE 0
37#define QCOW_CRYPT_AES 1
38
39#define QCOW_OFLAG_COMPRESSED (1LL << 63)
40
41typedef struct QCowHeader {
42 uint32_t magic;
43 uint32_t version;
44 uint64_t backing_file_offset;
45 uint32_t backing_file_size;
46 uint32_t mtime;
47 uint64_t size; /* in bytes */
48 uint8_t cluster_bits;
49 uint8_t l2_bits;
50 uint32_t crypt_method;
51 uint64_t l1_table_offset;
52} QCowHeader;
53
54#define L2_CACHE_SIZE 16
55
56typedef struct BDRVQcowState {
83f64091 57 BlockDriverState *hd;
ea2384d3
FB
58 int cluster_bits;
59 int cluster_size;
60 int cluster_sectors;
61 int l2_bits;
62 int l2_size;
63 int l1_size;
64 uint64_t cluster_offset_mask;
65 uint64_t l1_table_offset;
66 uint64_t *l1_table;
67 uint64_t *l2_cache;
68 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
69 uint32_t l2_cache_counts[L2_CACHE_SIZE];
70 uint8_t *cluster_cache;
71 uint8_t *cluster_data;
72 uint64_t cluster_cache_offset;
73 uint32_t crypt_method; /* current crypt method, 0 if no key yet */
74 uint32_t crypt_method_header;
75 AES_KEY aes_encrypt_key;
76 AES_KEY aes_decrypt_key;
77} BDRVQcowState;
78
66f82cee 79static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
ea2384d3
FB
80
81static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
82{
83 const QCowHeader *cow_header = (const void *)buf;
3b46e624 84
712e7874
FB
85 if (buf_size >= sizeof(QCowHeader) &&
86 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
5fafdf24 87 be32_to_cpu(cow_header->version) == QCOW_VERSION)
ea2384d3
FB
88 return 100;
89 else
90 return 0;
91}
92
66f82cee 93static int qcow_open(BlockDriverState *bs, int flags)
ea2384d3
FB
94{
95 BDRVQcowState *s = bs->opaque;
66f82cee 96 int len, i, shift;
ea2384d3 97 QCowHeader header;
83f64091 98
66f82cee 99 if (bdrv_pread(bs->file, 0, &header, sizeof(header)) != sizeof(header))
ea2384d3
FB
100 goto fail;
101 be32_to_cpus(&header.magic);
102 be32_to_cpus(&header.version);
103 be64_to_cpus(&header.backing_file_offset);
104 be32_to_cpus(&header.backing_file_size);
105 be32_to_cpus(&header.mtime);
106 be64_to_cpus(&header.size);
107 be32_to_cpus(&header.crypt_method);
108 be64_to_cpus(&header.l1_table_offset);
3b46e624 109
ea2384d3
FB
110 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
111 goto fail;
112 if (header.size <= 1 || header.cluster_bits < 9)
113 goto fail;
114 if (header.crypt_method > QCOW_CRYPT_AES)
115 goto fail;
116 s->crypt_method_header = header.crypt_method;
117 if (s->crypt_method_header)
118 bs->encrypted = 1;
119 s->cluster_bits = header.cluster_bits;
120 s->cluster_size = 1 << s->cluster_bits;
121 s->cluster_sectors = 1 << (s->cluster_bits - 9);
122 s->l2_bits = header.l2_bits;
123 s->l2_size = 1 << s->l2_bits;
124 bs->total_sectors = header.size / 512;
125 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
126
127 /* read the level 1 table */
128 shift = s->cluster_bits + s->l2_bits;
129 s->l1_size = (header.size + (1LL << shift) - 1) >> shift;
130
131 s->l1_table_offset = header.l1_table_offset;
132 s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
133 if (!s->l1_table)
134 goto fail;
66f82cee 135 if (bdrv_pread(bs->file, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
ea2384d3
FB
136 s->l1_size * sizeof(uint64_t))
137 goto fail;
138 for(i = 0;i < s->l1_size; i++) {
139 be64_to_cpus(&s->l1_table[i]);
140 }
141 /* alloc L2 cache */
142 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
143 if (!s->l2_cache)
144 goto fail;
145 s->cluster_cache = qemu_malloc(s->cluster_size);
146 if (!s->cluster_cache)
147 goto fail;
148 s->cluster_data = qemu_malloc(s->cluster_size);
149 if (!s->cluster_data)
150 goto fail;
151 s->cluster_cache_offset = -1;
3b46e624 152
ea2384d3
FB
153 /* read the backing file name */
154 if (header.backing_file_offset != 0) {
155 len = header.backing_file_size;
156 if (len > 1023)
157 len = 1023;
66f82cee 158 if (bdrv_pread(bs->file, header.backing_file_offset, bs->backing_file, len) != len)
ea2384d3
FB
159 goto fail;
160 bs->backing_file[len] = '\0';
161 }
162 return 0;
163
164 fail:
165 qemu_free(s->l1_table);
166 qemu_free(s->l2_cache);
167 qemu_free(s->cluster_cache);
168 qemu_free(s->cluster_data);
ea2384d3
FB
169 return -1;
170}
171
172static int qcow_set_key(BlockDriverState *bs, const char *key)
173{
174 BDRVQcowState *s = bs->opaque;
175 uint8_t keybuf[16];
176 int len, i;
3b46e624 177
ea2384d3
FB
178 memset(keybuf, 0, 16);
179 len = strlen(key);
180 if (len > 16)
181 len = 16;
182 /* XXX: we could compress the chars to 7 bits to increase
183 entropy */
184 for(i = 0;i < len;i++) {
185 keybuf[i] = key[i];
186 }
187 s->crypt_method = s->crypt_method_header;
188
189 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
190 return -1;
191 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
192 return -1;
193#if 0
194 /* test */
195 {
196 uint8_t in[16];
197 uint8_t out[16];
198 uint8_t tmp[16];
199 for(i=0;i<16;i++)
200 in[i] = i;
201 AES_encrypt(in, tmp, &s->aes_encrypt_key);
202 AES_decrypt(tmp, out, &s->aes_decrypt_key);
203 for(i = 0; i < 16; i++)
204 printf(" %02x", tmp[i]);
205 printf("\n");
206 for(i = 0; i < 16; i++)
207 printf(" %02x", out[i]);
208 printf("\n");
209 }
210#endif
211 return 0;
212}
213
214/* The crypt function is compatible with the linux cryptoloop
215 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
216 supported */
217static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
218 uint8_t *out_buf, const uint8_t *in_buf,
219 int nb_sectors, int enc,
220 const AES_KEY *key)
221{
222 union {
223 uint64_t ll[2];
224 uint8_t b[16];
225 } ivec;
226 int i;
227
228 for(i = 0; i < nb_sectors; i++) {
229 ivec.ll[0] = cpu_to_le64(sector_num);
230 ivec.ll[1] = 0;
5fafdf24 231 AES_cbc_encrypt(in_buf, out_buf, 512, key,
ea2384d3
FB
232 ivec.b, enc);
233 sector_num++;
234 in_buf += 512;
235 out_buf += 512;
236 }
237}
238
239/* 'allocate' is:
240 *
241 * 0 to not allocate.
242 *
243 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
244 * 'n_end')
245 *
246 * 2 to allocate a compressed cluster of size
247 * 'compressed_size'. 'compressed_size' must be > 0 and <
5fafdf24 248 * cluster_size
ea2384d3
FB
249 *
250 * return 0 if not allocated.
251 */
252static uint64_t get_cluster_offset(BlockDriverState *bs,
253 uint64_t offset, int allocate,
254 int compressed_size,
255 int n_start, int n_end)
256{
257 BDRVQcowState *s = bs->opaque;
258 int min_index, i, j, l1_index, l2_index;
259 uint64_t l2_offset, *l2_table, cluster_offset, tmp;
260 uint32_t min_count;
261 int new_l2_table;
3b46e624 262
ea2384d3
FB
263 l1_index = offset >> (s->l2_bits + s->cluster_bits);
264 l2_offset = s->l1_table[l1_index];
265 new_l2_table = 0;
266 if (!l2_offset) {
267 if (!allocate)
268 return 0;
269 /* allocate a new l2 entry */
66f82cee 270 l2_offset = bdrv_getlength(bs->file);
ea2384d3
FB
271 /* round to cluster size */
272 l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
273 /* update the L1 entry */
274 s->l1_table[l1_index] = l2_offset;
275 tmp = cpu_to_be64(l2_offset);
66f82cee 276 if (bdrv_pwrite(bs->file, s->l1_table_offset + l1_index * sizeof(tmp),
83f64091 277 &tmp, sizeof(tmp)) != sizeof(tmp))
ea2384d3
FB
278 return 0;
279 new_l2_table = 1;
280 }
281 for(i = 0; i < L2_CACHE_SIZE; i++) {
282 if (l2_offset == s->l2_cache_offsets[i]) {
283 /* increment the hit count */
284 if (++s->l2_cache_counts[i] == 0xffffffff) {
285 for(j = 0; j < L2_CACHE_SIZE; j++) {
286 s->l2_cache_counts[j] >>= 1;
287 }
288 }
289 l2_table = s->l2_cache + (i << s->l2_bits);
290 goto found;
291 }
292 }
293 /* not found: load a new entry in the least used one */
294 min_index = 0;
295 min_count = 0xffffffff;
296 for(i = 0; i < L2_CACHE_SIZE; i++) {
297 if (s->l2_cache_counts[i] < min_count) {
298 min_count = s->l2_cache_counts[i];
299 min_index = i;
300 }
301 }
302 l2_table = s->l2_cache + (min_index << s->l2_bits);
ea2384d3
FB
303 if (new_l2_table) {
304 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
66f82cee 305 if (bdrv_pwrite(bs->file, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
ea2384d3
FB
306 s->l2_size * sizeof(uint64_t))
307 return 0;
308 } else {
66f82cee 309 if (bdrv_pread(bs->file, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
ea2384d3
FB
310 s->l2_size * sizeof(uint64_t))
311 return 0;
312 }
313 s->l2_cache_offsets[min_index] = l2_offset;
314 s->l2_cache_counts[min_index] = 1;
315 found:
316 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
317 cluster_offset = be64_to_cpu(l2_table[l2_index]);
5fafdf24 318 if (!cluster_offset ||
ea2384d3
FB
319 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
320 if (!allocate)
321 return 0;
322 /* allocate a new cluster */
323 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
324 (n_end - n_start) < s->cluster_sectors) {
325 /* if the cluster is already compressed, we must
326 decompress it in the case it is not completely
327 overwritten */
66f82cee 328 if (decompress_cluster(bs, cluster_offset) < 0)
ea2384d3 329 return 0;
66f82cee 330 cluster_offset = bdrv_getlength(bs->file);
5fafdf24 331 cluster_offset = (cluster_offset + s->cluster_size - 1) &
ea2384d3
FB
332 ~(s->cluster_size - 1);
333 /* write the cluster content */
66f82cee 334 if (bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache, s->cluster_size) !=
ea2384d3
FB
335 s->cluster_size)
336 return -1;
337 } else {
66f82cee 338 cluster_offset = bdrv_getlength(bs->file);
7f48fa1f
AL
339 if (allocate == 1) {
340 /* round to cluster size */
341 cluster_offset = (cluster_offset + s->cluster_size - 1) &
342 ~(s->cluster_size - 1);
66f82cee 343 bdrv_truncate(bs->file, cluster_offset + s->cluster_size);
7f48fa1f
AL
344 /* if encrypted, we must initialize the cluster
345 content which won't be written */
346 if (s->crypt_method &&
347 (n_end - n_start) < s->cluster_sectors) {
348 uint64_t start_sect;
349 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
350 memset(s->cluster_data + 512, 0x00, 512);
351 for(i = 0; i < s->cluster_sectors; i++) {
352 if (i < n_start || i >= n_end) {
353 encrypt_sectors(s, start_sect + i,
354 s->cluster_data,
355 s->cluster_data + 512, 1, 1,
356 &s->aes_encrypt_key);
66f82cee 357 if (bdrv_pwrite(bs->file, cluster_offset + i * 512,
7f48fa1f
AL
358 s->cluster_data, 512) != 512)
359 return -1;
360 }
ea2384d3
FB
361 }
362 }
7f48fa1f
AL
363 } else if (allocate == 2) {
364 cluster_offset |= QCOW_OFLAG_COMPRESSED |
365 (uint64_t)compressed_size << (63 - s->cluster_bits);
ea2384d3
FB
366 }
367 }
368 /* update L2 table */
369 tmp = cpu_to_be64(cluster_offset);
370 l2_table[l2_index] = tmp;
66f82cee 371 if (bdrv_pwrite(bs->file,
83f64091 372 l2_offset + l2_index * sizeof(tmp), &tmp, sizeof(tmp)) != sizeof(tmp))
ea2384d3
FB
373 return 0;
374 }
375 return cluster_offset;
376}
377
5fafdf24 378static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
ea2384d3
FB
379 int nb_sectors, int *pnum)
380{
381 BDRVQcowState *s = bs->opaque;
382 int index_in_cluster, n;
383 uint64_t cluster_offset;
384
385 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
386 index_in_cluster = sector_num & (s->cluster_sectors - 1);
387 n = s->cluster_sectors - index_in_cluster;
388 if (n > nb_sectors)
389 n = nb_sectors;
390 *pnum = n;
391 return (cluster_offset != 0);
392}
393
394static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
395 const uint8_t *buf, int buf_size)
396{
397 z_stream strm1, *strm = &strm1;
398 int ret, out_len;
399
400 memset(strm, 0, sizeof(*strm));
401
402 strm->next_in = (uint8_t *)buf;
403 strm->avail_in = buf_size;
404 strm->next_out = out_buf;
405 strm->avail_out = out_buf_size;
406
407 ret = inflateInit2(strm, -12);
408 if (ret != Z_OK)
409 return -1;
410 ret = inflate(strm, Z_FINISH);
411 out_len = strm->next_out - out_buf;
412 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
413 out_len != out_buf_size) {
414 inflateEnd(strm);
415 return -1;
416 }
417 inflateEnd(strm);
418 return 0;
419}
3b46e624 420
66f82cee 421static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
ea2384d3 422{
66f82cee 423 BDRVQcowState *s = bs->opaque;
ea2384d3
FB
424 int ret, csize;
425 uint64_t coffset;
426
427 coffset = cluster_offset & s->cluster_offset_mask;
428 if (s->cluster_cache_offset != coffset) {
429 csize = cluster_offset >> (63 - s->cluster_bits);
430 csize &= (s->cluster_size - 1);
66f82cee 431 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
5fafdf24 432 if (ret != csize)
ea2384d3
FB
433 return -1;
434 if (decompress_buffer(s->cluster_cache, s->cluster_size,
435 s->cluster_data, csize) < 0) {
436 return -1;
437 }
438 s->cluster_cache_offset = coffset;
439 }
440 return 0;
441}
442
83f64091
FB
443#if 0
444
5fafdf24 445static int qcow_read(BlockDriverState *bs, int64_t sector_num,
ea2384d3
FB
446 uint8_t *buf, int nb_sectors)
447{
448 BDRVQcowState *s = bs->opaque;
449 int ret, index_in_cluster, n;
450 uint64_t cluster_offset;
3b46e624 451
ea2384d3
FB
452 while (nb_sectors > 0) {
453 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
454 index_in_cluster = sector_num & (s->cluster_sectors - 1);
455 n = s->cluster_sectors - index_in_cluster;
456 if (n > nb_sectors)
457 n = nb_sectors;
458 if (!cluster_offset) {
83f64091
FB
459 if (bs->backing_hd) {
460 /* read from the base image */
461 ret = bdrv_read(bs->backing_hd, sector_num, buf, n);
462 if (ret < 0)
463 return -1;
464 } else {
465 memset(buf, 0, 512 * n);
466 }
ea2384d3 467 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
66f82cee 468 if (decompress_cluster(bs, cluster_offset) < 0)
ea2384d3
FB
469 return -1;
470 memcpy(buf, s->cluster_cache + index_in_cluster * 512, 512 * n);
471 } else {
66f82cee 472 ret = bdrv_pread(bs->file, cluster_offset + index_in_cluster * 512, buf, n * 512);
5fafdf24 473 if (ret != n * 512)
ea2384d3
FB
474 return -1;
475 if (s->crypt_method) {
5fafdf24 476 encrypt_sectors(s, sector_num, buf, buf, n, 0,
ea2384d3
FB
477 &s->aes_decrypt_key);
478 }
479 }
480 nb_sectors -= n;
481 sector_num += n;
482 buf += n * 512;
483 }
484 return 0;
485}
83f64091 486#endif
ea2384d3 487
ce1a14dc
PB
488typedef struct QCowAIOCB {
489 BlockDriverAIOCB common;
83f64091 490 int64_t sector_num;
f141eafe 491 QEMUIOVector *qiov;
83f64091 492 uint8_t *buf;
f141eafe 493 void *orig_buf;
83f64091
FB
494 int nb_sectors;
495 int n;
496 uint64_t cluster_offset;
5fafdf24 497 uint8_t *cluster_data;
c87c0672
AL
498 struct iovec hd_iov;
499 QEMUIOVector hd_qiov;
83f64091 500 BlockDriverAIOCB *hd_aiocb;
83f64091
FB
501} QCowAIOCB;
502
c16b5a2c
CH
503static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
504{
b666d239 505 QCowAIOCB *acb = container_of(blockacb, QCowAIOCB, common);
c16b5a2c
CH
506 if (acb->hd_aiocb)
507 bdrv_aio_cancel(acb->hd_aiocb);
508 qemu_aio_release(acb);
509}
510
511static AIOPool qcow_aio_pool = {
512 .aiocb_size = sizeof(QCowAIOCB),
513 .cancel = qcow_aio_cancel,
514};
ad53089b
CH
515
516static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
517 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
518 BlockDriverCompletionFunc *cb, void *opaque, int is_write)
519{
520 QCowAIOCB *acb;
521
c16b5a2c 522 acb = qemu_aio_get(&qcow_aio_pool, bs, cb, opaque);
ad53089b
CH
523 if (!acb)
524 return NULL;
525 acb->hd_aiocb = NULL;
526 acb->sector_num = sector_num;
527 acb->qiov = qiov;
528 if (qiov->niov > 1) {
529 acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
530 if (is_write)
531 qemu_iovec_to_buffer(qiov, acb->buf);
532 } else {
533 acb->buf = (uint8_t *)qiov->iov->iov_base;
534 }
535 acb->nb_sectors = nb_sectors;
536 acb->n = 0;
537 acb->cluster_offset = 0;
538 return acb;
539}
540
83f64091
FB
541static void qcow_aio_read_cb(void *opaque, int ret)
542{
ce1a14dc
PB
543 QCowAIOCB *acb = opaque;
544 BlockDriverState *bs = acb->common.bs;
83f64091 545 BDRVQcowState *s = bs->opaque;
83f64091
FB
546 int index_in_cluster;
547
ce1a14dc 548 acb->hd_aiocb = NULL;
f141eafe
AL
549 if (ret < 0)
550 goto done;
83f64091
FB
551
552 redo:
553 /* post process the read buffer */
ce1a14dc 554 if (!acb->cluster_offset) {
83f64091 555 /* nothing to do */
ce1a14dc 556 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
83f64091
FB
557 /* nothing to do */
558 } else {
559 if (s->crypt_method) {
5fafdf24
TS
560 encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
561 acb->n, 0,
83f64091
FB
562 &s->aes_decrypt_key);
563 }
564 }
565
ce1a14dc
PB
566 acb->nb_sectors -= acb->n;
567 acb->sector_num += acb->n;
568 acb->buf += acb->n * 512;
83f64091 569
ce1a14dc 570 if (acb->nb_sectors == 0) {
83f64091 571 /* request completed */
f141eafe
AL
572 ret = 0;
573 goto done;
83f64091 574 }
3b46e624 575
83f64091 576 /* prepare next AIO request */
5fafdf24 577 acb->cluster_offset = get_cluster_offset(bs, acb->sector_num << 9,
ce1a14dc
PB
578 0, 0, 0, 0);
579 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
580 acb->n = s->cluster_sectors - index_in_cluster;
581 if (acb->n > acb->nb_sectors)
582 acb->n = acb->nb_sectors;
583
584 if (!acb->cluster_offset) {
83f64091
FB
585 if (bs->backing_hd) {
586 /* read from the base image */
3f4cb3d3 587 acb->hd_iov.iov_base = (void *)acb->buf;
c87c0672
AL
588 acb->hd_iov.iov_len = acb->n * 512;
589 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
590 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
591 &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
ce1a14dc 592 if (acb->hd_aiocb == NULL)
f141eafe 593 goto done;
83f64091
FB
594 } else {
595 /* Note: in this case, no need to wait */
ce1a14dc 596 memset(acb->buf, 0, 512 * acb->n);
83f64091
FB
597 goto redo;
598 }
ce1a14dc 599 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
83f64091 600 /* add AIO support for compressed blocks ? */
66f82cee 601 if (decompress_cluster(bs, acb->cluster_offset) < 0)
f141eafe 602 goto done;
5fafdf24 603 memcpy(acb->buf,
ce1a14dc 604 s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
83f64091
FB
605 goto redo;
606 } else {
ce1a14dc 607 if ((acb->cluster_offset & 511) != 0) {
83f64091 608 ret = -EIO;
f141eafe 609 goto done;
83f64091 610 }
3f4cb3d3 611 acb->hd_iov.iov_base = (void *)acb->buf;
c87c0672
AL
612 acb->hd_iov.iov_len = acb->n * 512;
613 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
66f82cee 614 acb->hd_aiocb = bdrv_aio_readv(bs->file,
5fafdf24 615 (acb->cluster_offset >> 9) + index_in_cluster,
c87c0672 616 &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
ce1a14dc 617 if (acb->hd_aiocb == NULL)
f141eafe
AL
618 goto done;
619 }
620
621 return;
622
623done:
624 if (acb->qiov->niov > 1) {
625 qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
626 qemu_vfree(acb->orig_buf);
83f64091 627 }
f141eafe
AL
628 acb->common.cb(acb->common.opaque, ret);
629 qemu_aio_release(acb);
83f64091
FB
630}
631
f141eafe
AL
632static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
633 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 634 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 635{
ce1a14dc
PB
636 QCowAIOCB *acb;
637
ad53089b 638 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
ce1a14dc
PB
639 if (!acb)
640 return NULL;
83f64091
FB
641
642 qcow_aio_read_cb(acb, 0);
ce1a14dc 643 return &acb->common;
83f64091
FB
644}
645
646static void qcow_aio_write_cb(void *opaque, int ret)
647{
ce1a14dc
PB
648 QCowAIOCB *acb = opaque;
649 BlockDriverState *bs = acb->common.bs;
83f64091 650 BDRVQcowState *s = bs->opaque;
83f64091
FB
651 int index_in_cluster;
652 uint64_t cluster_offset;
653 const uint8_t *src_buf;
ce1a14dc
PB
654
655 acb->hd_aiocb = NULL;
656
f141eafe
AL
657 if (ret < 0)
658 goto done;
83f64091 659
ce1a14dc
PB
660 acb->nb_sectors -= acb->n;
661 acb->sector_num += acb->n;
662 acb->buf += acb->n * 512;
83f64091 663
ce1a14dc 664 if (acb->nb_sectors == 0) {
83f64091 665 /* request completed */
f141eafe
AL
666 ret = 0;
667 goto done;
83f64091 668 }
3b46e624 669
ce1a14dc
PB
670 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
671 acb->n = s->cluster_sectors - index_in_cluster;
672 if (acb->n > acb->nb_sectors)
673 acb->n = acb->nb_sectors;
5fafdf24
TS
674 cluster_offset = get_cluster_offset(bs, acb->sector_num << 9, 1, 0,
675 index_in_cluster,
ce1a14dc 676 index_in_cluster + acb->n);
83f64091
FB
677 if (!cluster_offset || (cluster_offset & 511) != 0) {
678 ret = -EIO;
f141eafe 679 goto done;
83f64091
FB
680 }
681 if (s->crypt_method) {
ce1a14dc
PB
682 if (!acb->cluster_data) {
683 acb->cluster_data = qemu_mallocz(s->cluster_size);
684 if (!acb->cluster_data) {
83f64091 685 ret = -ENOMEM;
f141eafe 686 goto done;
83f64091
FB
687 }
688 }
5fafdf24 689 encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
ce1a14dc
PB
690 acb->n, 1, &s->aes_encrypt_key);
691 src_buf = acb->cluster_data;
83f64091 692 } else {
ce1a14dc 693 src_buf = acb->buf;
83f64091 694 }
c87c0672
AL
695
696 acb->hd_iov.iov_base = (void *)src_buf;
697 acb->hd_iov.iov_len = acb->n * 512;
698 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
66f82cee 699 acb->hd_aiocb = bdrv_aio_writev(bs->file,
c87c0672
AL
700 (cluster_offset >> 9) + index_in_cluster,
701 &acb->hd_qiov, acb->n,
702 qcow_aio_write_cb, acb);
ce1a14dc 703 if (acb->hd_aiocb == NULL)
f141eafe
AL
704 goto done;
705 return;
706
707done:
708 if (acb->qiov->niov > 1)
709 qemu_vfree(acb->orig_buf);
710 acb->common.cb(acb->common.opaque, ret);
711 qemu_aio_release(acb);
83f64091
FB
712}
713
f141eafe
AL
714static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
715 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
ce1a14dc 716 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 717{
83f64091 718 BDRVQcowState *s = bs->opaque;
ce1a14dc 719 QCowAIOCB *acb;
3b46e624 720
83f64091
FB
721 s->cluster_cache_offset = -1; /* disable compressed cache */
722
c53ffce9 723 acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
ce1a14dc
PB
724 if (!acb)
725 return NULL;
ad53089b 726
3b46e624 727
83f64091 728 qcow_aio_write_cb(acb, 0);
ce1a14dc 729 return &acb->common;
83f64091
FB
730}
731
e2731add 732static void qcow_close(BlockDriverState *bs)
ea2384d3
FB
733{
734 BDRVQcowState *s = bs->opaque;
735 qemu_free(s->l1_table);
736 qemu_free(s->l2_cache);
737 qemu_free(s->cluster_cache);
738 qemu_free(s->cluster_data);
ea2384d3
FB
739}
740
0e7e1989 741static int qcow_create(const char *filename, QEMUOptionParameter *options)
ea2384d3
FB
742{
743 int fd, header_size, backing_filename_len, l1_size, i, shift;
744 QCowHeader header;
ea2384d3 745 uint64_t tmp;
0e7e1989
KW
746 int64_t total_size = 0;
747 const char *backing_file = NULL;
748 int flags = 0;
3e1a8134 749 int ret;
0e7e1989
KW
750
751 /* Read out options */
752 while (options && options->name) {
753 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
754 total_size = options->value.n / 512;
755 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
756 backing_file = options->value.s;
757 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
758 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
759 }
760 options++;
761 }
ea2384d3 762
83f64091 763 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
ea2384d3 764 if (fd < 0)
98c2b2f4 765 return -errno;
ea2384d3
FB
766 memset(&header, 0, sizeof(header));
767 header.magic = cpu_to_be32(QCOW_MAGIC);
768 header.version = cpu_to_be32(QCOW_VERSION);
769 header.size = cpu_to_be64(total_size * 512);
770 header_size = sizeof(header);
771 backing_filename_len = 0;
772 if (backing_file) {
7852e5da
AJ
773 if (strcmp(backing_file, "fat:")) {
774 header.backing_file_offset = cpu_to_be64(header_size);
775 backing_filename_len = strlen(backing_file);
776 header.backing_file_size = cpu_to_be32(backing_filename_len);
777 header_size += backing_filename_len;
778 } else {
779 /* special backing file for vvfat */
780 backing_file = NULL;
781 }
ea2384d3
FB
782 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
783 unmodifyed sectors */
784 header.l2_bits = 12; /* 32 KB L2 tables */
785 } else {
786 header.cluster_bits = 12; /* 4 KB clusters */
787 header.l2_bits = 9; /* 4 KB L2 tables */
788 }
789 header_size = (header_size + 7) & ~7;
790 shift = header.cluster_bits + header.l2_bits;
791 l1_size = ((total_size * 512) + (1LL << shift) - 1) >> shift;
792
793 header.l1_table_offset = cpu_to_be64(header_size);
ec36ba14 794 if (flags & BLOCK_FLAG_ENCRYPT) {
ea2384d3
FB
795 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
796 } else {
797 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
798 }
3b46e624 799
ea2384d3 800 /* write all the data */
3e1a8134
KS
801 ret = qemu_write_full(fd, &header, sizeof(header));
802 if (ret != sizeof(header)) {
98c2b2f4 803 ret = -errno;
3e1a8134
KS
804 goto exit;
805 }
806
ea2384d3 807 if (backing_file) {
3e1a8134
KS
808 ret = qemu_write_full(fd, backing_file, backing_filename_len);
809 if (ret != backing_filename_len) {
98c2b2f4 810 ret = -errno;
3e1a8134
KS
811 goto exit;
812 }
813
ea2384d3
FB
814 }
815 lseek(fd, header_size, SEEK_SET);
816 tmp = 0;
817 for(i = 0;i < l1_size; i++) {
3e1a8134
KS
818 ret = qemu_write_full(fd, &tmp, sizeof(tmp));
819 if (ret != sizeof(tmp)) {
98c2b2f4 820 ret = -errno;
3e1a8134
KS
821 goto exit;
822 }
ea2384d3 823 }
3e1a8134
KS
824
825 ret = 0;
826exit:
ea2384d3 827 close(fd);
3e1a8134 828 return ret;
ea2384d3
FB
829}
830
c47c33b0 831static int qcow_make_empty(BlockDriverState *bs)
95389c86
FB
832{
833 BDRVQcowState *s = bs->opaque;
834 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
83f64091 835 int ret;
95389c86
FB
836
837 memset(s->l1_table, 0, l1_length);
66f82cee 838 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
95389c86 839 return -1;
66f82cee 840 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
83f64091
FB
841 if (ret < 0)
842 return ret;
95389c86
FB
843
844 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
845 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
846 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
847
848 return 0;
849}
850
ea2384d3
FB
851/* XXX: put compressed sectors first, then all the cluster aligned
852 tables to avoid losing bytes in alignment */
5fafdf24 853static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
c47c33b0 854 const uint8_t *buf, int nb_sectors)
ea2384d3
FB
855{
856 BDRVQcowState *s = bs->opaque;
857 z_stream strm;
858 int ret, out_len;
859 uint8_t *out_buf;
860 uint64_t cluster_offset;
861
c47c33b0
FB
862 if (nb_sectors != s->cluster_sectors)
863 return -EINVAL;
ea2384d3
FB
864
865 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
866 if (!out_buf)
867 return -1;
868
869 /* best compression, small window, no zlib header */
870 memset(&strm, 0, sizeof(strm));
871 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
5fafdf24 872 Z_DEFLATED, -12,
ea2384d3
FB
873 9, Z_DEFAULT_STRATEGY);
874 if (ret != 0) {
875 qemu_free(out_buf);
876 return -1;
877 }
878
879 strm.avail_in = s->cluster_size;
880 strm.next_in = (uint8_t *)buf;
881 strm.avail_out = s->cluster_size;
882 strm.next_out = out_buf;
883
884 ret = deflate(&strm, Z_FINISH);
885 if (ret != Z_STREAM_END && ret != Z_OK) {
886 qemu_free(out_buf);
887 deflateEnd(&strm);
888 return -1;
889 }
890 out_len = strm.next_out - out_buf;
891
892 deflateEnd(&strm);
893
894 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
895 /* could not compress: write normal cluster */
ade40677 896 bdrv_write(bs, sector_num, buf, s->cluster_sectors);
ea2384d3 897 } else {
5fafdf24 898 cluster_offset = get_cluster_offset(bs, sector_num << 9, 2,
ea2384d3
FB
899 out_len, 0, 0);
900 cluster_offset &= s->cluster_offset_mask;
66f82cee 901 if (bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len) != out_len) {
ea2384d3
FB
902 qemu_free(out_buf);
903 return -1;
904 }
905 }
3b46e624 906
ea2384d3
FB
907 qemu_free(out_buf);
908 return 0;
909}
910
7a6cba61
PB
911static void qcow_flush(BlockDriverState *bs)
912{
66f82cee 913 bdrv_flush(bs->file);
7a6cba61
PB
914}
915
f8012c13
KW
916static BlockDriverAIOCB *qcow_aio_flush(BlockDriverState *bs,
917 BlockDriverCompletionFunc *cb, void *opaque)
918{
66f82cee 919 return bdrv_aio_flush(bs->file, cb, opaque);
f8012c13
KW
920}
921
c47c33b0
FB
922static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
923{
924 BDRVQcowState *s = bs->opaque;
925 bdi->cluster_size = s->cluster_size;
926 return 0;
927}
928
0e7e1989
KW
929
930static QEMUOptionParameter qcow_create_options[] = {
db08adf5
KW
931 {
932 .name = BLOCK_OPT_SIZE,
933 .type = OPT_SIZE,
934 .help = "Virtual disk size"
935 },
936 {
937 .name = BLOCK_OPT_BACKING_FILE,
938 .type = OPT_STRING,
939 .help = "File name of a base image"
940 },
941 {
942 .name = BLOCK_OPT_ENCRYPT,
943 .type = OPT_FLAG,
944 .help = "Encrypt the image"
945 },
0e7e1989
KW
946 { NULL }
947};
948
5efa9d5a 949static BlockDriver bdrv_qcow = {
e60f469c
AJ
950 .format_name = "qcow",
951 .instance_size = sizeof(BDRVQcowState),
952 .bdrv_probe = qcow_probe,
953 .bdrv_open = qcow_open,
954 .bdrv_close = qcow_close,
955 .bdrv_create = qcow_create,
956 .bdrv_flush = qcow_flush,
957 .bdrv_is_allocated = qcow_is_allocated,
958 .bdrv_set_key = qcow_set_key,
959 .bdrv_make_empty = qcow_make_empty,
f141eafe
AL
960 .bdrv_aio_readv = qcow_aio_readv,
961 .bdrv_aio_writev = qcow_aio_writev,
f8012c13 962 .bdrv_aio_flush = qcow_aio_flush,
c47c33b0 963 .bdrv_write_compressed = qcow_write_compressed,
e60f469c 964 .bdrv_get_info = qcow_get_info,
0e7e1989
KW
965
966 .create_options = qcow_create_options,
ea2384d3 967};
5efa9d5a
AL
968
969static void bdrv_qcow_init(void)
970{
971 bdrv_register(&bdrv_qcow);
972}
973
974block_init(bdrv_qcow_init);