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