]> git.proxmox.com Git - qemu.git/blame - block/qcow2.c
Add proper -errno error return values to qcow2_open()
[qemu.git] / block / qcow2.c
CommitLineData
585f8587
FB
1/*
2 * Block driver for the QCOW version 2 format
5fafdf24 3 *
585f8587 4 * Copyright (c) 2004-2006 Fabrice Bellard
5fafdf24 5 *
585f8587
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
faf07963 24#include "qemu-common.h"
585f8587 25#include "block_int.h"
5efa9d5a 26#include "module.h"
585f8587
FB
27#include <zlib.h>
28#include "aes.h"
f7d0fe02 29#include "block/qcow2.h"
a9420734 30#include "qemu-error.h"
585f8587
FB
31
32/*
33 Differences with QCOW:
34
35 - Support for multiple incremental snapshots.
36 - Memory management by reference counts.
37 - Clusters which have a reference count of one have the bit
38 QCOW_OFLAG_COPIED to optimize write performance.
5fafdf24 39 - Size of compressed clusters is stored in sectors to reduce bit usage
585f8587
FB
40 in the cluster offsets.
41 - Support for storing additional data (such as the VM state) in the
3b46e624 42 snapshots.
585f8587
FB
43 - If a backing store is used, the cluster size is not constrained
44 (could be backported to QCOW).
45 - L2 tables have always a size of one cluster.
46*/
47
9b80ddf3
AL
48
49typedef struct {
50 uint32_t magic;
51 uint32_t len;
52} QCowExtension;
7c80ab3f
JS
53#define QCOW2_EXT_MAGIC_END 0
54#define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
9b80ddf3 55
7c80ab3f 56static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
585f8587
FB
57{
58 const QCowHeader *cow_header = (const void *)buf;
3b46e624 59
585f8587
FB
60 if (buf_size >= sizeof(QCowHeader) &&
61 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
5fafdf24 62 be32_to_cpu(cow_header->version) == QCOW_VERSION)
585f8587
FB
63 return 100;
64 else
65 return 0;
66}
67
9b80ddf3
AL
68
69/*
70 * read qcow2 extension and fill bs
71 * start reading from start_offset
72 * finish reading upon magic of value 0 or when end_offset reached
73 * unknown magic is skipped (future extension this version knows nothing about)
74 * return 0 upon success, non-0 otherwise
75 */
7c80ab3f
JS
76static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
77 uint64_t end_offset)
9b80ddf3 78{
9b80ddf3
AL
79 QCowExtension ext;
80 uint64_t offset;
81
82#ifdef DEBUG_EXT
7c80ab3f 83 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
9b80ddf3
AL
84#endif
85 offset = start_offset;
86 while (offset < end_offset) {
87
88#ifdef DEBUG_EXT
89 /* Sanity check */
90 if (offset > s->cluster_size)
7c80ab3f 91 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
9b80ddf3
AL
92
93 printf("attemting to read extended header in offset %lu\n", offset);
94#endif
95
66f82cee 96 if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
7c80ab3f 97 fprintf(stderr, "qcow2_read_extension: ERROR: "
0bfcd599
BS
98 "pread fail from offset %" PRIu64 "\n",
99 offset);
9b80ddf3
AL
100 return 1;
101 }
102 be32_to_cpus(&ext.magic);
103 be32_to_cpus(&ext.len);
104 offset += sizeof(ext);
105#ifdef DEBUG_EXT
106 printf("ext.magic = 0x%x\n", ext.magic);
107#endif
108 switch (ext.magic) {
7c80ab3f 109 case QCOW2_EXT_MAGIC_END:
9b80ddf3 110 return 0;
f965509c 111
7c80ab3f 112 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
f965509c
AL
113 if (ext.len >= sizeof(bs->backing_format)) {
114 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
4c978075 115 " (>=%zu)\n",
f965509c
AL
116 ext.len, sizeof(bs->backing_format));
117 return 2;
118 }
66f82cee 119 if (bdrv_pread(bs->file, offset , bs->backing_format,
f965509c
AL
120 ext.len) != ext.len)
121 return 3;
122 bs->backing_format[ext.len] = '\0';
123#ifdef DEBUG_EXT
124 printf("Qcow2: Got format extension %s\n", bs->backing_format);
125#endif
e1c7f0e3 126 offset = ((offset + ext.len + 7) & ~7);
f965509c
AL
127 break;
128
9b80ddf3
AL
129 default:
130 /* unknown magic -- just skip it */
e1c7f0e3 131 offset = ((offset + ext.len + 7) & ~7);
9b80ddf3
AL
132 break;
133 }
134 }
135
136 return 0;
137}
138
139
7c80ab3f 140static int qcow2_open(BlockDriverState *bs, int flags)
585f8587
FB
141{
142 BDRVQcowState *s = bs->opaque;
6d85a57e 143 int len, i, ret = 0;
585f8587 144 QCowHeader header;
9b80ddf3 145 uint64_t ext_end;
585f8587 146
6d85a57e
JS
147 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
148 if (ret < 0) {
585f8587 149 goto fail;
6d85a57e 150 }
585f8587
FB
151 be32_to_cpus(&header.magic);
152 be32_to_cpus(&header.version);
153 be64_to_cpus(&header.backing_file_offset);
154 be32_to_cpus(&header.backing_file_size);
155 be64_to_cpus(&header.size);
156 be32_to_cpus(&header.cluster_bits);
157 be32_to_cpus(&header.crypt_method);
158 be64_to_cpus(&header.l1_table_offset);
159 be32_to_cpus(&header.l1_size);
160 be64_to_cpus(&header.refcount_table_offset);
161 be32_to_cpus(&header.refcount_table_clusters);
162 be64_to_cpus(&header.snapshots_offset);
163 be32_to_cpus(&header.nb_snapshots);
3b46e624 164
6d85a57e
JS
165 if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION) {
166 ret = -EINVAL;
585f8587 167 goto fail;
6d85a57e 168 }
d191d12d 169 if (header.cluster_bits < MIN_CLUSTER_BITS ||
6d85a57e
JS
170 header.cluster_bits > MAX_CLUSTER_BITS) {
171 ret = -EINVAL;
585f8587 172 goto fail;
6d85a57e
JS
173 }
174 if (header.crypt_method > QCOW_CRYPT_AES) {
175 ret = -EINVAL;
585f8587 176 goto fail;
6d85a57e 177 }
585f8587 178 s->crypt_method_header = header.crypt_method;
6d85a57e 179 if (s->crypt_method_header) {
585f8587 180 bs->encrypted = 1;
6d85a57e 181 }
585f8587
FB
182 s->cluster_bits = header.cluster_bits;
183 s->cluster_size = 1 << s->cluster_bits;
184 s->cluster_sectors = 1 << (s->cluster_bits - 9);
185 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
186 s->l2_size = 1 << s->l2_bits;
187 bs->total_sectors = header.size / 512;
188 s->csize_shift = (62 - (s->cluster_bits - 8));
189 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
190 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
191 s->refcount_table_offset = header.refcount_table_offset;
5fafdf24 192 s->refcount_table_size =
585f8587
FB
193 header.refcount_table_clusters << (s->cluster_bits - 3);
194
195 s->snapshots_offset = header.snapshots_offset;
196 s->nb_snapshots = header.nb_snapshots;
197
198 /* read the level 1 table */
199 s->l1_size = header.l1_size;
419b19d9 200 s->l1_vm_state_index = size_to_l1(s, header.size);
585f8587
FB
201 /* the L1 table must contain at least enough entries to put
202 header.size bytes */
6d85a57e
JS
203 if (s->l1_size < s->l1_vm_state_index) {
204 ret = -EINVAL;
585f8587 205 goto fail;
6d85a57e 206 }
585f8587 207 s->l1_table_offset = header.l1_table_offset;
d191d12d
SW
208 if (s->l1_size > 0) {
209 s->l1_table = qemu_mallocz(
210 align_offset(s->l1_size * sizeof(uint64_t), 512));
6d85a57e
JS
211 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
212 s->l1_size * sizeof(uint64_t));
213 if (ret < 0) {
d191d12d 214 goto fail;
6d85a57e 215 }
d191d12d
SW
216 for(i = 0;i < s->l1_size; i++) {
217 be64_to_cpus(&s->l1_table[i]);
218 }
585f8587
FB
219 }
220 /* alloc L2 cache */
221 s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
585f8587 222 s->cluster_cache = qemu_malloc(s->cluster_size);
585f8587 223 /* one more sector for decompressed data alignment */
095a9c58
AL
224 s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
225 + 512);
585f8587 226 s->cluster_cache_offset = -1;
3b46e624 227
6d85a57e
JS
228 ret = qcow2_refcount_init(bs);
229 if (ret != 0) {
585f8587 230 goto fail;
6d85a57e 231 }
585f8587 232
72cf2d4f 233 QLIST_INIT(&s->cluster_allocs);
f214978a 234
9b80ddf3 235 /* read qcow2 extensions */
6d85a57e 236 if (header.backing_file_offset) {
9b80ddf3 237 ext_end = header.backing_file_offset;
6d85a57e 238 } else {
9b80ddf3 239 ext_end = s->cluster_size;
6d85a57e
JS
240 }
241 if (qcow2_read_extensions(bs, sizeof(header), ext_end)) {
242 ret = -EINVAL;
9b80ddf3 243 goto fail;
6d85a57e 244 }
9b80ddf3 245
585f8587
FB
246 /* read the backing file name */
247 if (header.backing_file_offset != 0) {
248 len = header.backing_file_size;
6d85a57e 249 if (len > 1023) {
585f8587 250 len = 1023;
6d85a57e
JS
251 }
252 ret = bdrv_pread(bs->file, header.backing_file_offset,
253 bs->backing_file, len);
254 if (ret < 0) {
585f8587 255 goto fail;
6d85a57e 256 }
585f8587
FB
257 bs->backing_file[len] = '\0';
258 }
6d85a57e
JS
259 if (qcow2_read_snapshots(bs) < 0) {
260 ret = -EINVAL;
585f8587 261 goto fail;
6d85a57e 262 }
585f8587
FB
263
264#ifdef DEBUG_ALLOC
14899cdf 265 qcow2_check_refcounts(bs);
585f8587 266#endif
6d85a57e 267 return ret;
585f8587
FB
268
269 fail:
ed6ccf0f
KW
270 qcow2_free_snapshots(bs);
271 qcow2_refcount_close(bs);
585f8587
FB
272 qemu_free(s->l1_table);
273 qemu_free(s->l2_cache);
274 qemu_free(s->cluster_cache);
275 qemu_free(s->cluster_data);
6d85a57e 276 return ret;
585f8587
FB
277}
278
7c80ab3f 279static int qcow2_set_key(BlockDriverState *bs, const char *key)
585f8587
FB
280{
281 BDRVQcowState *s = bs->opaque;
282 uint8_t keybuf[16];
283 int len, i;
3b46e624 284
585f8587
FB
285 memset(keybuf, 0, 16);
286 len = strlen(key);
287 if (len > 16)
288 len = 16;
289 /* XXX: we could compress the chars to 7 bits to increase
290 entropy */
291 for(i = 0;i < len;i++) {
292 keybuf[i] = key[i];
293 }
294 s->crypt_method = s->crypt_method_header;
295
296 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
297 return -1;
298 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
299 return -1;
300#if 0
301 /* test */
302 {
303 uint8_t in[16];
304 uint8_t out[16];
305 uint8_t tmp[16];
306 for(i=0;i<16;i++)
307 in[i] = i;
308 AES_encrypt(in, tmp, &s->aes_encrypt_key);
309 AES_decrypt(tmp, out, &s->aes_decrypt_key);
310 for(i = 0; i < 16; i++)
311 printf(" %02x", tmp[i]);
312 printf("\n");
313 for(i = 0; i < 16; i++)
314 printf(" %02x", out[i]);
315 printf("\n");
316 }
317#endif
318 return 0;
319}
320
7c80ab3f
JS
321static int qcow2_is_allocated(BlockDriverState *bs, int64_t sector_num,
322 int nb_sectors, int *pnum)
585f8587 323{
585f8587 324 uint64_t cluster_offset;
1c46efaa 325 int ret;
585f8587 326
095a9c58 327 *pnum = nb_sectors;
1c46efaa
KW
328 /* FIXME We can get errors here, but the bdrv_is_allocated interface can't
329 * pass them on today */
330 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
331 if (ret < 0) {
332 *pnum = 0;
333 }
095a9c58 334
585f8587
FB
335 return (cluster_offset != 0);
336}
337
a9465922 338/* handle reading after the end of the backing file */
bd28f835
KW
339int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
340 int64_t sector_num, int nb_sectors)
a9465922
FB
341{
342 int n1;
343 if ((sector_num + nb_sectors) <= bs->total_sectors)
344 return nb_sectors;
345 if (sector_num >= bs->total_sectors)
346 n1 = 0;
347 else
348 n1 = bs->total_sectors - sector_num;
bd28f835
KW
349
350 qemu_iovec_memset(qiov, 0, 512 * (nb_sectors - n1));
351
a9465922
FB
352 return n1;
353}
354
ce1a14dc
PB
355typedef struct QCowAIOCB {
356 BlockDriverAIOCB common;
585f8587 357 int64_t sector_num;
f141eafe 358 QEMUIOVector *qiov;
7b88e48b
CH
359 int remaining_sectors;
360 int cur_nr_sectors; /* number of sectors in current iteration */
bd28f835 361 uint64_t bytes_done;
585f8587 362 uint64_t cluster_offset;
5fafdf24 363 uint8_t *cluster_data;
585f8587 364 BlockDriverAIOCB *hd_aiocb;
c87c0672 365 QEMUIOVector hd_qiov;
1490791f 366 QEMUBH *bh;
e976c6a1 367 QCowL2Meta l2meta;
72cf2d4f 368 QLIST_ENTRY(QCowAIOCB) next_depend;
585f8587
FB
369} QCowAIOCB;
370
7c80ab3f 371static void qcow2_aio_cancel(BlockDriverAIOCB *blockacb)
c16b5a2c 372{
b666d239 373 QCowAIOCB *acb = container_of(blockacb, QCowAIOCB, common);
c16b5a2c
CH
374 if (acb->hd_aiocb)
375 bdrv_aio_cancel(acb->hd_aiocb);
376 qemu_aio_release(acb);
377}
378
7c80ab3f 379static AIOPool qcow2_aio_pool = {
c16b5a2c 380 .aiocb_size = sizeof(QCowAIOCB),
7c80ab3f 381 .cancel = qcow2_aio_cancel,
c16b5a2c
CH
382};
383
7c80ab3f
JS
384static void qcow2_aio_read_cb(void *opaque, int ret);
385static void qcow2_aio_read_bh(void *opaque)
1490791f
AL
386{
387 QCowAIOCB *acb = opaque;
388 qemu_bh_delete(acb->bh);
389 acb->bh = NULL;
7c80ab3f 390 qcow2_aio_read_cb(opaque, 0);
1490791f
AL
391}
392
7c80ab3f 393static int qcow2_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
a32ef786
AL
394{
395 if (acb->bh)
396 return -EIO;
397
398 acb->bh = qemu_bh_new(cb, acb);
399 if (!acb->bh)
400 return -EIO;
401
402 qemu_bh_schedule(acb->bh);
403
404 return 0;
405}
406
7c80ab3f 407static void qcow2_aio_read_cb(void *opaque, int ret)
585f8587 408{
ce1a14dc
PB
409 QCowAIOCB *acb = opaque;
410 BlockDriverState *bs = acb->common.bs;
585f8587 411 BDRVQcowState *s = bs->opaque;
a9465922 412 int index_in_cluster, n1;
585f8587 413
ce1a14dc 414 acb->hd_aiocb = NULL;
f141eafe
AL
415 if (ret < 0)
416 goto done;
585f8587 417
585f8587 418 /* post process the read buffer */
ce1a14dc 419 if (!acb->cluster_offset) {
585f8587 420 /* nothing to do */
ce1a14dc 421 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
585f8587
FB
422 /* nothing to do */
423 } else {
424 if (s->crypt_method) {
bd28f835
KW
425 qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data,
426 acb->cluster_data, acb->cur_nr_sectors, 0, &s->aes_decrypt_key);
427 qemu_iovec_reset(&acb->hd_qiov);
428 qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,
429 acb->cur_nr_sectors * 512);
430 qemu_iovec_from_buffer(&acb->hd_qiov, acb->cluster_data,
431 512 * acb->cur_nr_sectors);
585f8587
FB
432 }
433 }
434
7b88e48b
CH
435 acb->remaining_sectors -= acb->cur_nr_sectors;
436 acb->sector_num += acb->cur_nr_sectors;
bd28f835 437 acb->bytes_done += acb->cur_nr_sectors * 512;
585f8587 438
7b88e48b 439 if (acb->remaining_sectors == 0) {
585f8587 440 /* request completed */
f141eafe
AL
441 ret = 0;
442 goto done;
585f8587 443 }
3b46e624 444
585f8587 445 /* prepare next AIO request */
7b88e48b 446 acb->cur_nr_sectors = acb->remaining_sectors;
bd28f835
KW
447 if (s->crypt_method) {
448 acb->cur_nr_sectors = MIN(acb->cur_nr_sectors,
449 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
450 }
451
1c46efaa
KW
452 ret = qcow2_get_cluster_offset(bs, acb->sector_num << 9,
453 &acb->cur_nr_sectors, &acb->cluster_offset);
454 if (ret < 0) {
455 goto done;
456 }
457
ce1a14dc 458 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
ce1a14dc 459
bd28f835
KW
460 qemu_iovec_reset(&acb->hd_qiov);
461 qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,
462 acb->cur_nr_sectors * 512);
463
ce1a14dc 464 if (!acb->cluster_offset) {
bd28f835 465
585f8587
FB
466 if (bs->backing_hd) {
467 /* read from the base image */
bd28f835
KW
468 n1 = qcow2_backing_read1(bs->backing_hd, &acb->hd_qiov,
469 acb->sector_num, acb->cur_nr_sectors);
a9465922 470 if (n1 > 0) {
66f82cee 471 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
c87c0672 472 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
7b88e48b 473 &acb->hd_qiov, acb->cur_nr_sectors,
7c80ab3f 474 qcow2_aio_read_cb, acb);
ce1a14dc 475 if (acb->hd_aiocb == NULL)
f141eafe 476 goto done;
a9465922 477 } else {
7c80ab3f 478 ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);
a32ef786 479 if (ret < 0)
f141eafe 480 goto done;
a9465922 481 }
585f8587
FB
482 } else {
483 /* Note: in this case, no need to wait */
bd28f835 484 qemu_iovec_memset(&acb->hd_qiov, 0, 512 * acb->cur_nr_sectors);
7c80ab3f 485 ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);
a32ef786 486 if (ret < 0)
f141eafe 487 goto done;
585f8587 488 }
ce1a14dc 489 } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
585f8587 490 /* add AIO support for compressed blocks ? */
66f82cee 491 if (qcow2_decompress_cluster(bs, acb->cluster_offset) < 0)
f141eafe 492 goto done;
bd28f835
KW
493
494 qemu_iovec_from_buffer(&acb->hd_qiov,
495 s->cluster_cache + index_in_cluster * 512,
496 512 * acb->cur_nr_sectors);
497
7c80ab3f 498 ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);
a32ef786 499 if (ret < 0)
f141eafe 500 goto done;
585f8587 501 } else {
ce1a14dc 502 if ((acb->cluster_offset & 511) != 0) {
585f8587 503 ret = -EIO;
f141eafe 504 goto done;
585f8587 505 }
c87c0672 506
bd28f835
KW
507 if (s->crypt_method) {
508 /*
509 * For encrypted images, read everything into a temporary
510 * contiguous buffer on which the AES functions can work.
511 */
512 if (!acb->cluster_data) {
513 acb->cluster_data =
514 qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
515 }
516
517 assert(acb->cur_nr_sectors <=
518 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
519 qemu_iovec_reset(&acb->hd_qiov);
520 qemu_iovec_add(&acb->hd_qiov, acb->cluster_data,
521 512 * acb->cur_nr_sectors);
522 }
523
66f82cee
KW
524 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
525 acb->hd_aiocb = bdrv_aio_readv(bs->file,
5fafdf24 526 (acb->cluster_offset >> 9) + index_in_cluster,
7b88e48b 527 &acb->hd_qiov, acb->cur_nr_sectors,
7c80ab3f 528 qcow2_aio_read_cb, acb);
171e3d6b
KW
529 if (acb->hd_aiocb == NULL) {
530 ret = -EIO;
f141eafe 531 goto done;
171e3d6b 532 }
f141eafe
AL
533 }
534
535 return;
536done:
f141eafe 537 acb->common.cb(acb->common.opaque, ret);
bd28f835 538 qemu_iovec_destroy(&acb->hd_qiov);
f141eafe 539 qemu_aio_release(acb);
585f8587
FB
540}
541
7c80ab3f
JS
542static QCowAIOCB *qcow2_aio_setup(BlockDriverState *bs, int64_t sector_num,
543 QEMUIOVector *qiov, int nb_sectors,
544 BlockDriverCompletionFunc *cb,
545 void *opaque, int is_write)
585f8587 546{
ce1a14dc
PB
547 QCowAIOCB *acb;
548
7c80ab3f 549 acb = qemu_aio_get(&qcow2_aio_pool, bs, cb, opaque);
ce1a14dc
PB
550 if (!acb)
551 return NULL;
552 acb->hd_aiocb = NULL;
553 acb->sector_num = sector_num;
f141eafe 554 acb->qiov = qiov;
bd28f835 555
6f5f060b 556 qemu_iovec_init(&acb->hd_qiov, qiov->niov);
bd28f835
KW
557
558 acb->bytes_done = 0;
7b88e48b
CH
559 acb->remaining_sectors = nb_sectors;
560 acb->cur_nr_sectors = 0;
ce1a14dc 561 acb->cluster_offset = 0;
e976c6a1 562 acb->l2meta.nb_clusters = 0;
72cf2d4f 563 QLIST_INIT(&acb->l2meta.dependent_requests);
ce1a14dc
PB
564 return acb;
565}
566
7c80ab3f
JS
567static BlockDriverAIOCB *qcow2_aio_readv(BlockDriverState *bs,
568 int64_t sector_num,
569 QEMUIOVector *qiov, int nb_sectors,
570 BlockDriverCompletionFunc *cb,
571 void *opaque)
ce1a14dc
PB
572{
573 QCowAIOCB *acb;
574
7c80ab3f 575 acb = qcow2_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
ce1a14dc
PB
576 if (!acb)
577 return NULL;
585f8587 578
7c80ab3f 579 qcow2_aio_read_cb(acb, 0);
ce1a14dc 580 return &acb->common;
585f8587
FB
581}
582
7c80ab3f 583static void qcow2_aio_write_cb(void *opaque, int ret);
f214978a
KW
584
585static void run_dependent_requests(QCowL2Meta *m)
586{
587 QCowAIOCB *req;
588 QCowAIOCB *next;
589
590 /* Take the request off the list of running requests */
591 if (m->nb_clusters != 0) {
72cf2d4f 592 QLIST_REMOVE(m, next_in_flight);
f214978a
KW
593 }
594
d4c146f0
SH
595 /* Restart all dependent requests */
596 QLIST_FOREACH_SAFE(req, &m->dependent_requests, next_depend, next) {
7c80ab3f 597 qcow2_aio_write_cb(req, 0);
f214978a
KW
598 }
599
600 /* Empty the list for the next part of the request */
72cf2d4f 601 QLIST_INIT(&m->dependent_requests);
f214978a
KW
602}
603
7c80ab3f 604static void qcow2_aio_write_cb(void *opaque, int ret)
585f8587 605{
ce1a14dc
PB
606 QCowAIOCB *acb = opaque;
607 BlockDriverState *bs = acb->common.bs;
585f8587 608 BDRVQcowState *s = bs->opaque;
585f8587 609 int index_in_cluster;
095a9c58 610 int n_end;
ce1a14dc
PB
611
612 acb->hd_aiocb = NULL;
613
f214978a 614 if (ret >= 0) {
148da7ea 615 ret = qcow2_alloc_cluster_link_l2(bs, &acb->l2meta);
f214978a
KW
616 }
617
618 run_dependent_requests(&acb->l2meta);
619
f141eafe
AL
620 if (ret < 0)
621 goto done;
585f8587 622
7b88e48b
CH
623 acb->remaining_sectors -= acb->cur_nr_sectors;
624 acb->sector_num += acb->cur_nr_sectors;
6f5f060b 625 acb->bytes_done += acb->cur_nr_sectors * 512;
585f8587 626
7b88e48b 627 if (acb->remaining_sectors == 0) {
585f8587 628 /* request completed */
f141eafe
AL
629 ret = 0;
630 goto done;
585f8587 631 }
3b46e624 632
ce1a14dc 633 index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
7b88e48b 634 n_end = index_in_cluster + acb->remaining_sectors;
095a9c58
AL
635 if (s->crypt_method &&
636 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
637 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
638
148da7ea 639 ret = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
7b88e48b 640 index_in_cluster, n_end, &acb->cur_nr_sectors, &acb->l2meta);
148da7ea
KW
641 if (ret < 0) {
642 goto done;
643 }
644
645 acb->cluster_offset = acb->l2meta.cluster_offset;
f214978a
KW
646
647 /* Need to wait for another request? If so, we are done for now. */
148da7ea 648 if (acb->l2meta.nb_clusters == 0 && acb->l2meta.depends_on != NULL) {
72cf2d4f 649 QLIST_INSERT_HEAD(&acb->l2meta.depends_on->dependent_requests,
f214978a
KW
650 acb, next_depend);
651 return;
652 }
653
148da7ea
KW
654 assert((acb->cluster_offset & 511) == 0);
655
6f5f060b
KW
656 qemu_iovec_reset(&acb->hd_qiov);
657 qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,
658 acb->cur_nr_sectors * 512);
659
585f8587 660 if (s->crypt_method) {
ce1a14dc 661 if (!acb->cluster_data) {
095a9c58
AL
662 acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
663 s->cluster_size);
585f8587 664 }
6f5f060b
KW
665
666 assert(acb->hd_qiov.size <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
667 qemu_iovec_to_buffer(&acb->hd_qiov, acb->cluster_data);
668
669 qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data,
670 acb->cluster_data, acb->cur_nr_sectors, 1, &s->aes_encrypt_key);
671
672 qemu_iovec_reset(&acb->hd_qiov);
673 qemu_iovec_add(&acb->hd_qiov, acb->cluster_data,
674 acb->cur_nr_sectors * 512);
585f8587 675 }
6f5f060b 676
66f82cee
KW
677 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
678 acb->hd_aiocb = bdrv_aio_writev(bs->file,
c87c0672 679 (acb->cluster_offset >> 9) + index_in_cluster,
7b88e48b 680 &acb->hd_qiov, acb->cur_nr_sectors,
7c80ab3f 681 qcow2_aio_write_cb, acb);
171e3d6b
KW
682 if (acb->hd_aiocb == NULL) {
683 ret = -EIO;
c644db3d 684 goto fail;
171e3d6b 685 }
f141eafe
AL
686
687 return;
688
c644db3d
KW
689fail:
690 if (acb->l2meta.nb_clusters != 0) {
691 QLIST_REMOVE(&acb->l2meta, next_in_flight);
692 }
f141eafe 693done:
f141eafe 694 acb->common.cb(acb->common.opaque, ret);
6f5f060b 695 qemu_iovec_destroy(&acb->hd_qiov);
f141eafe 696 qemu_aio_release(acb);
585f8587
FB
697}
698
7c80ab3f
JS
699static BlockDriverAIOCB *qcow2_aio_writev(BlockDriverState *bs,
700 int64_t sector_num,
701 QEMUIOVector *qiov, int nb_sectors,
702 BlockDriverCompletionFunc *cb,
703 void *opaque)
585f8587 704{
585f8587 705 BDRVQcowState *s = bs->opaque;
ce1a14dc 706 QCowAIOCB *acb;
3b46e624 707
585f8587
FB
708 s->cluster_cache_offset = -1; /* disable compressed cache */
709
7c80ab3f 710 acb = qcow2_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
ce1a14dc
PB
711 if (!acb)
712 return NULL;
3b46e624 713
7c80ab3f 714 qcow2_aio_write_cb(acb, 0);
ce1a14dc 715 return &acb->common;
585f8587
FB
716}
717
7c80ab3f 718static void qcow2_close(BlockDriverState *bs)
585f8587
FB
719{
720 BDRVQcowState *s = bs->opaque;
721 qemu_free(s->l1_table);
722 qemu_free(s->l2_cache);
723 qemu_free(s->cluster_cache);
724 qemu_free(s->cluster_data);
ed6ccf0f 725 qcow2_refcount_close(bs);
585f8587
FB
726}
727
756e6736
KW
728/*
729 * Updates the variable length parts of the qcow2 header, i.e. the backing file
730 * name and all extensions. qcow2 was not designed to allow such changes, so if
731 * we run out of space (we can only use the first cluster) this function may
732 * fail.
733 *
734 * Returns 0 on success, -errno in error cases.
735 */
736static int qcow2_update_ext_header(BlockDriverState *bs,
737 const char *backing_file, const char *backing_fmt)
738{
739 size_t backing_file_len = 0;
740 size_t backing_fmt_len = 0;
741 BDRVQcowState *s = bs->opaque;
742 QCowExtension ext_backing_fmt = {0, 0};
743 int ret;
744
745 /* Backing file format doesn't make sense without a backing file */
746 if (backing_fmt && !backing_file) {
747 return -EINVAL;
748 }
749
750 /* Prepare the backing file format extension if needed */
751 if (backing_fmt) {
752 ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
7c80ab3f 753 ext_backing_fmt.magic = cpu_to_be32(QCOW2_EXT_MAGIC_BACKING_FORMAT);
756e6736
KW
754 backing_fmt_len = ((sizeof(ext_backing_fmt)
755 + strlen(backing_fmt) + 7) & ~7);
756 }
757
758 /* Check if we can fit the new header into the first cluster */
759 if (backing_file) {
760 backing_file_len = strlen(backing_file);
761 }
762
763 size_t header_size = sizeof(QCowHeader) + backing_file_len
764 + backing_fmt_len;
765
766 if (header_size > s->cluster_size) {
767 return -ENOSPC;
768 }
769
770 /* Rewrite backing file name and qcow2 extensions */
771 size_t ext_size = header_size - sizeof(QCowHeader);
772 uint8_t buf[ext_size];
773 size_t offset = 0;
774 size_t backing_file_offset = 0;
775
776 if (backing_file) {
777 if (backing_fmt) {
778 int padding = backing_fmt_len -
779 (sizeof(ext_backing_fmt) + strlen(backing_fmt));
780
781 memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
782 offset += sizeof(ext_backing_fmt);
783
784 memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
785 offset += strlen(backing_fmt);
786
787 memset(buf + offset, 0, padding);
788 offset += padding;
789 }
790
791 memcpy(buf + offset, backing_file, backing_file_len);
792 backing_file_offset = sizeof(QCowHeader) + offset;
793 }
794
8b3b7206 795 ret = bdrv_pwrite_sync(bs->file, sizeof(QCowHeader), buf, ext_size);
756e6736
KW
796 if (ret < 0) {
797 goto fail;
798 }
799
800 /* Update header fields */
801 uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
802 uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
803
8b3b7206 804 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, backing_file_offset),
756e6736
KW
805 &be_backing_file_offset, sizeof(uint64_t));
806 if (ret < 0) {
807 goto fail;
808 }
809
8b3b7206 810 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, backing_file_size),
756e6736
KW
811 &be_backing_file_size, sizeof(uint32_t));
812 if (ret < 0) {
813 goto fail;
814 }
815
816 ret = 0;
817fail:
818 return ret;
819}
820
821static int qcow2_change_backing_file(BlockDriverState *bs,
822 const char *backing_file, const char *backing_fmt)
823{
824 return qcow2_update_ext_header(bs, backing_file, backing_fmt);
825}
826
a35e1c17
KW
827static int preallocate(BlockDriverState *bs)
828{
a35e1c17
KW
829 uint64_t nb_sectors;
830 uint64_t offset;
831 int num;
148da7ea 832 int ret;
a35e1c17
KW
833 QCowL2Meta meta;
834
835 nb_sectors = bdrv_getlength(bs) >> 9;
836 offset = 0;
72cf2d4f 837 QLIST_INIT(&meta.dependent_requests);
148da7ea 838 meta.cluster_offset = 0;
a35e1c17
KW
839
840 while (nb_sectors) {
841 num = MIN(nb_sectors, INT_MAX >> 9);
148da7ea 842 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
148da7ea 843 if (ret < 0) {
19dbcbf7 844 return ret;
a35e1c17
KW
845 }
846
19dbcbf7
KW
847 ret = qcow2_alloc_cluster_link_l2(bs, &meta);
848 if (ret < 0) {
148da7ea 849 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
19dbcbf7 850 return ret;
a35e1c17
KW
851 }
852
f214978a
KW
853 /* There are no dependent requests, but we need to remove our request
854 * from the list of in-flight requests */
855 run_dependent_requests(&meta);
856
a35e1c17
KW
857 /* TODO Preallocate data if requested */
858
859 nb_sectors -= num;
860 offset += num << 9;
861 }
862
863 /*
864 * It is expected that the image file is large enough to actually contain
865 * all of the allocated clusters (otherwise we get failing reads after
866 * EOF). Extend the image to the last allocated sector.
867 */
148da7ea 868 if (meta.cluster_offset != 0) {
ea80b906
KW
869 uint8_t buf[512];
870 memset(buf, 0, 512);
19dbcbf7
KW
871 ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
872 if (ret < 0) {
873 return ret;
874 }
a35e1c17
KW
875 }
876
877 return 0;
878}
879
7c80ab3f
JS
880static int qcow2_create2(const char *filename, int64_t total_size,
881 const char *backing_file, const char *backing_format,
882 int flags, size_t cluster_size, int prealloc,
883 QEMUOptionParameter *options)
a9420734
KW
884{
885 /* Calulate cluster_bits */
886 int cluster_bits;
887 cluster_bits = ffs(cluster_size) - 1;
888 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
889 (1 << cluster_bits) != cluster_size)
890 {
891 error_report(
892 "Cluster size must be a power of two between %d and %dk\n",
893 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
894 return -EINVAL;
895 }
896
897 /*
898 * Open the image file and write a minimal qcow2 header.
899 *
900 * We keep things simple and start with a zero-sized image. We also
901 * do without refcount blocks or a L1 table for now. We'll fix the
902 * inconsistency later.
903 *
904 * We do need a refcount table because growing the refcount table means
905 * allocating two new refcount blocks - the seconds of which would be at
906 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
907 * size for any qcow2 image.
908 */
909 BlockDriverState* bs;
910 QCowHeader header;
911 uint8_t* refcount_table;
912 int ret;
913
914 ret = bdrv_create_file(filename, options);
915 if (ret < 0) {
916 return ret;
917 }
918
919 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
920 if (ret < 0) {
921 return ret;
922 }
923
924 /* Write the header */
925 memset(&header, 0, sizeof(header));
926 header.magic = cpu_to_be32(QCOW_MAGIC);
927 header.version = cpu_to_be32(QCOW_VERSION);
928 header.cluster_bits = cpu_to_be32(cluster_bits);
929 header.size = cpu_to_be64(0);
930 header.l1_table_offset = cpu_to_be64(0);
931 header.l1_size = cpu_to_be32(0);
932 header.refcount_table_offset = cpu_to_be64(cluster_size);
933 header.refcount_table_clusters = cpu_to_be32(1);
934
935 if (flags & BLOCK_FLAG_ENCRYPT) {
936 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
937 } else {
938 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
939 }
940
941 ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
942 if (ret < 0) {
943 goto out;
944 }
945
946 /* Write an empty refcount table */
947 refcount_table = qemu_mallocz(cluster_size);
948 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
949 qemu_free(refcount_table);
950
951 if (ret < 0) {
952 goto out;
953 }
954
955 bdrv_close(bs);
956
957 /*
958 * And now open the image and make it consistent first (i.e. increase the
959 * refcount of the cluster that is occupied by the header and the refcount
960 * table)
961 */
962 BlockDriver* drv = bdrv_find_format("qcow2");
963 assert(drv != NULL);
964 ret = bdrv_open(bs, filename, BDRV_O_RDWR | BDRV_O_NO_FLUSH, drv);
965 if (ret < 0) {
966 goto out;
967 }
968
969 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
970 if (ret < 0) {
971 goto out;
972
973 } else if (ret != 0) {
974 error_report("Huh, first cluster in empty image is already in use?");
975 abort();
976 }
977
978 /* Okay, now that we have a valid image, let's give it the right size */
979 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
980 if (ret < 0) {
981 goto out;
982 }
983
984 /* Want a backing file? There you go.*/
985 if (backing_file) {
986 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
987 if (ret < 0) {
988 goto out;
989 }
990 }
991
992 /* And if we're supposed to preallocate metadata, do that now */
993 if (prealloc) {
994 ret = preallocate(bs);
995 if (ret < 0) {
996 goto out;
997 }
998 }
999
1000 ret = 0;
1001out:
1002 bdrv_delete(bs);
1003 return ret;
1004}
de5f3f40 1005
7c80ab3f 1006static int qcow2_create(const char *filename, QEMUOptionParameter *options)
de5f3f40
KW
1007{
1008 const char *backing_file = NULL;
1009 const char *backing_fmt = NULL;
1010 uint64_t sectors = 0;
1011 int flags = 0;
1012 size_t cluster_size = 65536;
1013 int prealloc = 0;
1014
1015 /* Read out options */
1016 while (options && options->name) {
1017 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1018 sectors = options->value.n / 512;
1019 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1020 backing_file = options->value.s;
1021 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1022 backing_fmt = options->value.s;
1023 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1024 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1025 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1026 if (options->value.n) {
1027 cluster_size = options->value.n;
1028 }
1029 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1030 if (!options->value.s || !strcmp(options->value.s, "off")) {
1031 prealloc = 0;
1032 } else if (!strcmp(options->value.s, "metadata")) {
1033 prealloc = 1;
1034 } else {
1035 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1036 options->value.s);
1037 return -EINVAL;
1038 }
1039 }
1040 options++;
1041 }
1042
1043 if (backing_file && prealloc) {
1044 fprintf(stderr, "Backing file and preallocation cannot be used at "
1045 "the same time\n");
1046 return -EINVAL;
1047 }
1048
7c80ab3f
JS
1049 return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1050 cluster_size, prealloc, options);
de5f3f40
KW
1051}
1052
7c80ab3f 1053static int qcow2_make_empty(BlockDriverState *bs)
20d97356
BS
1054{
1055#if 0
1056 /* XXX: not correct */
1057 BDRVQcowState *s = bs->opaque;
1058 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1059 int ret;
1060
1061 memset(s->l1_table, 0, l1_length);
66f82cee 1062 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
20d97356 1063 return -1;
66f82cee 1064 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
20d97356
BS
1065 if (ret < 0)
1066 return ret;
1067
1068 l2_cache_reset(bs);
1069#endif
1070 return 0;
1071}
1072
419b19d9
SH
1073static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1074{
1075 BDRVQcowState *s = bs->opaque;
1076 int ret, new_l1_size;
1077
1078 if (offset & 511) {
1079 return -EINVAL;
1080 }
1081
1082 /* cannot proceed if image has snapshots */
1083 if (s->nb_snapshots) {
1084 return -ENOTSUP;
1085 }
1086
1087 /* shrinking is currently not supported */
1088 if (offset < bs->total_sectors * 512) {
1089 return -ENOTSUP;
1090 }
1091
1092 new_l1_size = size_to_l1(s, offset);
72893756 1093 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
419b19d9
SH
1094 if (ret < 0) {
1095 return ret;
1096 }
1097
1098 /* write updated header.size */
1099 offset = cpu_to_be64(offset);
8b3b7206
KW
1100 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1101 &offset, sizeof(uint64_t));
419b19d9
SH
1102 if (ret < 0) {
1103 return ret;
1104 }
1105
1106 s->l1_vm_state_index = new_l1_size;
1107 return 0;
1108}
1109
20d97356
BS
1110/* XXX: put compressed sectors first, then all the cluster aligned
1111 tables to avoid losing bytes in alignment */
7c80ab3f
JS
1112static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1113 const uint8_t *buf, int nb_sectors)
20d97356
BS
1114{
1115 BDRVQcowState *s = bs->opaque;
1116 z_stream strm;
1117 int ret, out_len;
1118 uint8_t *out_buf;
1119 uint64_t cluster_offset;
1120
1121 if (nb_sectors == 0) {
1122 /* align end of file to a sector boundary to ease reading with
1123 sector based I/Os */
66f82cee 1124 cluster_offset = bdrv_getlength(bs->file);
20d97356 1125 cluster_offset = (cluster_offset + 511) & ~511;
66f82cee 1126 bdrv_truncate(bs->file, cluster_offset);
20d97356
BS
1127 return 0;
1128 }
1129
1130 if (nb_sectors != s->cluster_sectors)
1131 return -EINVAL;
1132
1133 out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1134
1135 /* best compression, small window, no zlib header */
1136 memset(&strm, 0, sizeof(strm));
1137 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1138 Z_DEFLATED, -12,
1139 9, Z_DEFAULT_STRATEGY);
1140 if (ret != 0) {
1141 qemu_free(out_buf);
1142 return -1;
1143 }
1144
1145 strm.avail_in = s->cluster_size;
1146 strm.next_in = (uint8_t *)buf;
1147 strm.avail_out = s->cluster_size;
1148 strm.next_out = out_buf;
1149
1150 ret = deflate(&strm, Z_FINISH);
1151 if (ret != Z_STREAM_END && ret != Z_OK) {
1152 qemu_free(out_buf);
1153 deflateEnd(&strm);
1154 return -1;
1155 }
1156 out_len = strm.next_out - out_buf;
1157
1158 deflateEnd(&strm);
1159
1160 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1161 /* could not compress: write normal cluster */
1162 bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1163 } else {
1164 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1165 sector_num << 9, out_len);
1166 if (!cluster_offset)
1167 return -1;
1168 cluster_offset &= s->cluster_offset_mask;
66f82cee
KW
1169 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1170 if (bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len) != out_len) {
20d97356
BS
1171 qemu_free(out_buf);
1172 return -1;
1173 }
1174 }
1175
1176 qemu_free(out_buf);
1177 return 0;
1178}
1179
7c80ab3f 1180static int qcow2_flush(BlockDriverState *bs)
20d97356 1181{
205ef796 1182 return bdrv_flush(bs->file);
20d97356
BS
1183}
1184
7c80ab3f
JS
1185static BlockDriverAIOCB *qcow2_aio_flush(BlockDriverState *bs,
1186 BlockDriverCompletionFunc *cb,
1187 void *opaque)
20d97356 1188{
66f82cee 1189 return bdrv_aio_flush(bs->file, cb, opaque);
20d97356
BS
1190}
1191
7c80ab3f 1192static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
20d97356
BS
1193{
1194 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1195}
1196
7c80ab3f 1197static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356
BS
1198{
1199 BDRVQcowState *s = bs->opaque;
1200 bdi->cluster_size = s->cluster_size;
7c80ab3f 1201 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
1202 return 0;
1203}
1204
1205
7c80ab3f 1206static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result)
20d97356 1207{
9ac228e0 1208 return qcow2_check_refcounts(bs, result);
20d97356
BS
1209}
1210
1211#if 0
1212static void dump_refcounts(BlockDriverState *bs)
1213{
1214 BDRVQcowState *s = bs->opaque;
1215 int64_t nb_clusters, k, k1, size;
1216 int refcount;
1217
66f82cee 1218 size = bdrv_getlength(bs->file);
20d97356
BS
1219 nb_clusters = size_to_clusters(s, size);
1220 for(k = 0; k < nb_clusters;) {
1221 k1 = k;
1222 refcount = get_refcount(bs, k);
1223 k++;
1224 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1225 k++;
0bfcd599
BS
1226 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1227 k - k1);
20d97356
BS
1228 }
1229}
1230#endif
1231
7c80ab3f
JS
1232static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1233 int64_t pos, int size)
20d97356
BS
1234{
1235 BDRVQcowState *s = bs->opaque;
1236 int growable = bs->growable;
1237 int ret;
1238
66f82cee 1239 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
20d97356 1240 bs->growable = 1;
7c80ab3f 1241 ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
20d97356
BS
1242 bs->growable = growable;
1243
1244 return ret;
1245}
1246
7c80ab3f
JS
1247static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1248 int64_t pos, int size)
20d97356
BS
1249{
1250 BDRVQcowState *s = bs->opaque;
1251 int growable = bs->growable;
1252 int ret;
1253
66f82cee 1254 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
20d97356 1255 bs->growable = 1;
7c80ab3f 1256 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
20d97356
BS
1257 bs->growable = growable;
1258
1259 return ret;
1260}
1261
7c80ab3f 1262static QEMUOptionParameter qcow2_create_options[] = {
20d97356
BS
1263 {
1264 .name = BLOCK_OPT_SIZE,
1265 .type = OPT_SIZE,
1266 .help = "Virtual disk size"
1267 },
1268 {
1269 .name = BLOCK_OPT_BACKING_FILE,
1270 .type = OPT_STRING,
1271 .help = "File name of a base image"
1272 },
1273 {
1274 .name = BLOCK_OPT_BACKING_FMT,
1275 .type = OPT_STRING,
1276 .help = "Image format of the base image"
1277 },
1278 {
1279 .name = BLOCK_OPT_ENCRYPT,
1280 .type = OPT_FLAG,
1281 .help = "Encrypt the image"
1282 },
1283 {
1284 .name = BLOCK_OPT_CLUSTER_SIZE,
1285 .type = OPT_SIZE,
1286 .help = "qcow2 cluster size"
1287 },
1288 {
1289 .name = BLOCK_OPT_PREALLOC,
1290 .type = OPT_STRING,
1291 .help = "Preallocation mode (allowed values: off, metadata)"
1292 },
1293 { NULL }
1294};
1295
1296static BlockDriver bdrv_qcow2 = {
7c80ab3f
JS
1297 .format_name = "qcow2",
1298 .instance_size = sizeof(BDRVQcowState),
1299 .bdrv_probe = qcow2_probe,
1300 .bdrv_open = qcow2_open,
1301 .bdrv_close = qcow2_close,
1302 .bdrv_create = qcow2_create,
1303 .bdrv_flush = qcow2_flush,
1304 .bdrv_is_allocated = qcow2_is_allocated,
1305 .bdrv_set_key = qcow2_set_key,
1306 .bdrv_make_empty = qcow2_make_empty,
1307
1308 .bdrv_aio_readv = qcow2_aio_readv,
1309 .bdrv_aio_writev = qcow2_aio_writev,
1310 .bdrv_aio_flush = qcow2_aio_flush,
419b19d9
SH
1311
1312 .bdrv_truncate = qcow2_truncate,
7c80ab3f 1313 .bdrv_write_compressed = qcow2_write_compressed,
20d97356
BS
1314
1315 .bdrv_snapshot_create = qcow2_snapshot_create,
1316 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1317 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1318 .bdrv_snapshot_list = qcow2_snapshot_list,
51ef6727 1319 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
7c80ab3f 1320 .bdrv_get_info = qcow2_get_info,
20d97356 1321
7c80ab3f
JS
1322 .bdrv_save_vmstate = qcow2_save_vmstate,
1323 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356
BS
1324
1325 .bdrv_change_backing_file = qcow2_change_backing_file,
1326
7c80ab3f
JS
1327 .create_options = qcow2_create_options,
1328 .bdrv_check = qcow2_check,
20d97356
BS
1329};
1330
5efa9d5a
AL
1331static void bdrv_qcow2_init(void)
1332{
1333 bdrv_register(&bdrv_qcow2);
1334}
1335
1336block_init(bdrv_qcow2_init);