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