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