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