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