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