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