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