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