]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow.c
qemu-img: mandate argument to 'qemu-img check --repair'
[mirror_qemu.git] / block / qcow.c
CommitLineData
ea2384d3
FB
1/*
2 * Block driver for the QCOW format
5fafdf24 3 *
83f64091 4 * Copyright (c) 2004-2006 Fabrice Bellard
5fafdf24 5 *
ea2384d3
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
faf07963 24#include "qemu-common.h"
737e150e 25#include "block/block_int.h"
1de7afc9 26#include "qemu/module.h"
28d34b82 27#include <zlib.h>
753d9b82 28#include "qemu/aes.h"
caf71f86 29#include "migration/migration.h"
ea2384d3
FB
30
31/**************************************************************/
32/* QEMU COW block driver with compression and encryption support */
33
34#define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
35#define QCOW_VERSION 1
36
37#define QCOW_CRYPT_NONE 0
38#define QCOW_CRYPT_AES 1
39
40#define QCOW_OFLAG_COMPRESSED (1LL << 63)
41
42typedef struct QCowHeader {
43 uint32_t magic;
44 uint32_t version;
45 uint64_t backing_file_offset;
46 uint32_t backing_file_size;
47 uint32_t mtime;
48 uint64_t size; /* in bytes */
49 uint8_t cluster_bits;
50 uint8_t l2_bits;
51 uint32_t crypt_method;
52 uint64_t l1_table_offset;
53} QCowHeader;
54
55#define L2_CACHE_SIZE 16
56
57typedef struct BDRVQcowState {
ea2384d3
FB
58 int cluster_bits;
59 int cluster_size;
60 int cluster_sectors;
61 int l2_bits;
62 int l2_size;
63 int l1_size;
64 uint64_t cluster_offset_mask;
65 uint64_t l1_table_offset;
66 uint64_t *l1_table;
67 uint64_t *l2_cache;
68 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
69 uint32_t l2_cache_counts[L2_CACHE_SIZE];
70 uint8_t *cluster_cache;
71 uint8_t *cluster_data;
72 uint64_t cluster_cache_offset;
73 uint32_t crypt_method; /* current crypt method, 0 if no key yet */
74 uint32_t crypt_method_header;
75 AES_KEY aes_encrypt_key;
76 AES_KEY aes_decrypt_key;
52b8eb60 77 CoMutex lock;
fd9f102c 78 Error *migration_blocker;
ea2384d3
FB
79} BDRVQcowState;
80
66f82cee 81static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
ea2384d3
FB
82
83static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
84{
85 const QCowHeader *cow_header = (const void *)buf;
3b46e624 86
712e7874
FB
87 if (buf_size >= sizeof(QCowHeader) &&
88 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
5fafdf24 89 be32_to_cpu(cow_header->version) == QCOW_VERSION)
ea2384d3
FB
90 return 100;
91 else
92 return 0;
93}
94
015a1036
HR
95static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
96 Error **errp)
ea2384d3
FB
97{
98 BDRVQcowState *s = bs->opaque;
84b0ec02 99 int len, i, shift, ret;
ea2384d3 100 QCowHeader header;
83f64091 101
84b0ec02
LZH
102 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
103 if (ret < 0) {
ea2384d3 104 goto fail;
84b0ec02 105 }
ea2384d3
FB
106 be32_to_cpus(&header.magic);
107 be32_to_cpus(&header.version);
108 be64_to_cpus(&header.backing_file_offset);
109 be32_to_cpus(&header.backing_file_size);
110 be32_to_cpus(&header.mtime);
111 be64_to_cpus(&header.size);
112 be32_to_cpus(&header.crypt_method);
113 be64_to_cpus(&header.l1_table_offset);
3b46e624 114
84b0ec02 115 if (header.magic != QCOW_MAGIC) {
76abe407
PB
116 error_setg(errp, "Image not in qcow format");
117 ret = -EINVAL;
84b0ec02
LZH
118 goto fail;
119 }
120 if (header.version != QCOW_VERSION) {
121 char version[64];
122 snprintf(version, sizeof(version), "QCOW version %d", header.version);
b6d5066d
PB
123 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
124 bs->device_name, "qcow", version);
84b0ec02 125 ret = -ENOTSUP;
ea2384d3 126 goto fail;
84b0ec02
LZH
127 }
128
129 if (header.size <= 1 || header.cluster_bits < 9) {
b6d5066d 130 error_setg(errp, "invalid value in qcow header");
84b0ec02 131 ret = -EINVAL;
ea2384d3 132 goto fail;
84b0ec02
LZH
133 }
134 if (header.crypt_method > QCOW_CRYPT_AES) {
b6d5066d 135 error_setg(errp, "invalid encryption method in qcow header");
84b0ec02 136 ret = -EINVAL;
ea2384d3 137 goto fail;
84b0ec02 138 }
ea2384d3 139 s->crypt_method_header = header.crypt_method;
84b0ec02 140 if (s->crypt_method_header) {
ea2384d3 141 bs->encrypted = 1;
84b0ec02 142 }
ea2384d3
FB
143 s->cluster_bits = header.cluster_bits;
144 s->cluster_size = 1 << s->cluster_bits;
145 s->cluster_sectors = 1 << (s->cluster_bits - 9);
146 s->l2_bits = header.l2_bits;
147 s->l2_size = 1 << s->l2_bits;
148 bs->total_sectors = header.size / 512;
149 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
150
151 /* read the level 1 table */
152 shift = s->cluster_bits + s->l2_bits;
153 s->l1_size = (header.size + (1LL << shift) - 1) >> shift;
154
155 s->l1_table_offset = header.l1_table_offset;
7267c094 156 s->l1_table = g_malloc(s->l1_size * sizeof(uint64_t));
84b0ec02
LZH
157
158 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
159 s->l1_size * sizeof(uint64_t));
160 if (ret < 0) {
ea2384d3 161 goto fail;
84b0ec02
LZH
162 }
163
ea2384d3
FB
164 for(i = 0;i < s->l1_size; i++) {
165 be64_to_cpus(&s->l1_table[i]);
166 }
167 /* alloc L2 cache */
7267c094 168 s->l2_cache = g_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
7267c094 169 s->cluster_cache = g_malloc(s->cluster_size);
7267c094 170 s->cluster_data = g_malloc(s->cluster_size);
ea2384d3 171 s->cluster_cache_offset = -1;
3b46e624 172
ea2384d3
FB
173 /* read the backing file name */
174 if (header.backing_file_offset != 0) {
175 len = header.backing_file_size;
84b0ec02 176 if (len > 1023) {
ea2384d3 177 len = 1023;
84b0ec02
LZH
178 }
179 ret = bdrv_pread(bs->file, header.backing_file_offset,
180 bs->backing_file, len);
181 if (ret < 0) {
ea2384d3 182 goto fail;
84b0ec02 183 }
ea2384d3
FB
184 bs->backing_file[len] = '\0';
185 }
de33b1f3 186
fd9f102c
KW
187 /* Disable migration when qcow images are used */
188 error_set(&s->migration_blocker,
189 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
190 "qcow", bs->device_name, "live migration");
191 migrate_add_blocker(s->migration_blocker);
192
de33b1f3 193 qemu_co_mutex_init(&s->lock);
ea2384d3
FB
194 return 0;
195
196 fail:
7267c094
AL
197 g_free(s->l1_table);
198 g_free(s->l2_cache);
199 g_free(s->cluster_cache);
200 g_free(s->cluster_data);
84b0ec02 201 return ret;
ea2384d3
FB
202}
203
d177692e
JC
204
205/* We have nothing to do for QCOW reopen, stubs just return
206 * success */
207static int qcow_reopen_prepare(BDRVReopenState *state,
208 BlockReopenQueue *queue, Error **errp)
209{
210 return 0;
211}
212
ea2384d3
FB
213static int qcow_set_key(BlockDriverState *bs, const char *key)
214{
215 BDRVQcowState *s = bs->opaque;
216 uint8_t keybuf[16];
217 int len, i;
3b46e624 218
ea2384d3
FB
219 memset(keybuf, 0, 16);
220 len = strlen(key);
221 if (len > 16)
222 len = 16;
223 /* XXX: we could compress the chars to 7 bits to increase
224 entropy */
225 for(i = 0;i < len;i++) {
226 keybuf[i] = key[i];
227 }
228 s->crypt_method = s->crypt_method_header;
229
230 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
231 return -1;
232 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
233 return -1;
ea2384d3
FB
234 return 0;
235}
236
237/* The crypt function is compatible with the linux cryptoloop
238 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
239 supported */
240static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
241 uint8_t *out_buf, const uint8_t *in_buf,
242 int nb_sectors, int enc,
243 const AES_KEY *key)
244{
245 union {
246 uint64_t ll[2];
247 uint8_t b[16];
248 } ivec;
249 int i;
250
251 for(i = 0; i < nb_sectors; i++) {
252 ivec.ll[0] = cpu_to_le64(sector_num);
253 ivec.ll[1] = 0;
5fafdf24 254 AES_cbc_encrypt(in_buf, out_buf, 512, key,
ea2384d3
FB
255 ivec.b, enc);
256 sector_num++;
257 in_buf += 512;
258 out_buf += 512;
259 }
260}
261
262/* 'allocate' is:
263 *
264 * 0 to not allocate.
265 *
266 * 1 to allocate a normal cluster (for sector indexes 'n_start' to
267 * 'n_end')
268 *
269 * 2 to allocate a compressed cluster of size
270 * 'compressed_size'. 'compressed_size' must be > 0 and <
5fafdf24 271 * cluster_size
ea2384d3
FB
272 *
273 * return 0 if not allocated.
274 */
275static uint64_t get_cluster_offset(BlockDriverState *bs,
276 uint64_t offset, int allocate,
277 int compressed_size,
278 int n_start, int n_end)
279{
280 BDRVQcowState *s = bs->opaque;
281 int min_index, i, j, l1_index, l2_index;
282 uint64_t l2_offset, *l2_table, cluster_offset, tmp;
283 uint32_t min_count;
284 int new_l2_table;
3b46e624 285
ea2384d3
FB
286 l1_index = offset >> (s->l2_bits + s->cluster_bits);
287 l2_offset = s->l1_table[l1_index];
288 new_l2_table = 0;
289 if (!l2_offset) {
290 if (!allocate)
291 return 0;
292 /* allocate a new l2 entry */
66f82cee 293 l2_offset = bdrv_getlength(bs->file);
ea2384d3
FB
294 /* round to cluster size */
295 l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
296 /* update the L1 entry */
297 s->l1_table[l1_index] = l2_offset;
298 tmp = cpu_to_be64(l2_offset);
5e5557d9
KW
299 if (bdrv_pwrite_sync(bs->file,
300 s->l1_table_offset + l1_index * sizeof(tmp),
301 &tmp, sizeof(tmp)) < 0)
ea2384d3
FB
302 return 0;
303 new_l2_table = 1;
304 }
305 for(i = 0; i < L2_CACHE_SIZE; i++) {
306 if (l2_offset == s->l2_cache_offsets[i]) {
307 /* increment the hit count */
308 if (++s->l2_cache_counts[i] == 0xffffffff) {
309 for(j = 0; j < L2_CACHE_SIZE; j++) {
310 s->l2_cache_counts[j] >>= 1;
311 }
312 }
313 l2_table = s->l2_cache + (i << s->l2_bits);
314 goto found;
315 }
316 }
317 /* not found: load a new entry in the least used one */
318 min_index = 0;
319 min_count = 0xffffffff;
320 for(i = 0; i < L2_CACHE_SIZE; i++) {
321 if (s->l2_cache_counts[i] < min_count) {
322 min_count = s->l2_cache_counts[i];
323 min_index = i;
324 }
325 }
326 l2_table = s->l2_cache + (min_index << s->l2_bits);
ea2384d3
FB
327 if (new_l2_table) {
328 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
5e5557d9
KW
329 if (bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
330 s->l2_size * sizeof(uint64_t)) < 0)
ea2384d3
FB
331 return 0;
332 } else {
66f82cee 333 if (bdrv_pread(bs->file, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=
ea2384d3
FB
334 s->l2_size * sizeof(uint64_t))
335 return 0;
336 }
337 s->l2_cache_offsets[min_index] = l2_offset;
338 s->l2_cache_counts[min_index] = 1;
339 found:
340 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
341 cluster_offset = be64_to_cpu(l2_table[l2_index]);
5fafdf24 342 if (!cluster_offset ||
ea2384d3
FB
343 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
344 if (!allocate)
345 return 0;
346 /* allocate a new cluster */
347 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
348 (n_end - n_start) < s->cluster_sectors) {
349 /* if the cluster is already compressed, we must
350 decompress it in the case it is not completely
351 overwritten */
66f82cee 352 if (decompress_cluster(bs, cluster_offset) < 0)
ea2384d3 353 return 0;
66f82cee 354 cluster_offset = bdrv_getlength(bs->file);
5fafdf24 355 cluster_offset = (cluster_offset + s->cluster_size - 1) &
ea2384d3
FB
356 ~(s->cluster_size - 1);
357 /* write the cluster content */
66f82cee 358 if (bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache, s->cluster_size) !=
ea2384d3
FB
359 s->cluster_size)
360 return -1;
361 } else {
66f82cee 362 cluster_offset = bdrv_getlength(bs->file);
7f48fa1f
AL
363 if (allocate == 1) {
364 /* round to cluster size */
365 cluster_offset = (cluster_offset + s->cluster_size - 1) &
366 ~(s->cluster_size - 1);
66f82cee 367 bdrv_truncate(bs->file, cluster_offset + s->cluster_size);
7f48fa1f
AL
368 /* if encrypted, we must initialize the cluster
369 content which won't be written */
370 if (s->crypt_method &&
371 (n_end - n_start) < s->cluster_sectors) {
372 uint64_t start_sect;
373 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
374 memset(s->cluster_data + 512, 0x00, 512);
375 for(i = 0; i < s->cluster_sectors; i++) {
376 if (i < n_start || i >= n_end) {
377 encrypt_sectors(s, start_sect + i,
378 s->cluster_data,
379 s->cluster_data + 512, 1, 1,
380 &s->aes_encrypt_key);
66f82cee 381 if (bdrv_pwrite(bs->file, cluster_offset + i * 512,
7f48fa1f
AL
382 s->cluster_data, 512) != 512)
383 return -1;
384 }
ea2384d3
FB
385 }
386 }
7f48fa1f
AL
387 } else if (allocate == 2) {
388 cluster_offset |= QCOW_OFLAG_COMPRESSED |
389 (uint64_t)compressed_size << (63 - s->cluster_bits);
ea2384d3
FB
390 }
391 }
392 /* update L2 table */
393 tmp = cpu_to_be64(cluster_offset);
394 l2_table[l2_index] = tmp;
5e5557d9
KW
395 if (bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
396 &tmp, sizeof(tmp)) < 0)
ea2384d3
FB
397 return 0;
398 }
399 return cluster_offset;
400}
401
b6b8a333 402static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
f8a2e5e3 403 int64_t sector_num, int nb_sectors, int *pnum)
ea2384d3
FB
404{
405 BDRVQcowState *s = bs->opaque;
406 int index_in_cluster, n;
407 uint64_t cluster_offset;
408
f8a2e5e3 409 qemu_co_mutex_lock(&s->lock);
ea2384d3 410 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
f8a2e5e3 411 qemu_co_mutex_unlock(&s->lock);
ea2384d3
FB
412 index_in_cluster = sector_num & (s->cluster_sectors - 1);
413 n = s->cluster_sectors - index_in_cluster;
414 if (n > nb_sectors)
415 n = nb_sectors;
416 *pnum = n;
4bc74be9
PB
417 if (!cluster_offset) {
418 return 0;
419 }
420 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypt_method) {
421 return BDRV_BLOCK_DATA;
422 }
423 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
424 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
ea2384d3
FB
425}
426
427static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
428 const uint8_t *buf, int buf_size)
429{
430 z_stream strm1, *strm = &strm1;
431 int ret, out_len;
432
433 memset(strm, 0, sizeof(*strm));
434
435 strm->next_in = (uint8_t *)buf;
436 strm->avail_in = buf_size;
437 strm->next_out = out_buf;
438 strm->avail_out = out_buf_size;
439
440 ret = inflateInit2(strm, -12);
441 if (ret != Z_OK)
442 return -1;
443 ret = inflate(strm, Z_FINISH);
444 out_len = strm->next_out - out_buf;
445 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
446 out_len != out_buf_size) {
447 inflateEnd(strm);
448 return -1;
449 }
450 inflateEnd(strm);
451 return 0;
452}
3b46e624 453
66f82cee 454static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
ea2384d3 455{
66f82cee 456 BDRVQcowState *s = bs->opaque;
ea2384d3
FB
457 int ret, csize;
458 uint64_t coffset;
459
460 coffset = cluster_offset & s->cluster_offset_mask;
461 if (s->cluster_cache_offset != coffset) {
462 csize = cluster_offset >> (63 - s->cluster_bits);
463 csize &= (s->cluster_size - 1);
66f82cee 464 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
5fafdf24 465 if (ret != csize)
ea2384d3
FB
466 return -1;
467 if (decompress_buffer(s->cluster_cache, s->cluster_size,
468 s->cluster_data, csize) < 0) {
469 return -1;
470 }
471 s->cluster_cache_offset = coffset;
472 }
473 return 0;
474}
475
a968168c 476static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
27deebe8 477 int nb_sectors, QEMUIOVector *qiov)
83f64091 478{
83f64091 479 BDRVQcowState *s = bs->opaque;
83f64091 480 int index_in_cluster;
27deebe8 481 int ret = 0, n;
43ca85b5 482 uint64_t cluster_offset;
430bbaaa
FZ
483 struct iovec hd_iov;
484 QEMUIOVector hd_qiov;
27deebe8
FZ
485 uint8_t *buf;
486 void *orig_buf;
83f64091 487
27deebe8
FZ
488 if (qiov->niov > 1) {
489 buf = orig_buf = qemu_blockalign(bs, qiov->size);
490 } else {
491 orig_buf = NULL;
492 buf = (uint8_t *)qiov->iov->iov_base;
83f64091 493 }
3b46e624 494
27deebe8
FZ
495 qemu_co_mutex_lock(&s->lock);
496
497 while (nb_sectors != 0) {
498 /* prepare next request */
499 cluster_offset = get_cluster_offset(bs, sector_num << 9,
500 0, 0, 0, 0);
501 index_in_cluster = sector_num & (s->cluster_sectors - 1);
502 n = s->cluster_sectors - index_in_cluster;
503 if (n > nb_sectors) {
504 n = nb_sectors;
505 }
ce1a14dc 506
27deebe8
FZ
507 if (!cluster_offset) {
508 if (bs->backing_hd) {
509 /* read from the base image */
510 hd_iov.iov_base = (void *)buf;
511 hd_iov.iov_len = n * 512;
512 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
513 qemu_co_mutex_unlock(&s->lock);
514 ret = bdrv_co_readv(bs->backing_hd, sector_num,
515 n, &hd_qiov);
516 qemu_co_mutex_lock(&s->lock);
517 if (ret < 0) {
518 goto fail;
519 }
520 } else {
521 /* Note: in this case, no need to wait */
522 memset(buf, 0, 512 * n);
523 }
524 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
525 /* add AIO support for compressed blocks ? */
526 if (decompress_cluster(bs, cluster_offset) < 0) {
527 goto fail;
528 }
529 memcpy(buf,
530 s->cluster_cache + index_in_cluster * 512, 512 * n);
531 } else {
532 if ((cluster_offset & 511) != 0) {
533 goto fail;
534 }
535 hd_iov.iov_base = (void *)buf;
430bbaaa
FZ
536 hd_iov.iov_len = n * 512;
537 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
52b8eb60 538 qemu_co_mutex_unlock(&s->lock);
27deebe8
FZ
539 ret = bdrv_co_readv(bs->file,
540 (cluster_offset >> 9) + index_in_cluster,
430bbaaa 541 n, &hd_qiov);
52b8eb60
KW
542 qemu_co_mutex_lock(&s->lock);
543 if (ret < 0) {
27deebe8
FZ
544 break;
545 }
546 if (s->crypt_method) {
547 encrypt_sectors(s, sector_num, buf, buf,
548 n, 0,
549 &s->aes_decrypt_key);
5614c188 550 }
5614c188 551 }
27deebe8 552 ret = 0;
f141eafe 553
27deebe8
FZ
554 nb_sectors -= n;
555 sector_num += n;
556 buf += n * 512;
43ca85b5
FZ
557 }
558
27deebe8 559done:
52b8eb60
KW
560 qemu_co_mutex_unlock(&s->lock);
561
27deebe8 562 if (qiov->niov > 1) {
03396148 563 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
27deebe8 564 qemu_vfree(orig_buf);
b11a24de
KW
565 }
566
52b8eb60 567 return ret;
27deebe8
FZ
568
569fail:
570 ret = -EIO;
571 goto done;
83f64091
FB
572}
573
a968168c 574static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
27deebe8 575 int nb_sectors, QEMUIOVector *qiov)
83f64091 576{
83f64091 577 BDRVQcowState *s = bs->opaque;
83f64091
FB
578 int index_in_cluster;
579 uint64_t cluster_offset;
580 const uint8_t *src_buf;
27deebe8 581 int ret = 0, n;
430bbaaa
FZ
582 uint8_t *cluster_data = NULL;
583 struct iovec hd_iov;
584 QEMUIOVector hd_qiov;
27deebe8
FZ
585 uint8_t *buf;
586 void *orig_buf;
ce1a14dc 587
27deebe8 588 s->cluster_cache_offset = -1; /* disable compressed cache */
3b46e624 589
27deebe8
FZ
590 if (qiov->niov > 1) {
591 buf = orig_buf = qemu_blockalign(bs, qiov->size);
d5e6b161 592 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
83f64091 593 } else {
27deebe8
FZ
594 orig_buf = NULL;
595 buf = (uint8_t *)qiov->iov->iov_base;
83f64091 596 }
c87c0672 597
52b8eb60 598 qemu_co_mutex_lock(&s->lock);
43ca85b5 599
27deebe8 600 while (nb_sectors != 0) {
83f64091 601
27deebe8
FZ
602 index_in_cluster = sector_num & (s->cluster_sectors - 1);
603 n = s->cluster_sectors - index_in_cluster;
604 if (n > nb_sectors) {
605 n = nb_sectors;
606 }
607 cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
608 index_in_cluster,
609 index_in_cluster + n);
610 if (!cluster_offset || (cluster_offset & 511) != 0) {
611 ret = -EIO;
612 break;
613 }
614 if (s->crypt_method) {
615 if (!cluster_data) {
616 cluster_data = g_malloc0(s->cluster_size);
617 }
618 encrypt_sectors(s, sector_num, cluster_data, buf,
619 n, 1, &s->aes_encrypt_key);
620 src_buf = cluster_data;
621 } else {
622 src_buf = buf;
623 }
83f64091 624
27deebe8
FZ
625 hd_iov.iov_base = (void *)src_buf;
626 hd_iov.iov_len = n * 512;
627 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
628 qemu_co_mutex_unlock(&s->lock);
629 ret = bdrv_co_writev(bs->file,
630 (cluster_offset >> 9) + index_in_cluster,
631 n, &hd_qiov);
632 qemu_co_mutex_lock(&s->lock);
633 if (ret < 0) {
634 break;
635 }
636 ret = 0;
ad53089b 637
27deebe8
FZ
638 nb_sectors -= n;
639 sector_num += n;
640 buf += n * 512;
641 }
52b8eb60 642 qemu_co_mutex_unlock(&s->lock);
3b46e624 643
27deebe8
FZ
644 if (qiov->niov > 1) {
645 qemu_vfree(orig_buf);
b11a24de 646 }
add8d262 647 g_free(cluster_data);
b11a24de 648
52b8eb60 649 return ret;
83f64091
FB
650}
651
e2731add 652static void qcow_close(BlockDriverState *bs)
ea2384d3
FB
653{
654 BDRVQcowState *s = bs->opaque;
fd9f102c 655
7267c094
AL
656 g_free(s->l1_table);
657 g_free(s->l2_cache);
658 g_free(s->cluster_cache);
659 g_free(s->cluster_data);
fd9f102c
KW
660
661 migrate_del_blocker(s->migration_blocker);
662 error_free(s->migration_blocker);
ea2384d3
FB
663}
664
d5124c00
HR
665static int qcow_create(const char *filename, QEMUOptionParameter *options,
666 Error **errp)
ea2384d3 667{
2b16c9ff 668 int header_size, backing_filename_len, l1_size, shift, i;
ea2384d3 669 QCowHeader header;
2b16c9ff 670 uint8_t *tmp;
0e7e1989
KW
671 int64_t total_size = 0;
672 const char *backing_file = NULL;
673 int flags = 0;
34b5d2c6 674 Error *local_err = NULL;
3e1a8134 675 int ret;
2b16c9ff 676 BlockDriverState *qcow_bs;
0e7e1989
KW
677
678 /* Read out options */
679 while (options && options->name) {
680 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
681 total_size = options->value.n / 512;
682 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
683 backing_file = options->value.s;
684 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
685 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
686 }
687 options++;
688 }
ea2384d3 689
cc84d90f 690 ret = bdrv_create_file(filename, options, &local_err);
2b16c9ff 691 if (ret < 0) {
b6d5066d 692 error_propagate(errp, local_err);
2b16c9ff
LZH
693 return ret;
694 }
695
2e40134b
HR
696 qcow_bs = NULL;
697 ret = bdrv_open(&qcow_bs, filename, NULL, NULL,
698 BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);
2b16c9ff 699 if (ret < 0) {
b6d5066d 700 error_propagate(errp, local_err);
2b16c9ff
LZH
701 return ret;
702 }
703
704 ret = bdrv_truncate(qcow_bs, 0);
705 if (ret < 0) {
706 goto exit;
707 }
708
ea2384d3
FB
709 memset(&header, 0, sizeof(header));
710 header.magic = cpu_to_be32(QCOW_MAGIC);
711 header.version = cpu_to_be32(QCOW_VERSION);
712 header.size = cpu_to_be64(total_size * 512);
713 header_size = sizeof(header);
714 backing_filename_len = 0;
715 if (backing_file) {
7852e5da
AJ
716 if (strcmp(backing_file, "fat:")) {
717 header.backing_file_offset = cpu_to_be64(header_size);
718 backing_filename_len = strlen(backing_file);
719 header.backing_file_size = cpu_to_be32(backing_filename_len);
720 header_size += backing_filename_len;
721 } else {
722 /* special backing file for vvfat */
723 backing_file = NULL;
724 }
ea2384d3
FB
725 header.cluster_bits = 9; /* 512 byte cluster to avoid copying
726 unmodifyed sectors */
727 header.l2_bits = 12; /* 32 KB L2 tables */
728 } else {
729 header.cluster_bits = 12; /* 4 KB clusters */
730 header.l2_bits = 9; /* 4 KB L2 tables */
731 }
732 header_size = (header_size + 7) & ~7;
733 shift = header.cluster_bits + header.l2_bits;
734 l1_size = ((total_size * 512) + (1LL << shift) - 1) >> shift;
735
736 header.l1_table_offset = cpu_to_be64(header_size);
ec36ba14 737 if (flags & BLOCK_FLAG_ENCRYPT) {
ea2384d3
FB
738 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
739 } else {
740 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
741 }
3b46e624 742
ea2384d3 743 /* write all the data */
2b16c9ff 744 ret = bdrv_pwrite(qcow_bs, 0, &header, sizeof(header));
3e1a8134 745 if (ret != sizeof(header)) {
3e1a8134
KS
746 goto exit;
747 }
748
ea2384d3 749 if (backing_file) {
2b16c9ff
LZH
750 ret = bdrv_pwrite(qcow_bs, sizeof(header),
751 backing_file, backing_filename_len);
3e1a8134 752 if (ret != backing_filename_len) {
3e1a8134
KS
753 goto exit;
754 }
ea2384d3 755 }
2b16c9ff
LZH
756
757 tmp = g_malloc0(BDRV_SECTOR_SIZE);
758 for (i = 0; i < ((sizeof(uint64_t)*l1_size + BDRV_SECTOR_SIZE - 1)/
759 BDRV_SECTOR_SIZE); i++) {
760 ret = bdrv_pwrite(qcow_bs, header_size +
761 BDRV_SECTOR_SIZE*i, tmp, BDRV_SECTOR_SIZE);
762 if (ret != BDRV_SECTOR_SIZE) {
763 g_free(tmp);
3e1a8134
KS
764 goto exit;
765 }
ea2384d3 766 }
3e1a8134 767
2b16c9ff 768 g_free(tmp);
3e1a8134
KS
769 ret = 0;
770exit:
4f6fd349 771 bdrv_unref(qcow_bs);
3e1a8134 772 return ret;
ea2384d3
FB
773}
774
c47c33b0 775static int qcow_make_empty(BlockDriverState *bs)
95389c86
FB
776{
777 BDRVQcowState *s = bs->opaque;
778 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
83f64091 779 int ret;
95389c86
FB
780
781 memset(s->l1_table, 0, l1_length);
5e5557d9
KW
782 if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
783 l1_length) < 0)
784 return -1;
66f82cee 785 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
83f64091
FB
786 if (ret < 0)
787 return ret;
95389c86
FB
788
789 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
790 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
791 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
792
793 return 0;
794}
795
ea2384d3
FB
796/* XXX: put compressed sectors first, then all the cluster aligned
797 tables to avoid losing bytes in alignment */
5fafdf24 798static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
c47c33b0 799 const uint8_t *buf, int nb_sectors)
ea2384d3
FB
800{
801 BDRVQcowState *s = bs->opaque;
802 z_stream strm;
803 int ret, out_len;
804 uint8_t *out_buf;
805 uint64_t cluster_offset;
806
16b3c5cd
SH
807 if (nb_sectors != s->cluster_sectors) {
808 ret = -EINVAL;
809
810 /* Zero-pad last write if image size is not cluster aligned */
811 if (sector_num + nb_sectors == bs->total_sectors &&
812 nb_sectors < s->cluster_sectors) {
813 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
814 memset(pad_buf, 0, s->cluster_size);
815 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
816 ret = qcow_write_compressed(bs, sector_num,
817 pad_buf, s->cluster_sectors);
818 qemu_vfree(pad_buf);
819 }
820 return ret;
821 }
ea2384d3 822
7267c094 823 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
ea2384d3
FB
824
825 /* best compression, small window, no zlib header */
826 memset(&strm, 0, sizeof(strm));
827 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
5fafdf24 828 Z_DEFLATED, -12,
ea2384d3
FB
829 9, Z_DEFAULT_STRATEGY);
830 if (ret != 0) {
64ebe71a
KW
831 ret = -EINVAL;
832 goto fail;
ea2384d3
FB
833 }
834
835 strm.avail_in = s->cluster_size;
836 strm.next_in = (uint8_t *)buf;
837 strm.avail_out = s->cluster_size;
838 strm.next_out = out_buf;
839
840 ret = deflate(&strm, Z_FINISH);
841 if (ret != Z_STREAM_END && ret != Z_OK) {
ea2384d3 842 deflateEnd(&strm);
64ebe71a
KW
843 ret = -EINVAL;
844 goto fail;
ea2384d3
FB
845 }
846 out_len = strm.next_out - out_buf;
847
848 deflateEnd(&strm);
849
850 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
851 /* could not compress: write normal cluster */
64ebe71a
KW
852 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
853 if (ret < 0) {
854 goto fail;
855 }
ea2384d3 856 } else {
5fafdf24 857 cluster_offset = get_cluster_offset(bs, sector_num << 9, 2,
ea2384d3 858 out_len, 0, 0);
64ebe71a
KW
859 if (cluster_offset == 0) {
860 ret = -EIO;
861 goto fail;
862 }
863
ea2384d3 864 cluster_offset &= s->cluster_offset_mask;
64ebe71a
KW
865 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
866 if (ret < 0) {
867 goto fail;
ea2384d3
FB
868 }
869 }
3b46e624 870
64ebe71a
KW
871 ret = 0;
872fail:
7267c094 873 g_free(out_buf);
64ebe71a 874 return ret;
ea2384d3
FB
875}
876
c47c33b0
FB
877static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
878{
879 BDRVQcowState *s = bs->opaque;
880 bdi->cluster_size = s->cluster_size;
881 return 0;
882}
883
0e7e1989
KW
884
885static QEMUOptionParameter qcow_create_options[] = {
db08adf5
KW
886 {
887 .name = BLOCK_OPT_SIZE,
888 .type = OPT_SIZE,
889 .help = "Virtual disk size"
890 },
891 {
892 .name = BLOCK_OPT_BACKING_FILE,
893 .type = OPT_STRING,
894 .help = "File name of a base image"
895 },
896 {
897 .name = BLOCK_OPT_ENCRYPT,
898 .type = OPT_FLAG,
899 .help = "Encrypt the image"
900 },
0e7e1989
KW
901 { NULL }
902};
903
5efa9d5a 904static BlockDriver bdrv_qcow = {
e60f469c
AJ
905 .format_name = "qcow",
906 .instance_size = sizeof(BDRVQcowState),
907 .bdrv_probe = qcow_probe,
908 .bdrv_open = qcow_open,
909 .bdrv_close = qcow_close,
d177692e 910 .bdrv_reopen_prepare = qcow_reopen_prepare,
e60f469c 911 .bdrv_create = qcow_create,
3ac21627 912 .bdrv_has_zero_init = bdrv_has_zero_init_1,
c68b89ac
KW
913
914 .bdrv_co_readv = qcow_co_readv,
915 .bdrv_co_writev = qcow_co_writev,
b6b8a333 916 .bdrv_co_get_block_status = qcow_co_get_block_status,
c68b89ac
KW
917
918 .bdrv_set_key = qcow_set_key,
919 .bdrv_make_empty = qcow_make_empty,
920 .bdrv_write_compressed = qcow_write_compressed,
921 .bdrv_get_info = qcow_get_info,
0e7e1989
KW
922
923 .create_options = qcow_create_options,
ea2384d3 924};
5efa9d5a
AL
925
926static void bdrv_qcow_init(void)
927{
928 bdrv_register(&bdrv_qcow);
929}
930
931block_init(bdrv_qcow_init);