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