1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24#include "qemu/osdep.h"
25#include "qapi/error.h"
26#include "qemu-common.h"
27#include "qemu/error-report.h"
28#include "block/block_int.h"
29#include "sysemu/block-backend.h"
30#include "qemu/module.h"
31#include "qemu/bswap.h"
32#include <zlib.h>
33#include "qapi/qmp/qerror.h"
34#include "qapi/qmp/qstring.h"
35#include "crypto/block.h"
36#include "migration/blocker.h"
37#include "block/crypto.h"
38
39
40
41
42#define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
43#define QCOW_VERSION 1
44
45#define QCOW_CRYPT_NONE 0
46#define QCOW_CRYPT_AES 1
47
48#define QCOW_OFLAG_COMPRESSED (1LL << 63)
49
50typedef struct QCowHeader {
51 uint32_t magic;
52 uint32_t version;
53 uint64_t backing_file_offset;
54 uint32_t backing_file_size;
55 uint32_t mtime;
56 uint64_t size;
57 uint8_t cluster_bits;
58 uint8_t l2_bits;
59 uint16_t padding;
60 uint32_t crypt_method;
61 uint64_t l1_table_offset;
62} QEMU_PACKED QCowHeader;
63
64#define L2_CACHE_SIZE 16
65
66typedef struct BDRVQcowState {
67 int cluster_bits;
68 int cluster_size;
69 int cluster_sectors;
70 int l2_bits;
71 int l2_size;
72 unsigned int l1_size;
73 uint64_t cluster_offset_mask;
74 uint64_t l1_table_offset;
75 uint64_t *l1_table;
76 uint64_t *l2_cache;
77 uint64_t l2_cache_offsets[L2_CACHE_SIZE];
78 uint32_t l2_cache_counts[L2_CACHE_SIZE];
79 uint8_t *cluster_cache;
80 uint8_t *cluster_data;
81 uint64_t cluster_cache_offset;
82 QCryptoBlock *crypto;
83 uint32_t crypt_method_header;
84 CoMutex lock;
85 Error *migration_blocker;
86} BDRVQcowState;
87
88static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
89
90static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
91{
92 const QCowHeader *cow_header = (const void *)buf;
93
94 if (buf_size >= sizeof(QCowHeader) &&
95 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
96 be32_to_cpu(cow_header->version) == QCOW_VERSION)
97 return 100;
98 else
99 return 0;
100}
101
102static QemuOptsList qcow_runtime_opts = {
103 .name = "qcow",
104 .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head),
105 .desc = {
106 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
107 { }
108 },
109};
110
111static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
112 Error **errp)
113{
114 BDRVQcowState *s = bs->opaque;
115 unsigned int len, i, shift;
116 int ret;
117 QCowHeader header;
118 Error *local_err = NULL;
119 QCryptoBlockOpenOptions *crypto_opts = NULL;
120 unsigned int cflags = 0;
121 QDict *encryptopts = NULL;
122 const char *encryptfmt;
123
124 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
125 encryptfmt = qdict_get_try_str(encryptopts, "format");
126
127 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
128 false, errp);
129 if (!bs->file) {
130 ret = -EINVAL;
131 goto fail;
132 }
133
134 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
135 if (ret < 0) {
136 goto fail;
137 }
138 be32_to_cpus(&header.magic);
139 be32_to_cpus(&header.version);
140 be64_to_cpus(&header.backing_file_offset);
141 be32_to_cpus(&header.backing_file_size);
142 be32_to_cpus(&header.mtime);
143 be64_to_cpus(&header.size);
144 be32_to_cpus(&header.crypt_method);
145 be64_to_cpus(&header.l1_table_offset);
146
147 if (header.magic != QCOW_MAGIC) {
148 error_setg(errp, "Image not in qcow format");
149 ret = -EINVAL;
150 goto fail;
151 }
152 if (header.version != QCOW_VERSION) {
153 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
154 ret = -ENOTSUP;
155 goto fail;
156 }
157
158 if (header.size <= 1) {
159 error_setg(errp, "Image size is too small (must be at least 2 bytes)");
160 ret = -EINVAL;
161 goto fail;
162 }
163 if (header.cluster_bits < 9 || header.cluster_bits > 16) {
164 error_setg(errp, "Cluster size must be between 512 and 64k");
165 ret = -EINVAL;
166 goto fail;
167 }
168
169
170
171 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
172 error_setg(errp, "L2 table size must be between 512 and 64k");
173 ret = -EINVAL;
174 goto fail;
175 }
176
177 s->crypt_method_header = header.crypt_method;
178 if (s->crypt_method_header) {
179 if (bdrv_uses_whitelist() &&
180 s->crypt_method_header == QCOW_CRYPT_AES) {
181 error_setg(errp,
182 "Use of AES-CBC encrypted qcow images is no longer "
183 "supported in system emulators");
184 error_append_hint(errp,
185 "You can use 'qemu-img convert' to convert your "
186 "image to an alternative supported format, such "
187 "as unencrypted qcow, or raw with the LUKS "
188 "format instead.\n");
189 ret = -ENOSYS;
190 goto fail;
191 }
192 if (s->crypt_method_header == QCOW_CRYPT_AES) {
193 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
194 error_setg(errp,
195 "Header reported 'aes' encryption format but "
196 "options specify '%s'", encryptfmt);
197 ret = -EINVAL;
198 goto fail;
199 }
200 qdict_del(encryptopts, "format");
201 crypto_opts = block_crypto_open_opts_init(
202 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
203 if (!crypto_opts) {
204 ret = -EINVAL;
205 goto fail;
206 }
207
208 if (flags & BDRV_O_NO_IO) {
209 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
210 }
211 s->crypto = qcrypto_block_open(crypto_opts, "encrypt.",
212 NULL, NULL, cflags, errp);
213 if (!s->crypto) {
214 ret = -EINVAL;
215 goto fail;
216 }
217 } else {
218 error_setg(errp, "invalid encryption method in qcow header");
219 ret = -EINVAL;
220 goto fail;
221 }
222 bs->encrypted = true;
223 } else {
224 if (encryptfmt) {
225 error_setg(errp, "No encryption in image header, but options "
226 "specified format '%s'", encryptfmt);
227 ret = -EINVAL;
228 goto fail;
229 }
230 }
231 s->cluster_bits = header.cluster_bits;
232 s->cluster_size = 1 << s->cluster_bits;
233 s->cluster_sectors = 1 << (s->cluster_bits - 9);
234 s->l2_bits = header.l2_bits;
235 s->l2_size = 1 << s->l2_bits;
236 bs->total_sectors = header.size / 512;
237 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
238
239
240 shift = s->cluster_bits + s->l2_bits;
241 if (header.size > UINT64_MAX - (1LL << shift)) {
242 error_setg(errp, "Image too large");
243 ret = -EINVAL;
244 goto fail;
245 } else {
246 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
247 if (l1_size > INT_MAX / sizeof(uint64_t)) {
248 error_setg(errp, "Image too large");
249 ret = -EINVAL;
250 goto fail;
251 }
252 s->l1_size = l1_size;
253 }
254
255 s->l1_table_offset = header.l1_table_offset;
256 s->l1_table = g_try_new(uint64_t, s->l1_size);
257 if (s->l1_table == NULL) {
258 error_setg(errp, "Could not allocate memory for L1 table");
259 ret = -ENOMEM;
260 goto fail;
261 }
262
263 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
264 s->l1_size * sizeof(uint64_t));
265 if (ret < 0) {
266 goto fail;
267 }
268
269 for(i = 0;i < s->l1_size; i++) {
270 be64_to_cpus(&s->l1_table[i]);
271 }
272
273
274 s->l2_cache =
275 qemu_try_blockalign(bs->file->bs,
276 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
277 if (s->l2_cache == NULL) {
278 error_setg(errp, "Could not allocate L2 table cache");
279 ret = -ENOMEM;
280 goto fail;
281 }
282 s->cluster_cache = g_malloc(s->cluster_size);
283 s->cluster_data = g_malloc(s->cluster_size);
284 s->cluster_cache_offset = -1;
285
286
287 if (header.backing_file_offset != 0) {
288 len = header.backing_file_size;
289 if (len > 1023 || len >= sizeof(bs->backing_file)) {
290 error_setg(errp, "Backing file name too long");
291 ret = -EINVAL;
292 goto fail;
293 }
294 ret = bdrv_pread(bs->file, header.backing_file_offset,
295 bs->backing_file, len);
296 if (ret < 0) {
297 goto fail;
298 }
299 bs->backing_file[len] = '\0';
300 }
301
302
303 error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
304 "does not support live migration",
305 bdrv_get_device_or_node_name(bs));
306 ret = migrate_add_blocker(s->migration_blocker, &local_err);
307 if (local_err) {
308 error_propagate(errp, local_err);
309 error_free(s->migration_blocker);
310 goto fail;
311 }
312
313 QDECREF(encryptopts);
314 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
315 qemu_co_mutex_init(&s->lock);
316 return 0;
317
318 fail:
319 g_free(s->l1_table);
320 qemu_vfree(s->l2_cache);
321 g_free(s->cluster_cache);
322 g_free(s->cluster_data);
323 qcrypto_block_free(s->crypto);
324 QDECREF(encryptopts);
325 qapi_free_QCryptoBlockOpenOptions(crypto_opts);
326 return ret;
327}
328
329
330
331
332static int qcow_reopen_prepare(BDRVReopenState *state,
333 BlockReopenQueue *queue, Error **errp)
334{
335 return 0;
336}
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352static uint64_t get_cluster_offset(BlockDriverState *bs,
353 uint64_t offset, int allocate,
354 int compressed_size,
355 int n_start, int n_end)
356{
357 BDRVQcowState *s = bs->opaque;
358 int min_index, i, j, l1_index, l2_index;
359 uint64_t l2_offset, *l2_table, cluster_offset, tmp;
360 uint32_t min_count;
361 int new_l2_table;
362
363 l1_index = offset >> (s->l2_bits + s->cluster_bits);
364 l2_offset = s->l1_table[l1_index];
365 new_l2_table = 0;
366 if (!l2_offset) {
367 if (!allocate)
368 return 0;
369
370 l2_offset = bdrv_getlength(bs->file->bs);
371
372 l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
373
374 s->l1_table[l1_index] = l2_offset;
375 tmp = cpu_to_be64(l2_offset);
376 if (bdrv_pwrite_sync(bs->file,
377 s->l1_table_offset + l1_index * sizeof(tmp),
378 &tmp, sizeof(tmp)) < 0)
379 return 0;
380 new_l2_table = 1;
381 }
382 for(i = 0; i < L2_CACHE_SIZE; i++) {
383 if (l2_offset == s->l2_cache_offsets[i]) {
384
385 if (++s->l2_cache_counts[i] == 0xffffffff) {
386 for(j = 0; j < L2_CACHE_SIZE; j++) {
387 s->l2_cache_counts[j] >>= 1;
388 }
389 }
390 l2_table = s->l2_cache + (i << s->l2_bits);
391 goto found;
392 }
393 }
394
395 min_index = 0;
396 min_count = 0xffffffff;
397 for(i = 0; i < L2_CACHE_SIZE; i++) {
398 if (s->l2_cache_counts[i] < min_count) {
399 min_count = s->l2_cache_counts[i];
400 min_index = i;
401 }
402 }
403 l2_table = s->l2_cache + (min_index << s->l2_bits);
404 if (new_l2_table) {
405 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
406 if (bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
407 s->l2_size * sizeof(uint64_t)) < 0)
408 return 0;
409 } else {
410 if (bdrv_pread(bs->file, l2_offset, l2_table,
411 s->l2_size * sizeof(uint64_t)) !=
412 s->l2_size * sizeof(uint64_t))
413 return 0;
414 }
415 s->l2_cache_offsets[min_index] = l2_offset;
416 s->l2_cache_counts[min_index] = 1;
417 found:
418 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
419 cluster_offset = be64_to_cpu(l2_table[l2_index]);
420 if (!cluster_offset ||
421 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
422 if (!allocate)
423 return 0;
424
425 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
426 (n_end - n_start) < s->cluster_sectors) {
427
428
429
430 if (decompress_cluster(bs, cluster_offset) < 0)
431 return 0;
432 cluster_offset = bdrv_getlength(bs->file->bs);
433 cluster_offset = (cluster_offset + s->cluster_size - 1) &
434 ~(s->cluster_size - 1);
435
436 if (bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
437 s->cluster_size) !=
438 s->cluster_size)
439 return -1;
440 } else {
441 cluster_offset = bdrv_getlength(bs->file->bs);
442 if (allocate == 1) {
443
444 cluster_offset = (cluster_offset + s->cluster_size - 1) &
445 ~(s->cluster_size - 1);
446 bdrv_truncate(bs->file, cluster_offset + s->cluster_size,
447 PREALLOC_MODE_OFF, NULL);
448
449
450 if (bs->encrypted &&
451 (n_end - n_start) < s->cluster_sectors) {
452 uint64_t start_sect;
453 assert(s->crypto);
454 start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
455 for(i = 0; i < s->cluster_sectors; i++) {
456 if (i < n_start || i >= n_end) {
457 Error *err = NULL;
458 memset(s->cluster_data, 0x00, 512);
459 if (qcrypto_block_encrypt(s->crypto, start_sect + i,
460 s->cluster_data,
461 BDRV_SECTOR_SIZE,
462 &err) < 0) {
463 error_free(err);
464 errno = EIO;
465 return -1;
466 }
467 if (bdrv_pwrite(bs->file,
468 cluster_offset + i * 512,
469 s->cluster_data, 512) != 512)
470 return -1;
471 }
472 }
473 }
474 } else if (allocate == 2) {
475 cluster_offset |= QCOW_OFLAG_COMPRESSED |
476 (uint64_t)compressed_size << (63 - s->cluster_bits);
477 }
478 }
479
480 tmp = cpu_to_be64(cluster_offset);
481 l2_table[l2_index] = tmp;
482 if (bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
483 &tmp, sizeof(tmp)) < 0)
484 return 0;
485 }
486 return cluster_offset;
487}
488
489static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
490 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
491{
492 BDRVQcowState *s = bs->opaque;
493 int index_in_cluster, n;
494 uint64_t cluster_offset;
495
496 qemu_co_mutex_lock(&s->lock);
497 cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
498 qemu_co_mutex_unlock(&s->lock);
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;
504 if (!cluster_offset) {
505 return 0;
506 }
507 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) {
508 return BDRV_BLOCK_DATA;
509 }
510 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
511 *file = bs->file->bs;
512 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
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}
541
542static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
543{
544 BDRVQcowState *s = bs->opaque;
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);
552 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
553 if (ret != csize)
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
564static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
565 int nb_sectors, QEMUIOVector *qiov)
566{
567 BDRVQcowState *s = bs->opaque;
568 int index_in_cluster;
569 int ret = 0, n;
570 uint64_t cluster_offset;
571 struct iovec hd_iov;
572 QEMUIOVector hd_qiov;
573 uint8_t *buf;
574 void *orig_buf;
575 Error *err = NULL;
576
577 if (qiov->niov > 1) {
578 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
579 if (buf == NULL) {
580 return -ENOMEM;
581 }
582 } else {
583 orig_buf = NULL;
584 buf = (uint8_t *)qiov->iov->iov_base;
585 }
586
587 qemu_co_mutex_lock(&s->lock);
588
589 while (nb_sectors != 0) {
590
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 }
598
599 if (!cluster_offset) {
600 if (bs->backing) {
601
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);
606 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);
607 qemu_co_mutex_lock(&s->lock);
608 if (ret < 0) {
609 goto fail;
610 }
611 } else {
612
613 memset(buf, 0, 512 * n);
614 }
615 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
616
617 if (decompress_cluster(bs, cluster_offset) < 0) {
618 goto fail;
619 }
620 memcpy(buf,
621 s->cluster_cache + index_in_cluster * 512, 512 * n);
622 } else {
623 if ((cluster_offset & 511) != 0) {
624 goto fail;
625 }
626 hd_iov.iov_base = (void *)buf;
627 hd_iov.iov_len = n * 512;
628 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
629 qemu_co_mutex_unlock(&s->lock);
630 ret = bdrv_co_readv(bs->file,
631 (cluster_offset >> 9) + index_in_cluster,
632 n, &hd_qiov);
633 qemu_co_mutex_lock(&s->lock);
634 if (ret < 0) {
635 break;
636 }
637 if (bs->encrypted) {
638 assert(s->crypto);
639 if (qcrypto_block_decrypt(s->crypto, sector_num, buf,
640 n * BDRV_SECTOR_SIZE, &err) < 0) {
641 goto fail;
642 }
643 }
644 }
645 ret = 0;
646
647 nb_sectors -= n;
648 sector_num += n;
649 buf += n * 512;
650 }
651
652done:
653 qemu_co_mutex_unlock(&s->lock);
654
655 if (qiov->niov > 1) {
656 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
657 qemu_vfree(orig_buf);
658 }
659
660 return ret;
661
662fail:
663 error_free(err);
664 ret = -EIO;
665 goto done;
666}
667
668static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
669 int nb_sectors, QEMUIOVector *qiov)
670{
671 BDRVQcowState *s = bs->opaque;
672 int index_in_cluster;
673 uint64_t cluster_offset;
674 int ret = 0, n;
675 struct iovec hd_iov;
676 QEMUIOVector hd_qiov;
677 uint8_t *buf;
678 void *orig_buf;
679
680 s->cluster_cache_offset = -1;
681
682
683
684 if (bs->encrypted || qiov->niov > 1) {
685 buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
686 if (buf == NULL) {
687 return -ENOMEM;
688 }
689 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
690 } else {
691 orig_buf = NULL;
692 buf = (uint8_t *)qiov->iov->iov_base;
693 }
694
695 qemu_co_mutex_lock(&s->lock);
696
697 while (nb_sectors != 0) {
698
699 index_in_cluster = sector_num & (s->cluster_sectors - 1);
700 n = s->cluster_sectors - index_in_cluster;
701 if (n > nb_sectors) {
702 n = nb_sectors;
703 }
704 cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
705 index_in_cluster,
706 index_in_cluster + n);
707 if (!cluster_offset || (cluster_offset & 511) != 0) {
708 ret = -EIO;
709 break;
710 }
711 if (bs->encrypted) {
712 Error *err = NULL;
713 assert(s->crypto);
714 if (qcrypto_block_encrypt(s->crypto, sector_num, buf,
715 n * BDRV_SECTOR_SIZE, &err) < 0) {
716 error_free(err);
717 ret = -EIO;
718 break;
719 }
720 }
721
722 hd_iov.iov_base = (void *)buf;
723 hd_iov.iov_len = n * 512;
724 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
725 qemu_co_mutex_unlock(&s->lock);
726 ret = bdrv_co_writev(bs->file,
727 (cluster_offset >> 9) + index_in_cluster,
728 n, &hd_qiov);
729 qemu_co_mutex_lock(&s->lock);
730 if (ret < 0) {
731 break;
732 }
733 ret = 0;
734
735 nb_sectors -= n;
736 sector_num += n;
737 buf += n * 512;
738 }
739 qemu_co_mutex_unlock(&s->lock);
740
741 qemu_vfree(orig_buf);
742
743 return ret;
744}
745
746static void qcow_close(BlockDriverState *bs)
747{
748 BDRVQcowState *s = bs->opaque;
749
750 qcrypto_block_free(s->crypto);
751 s->crypto = NULL;
752 g_free(s->l1_table);
753 qemu_vfree(s->l2_cache);
754 g_free(s->cluster_cache);
755 g_free(s->cluster_data);
756
757 migrate_del_blocker(s->migration_blocker);
758 error_free(s->migration_blocker);
759}
760
761static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
762{
763 int header_size, backing_filename_len, l1_size, shift, i;
764 QCowHeader header;
765 uint8_t *tmp;
766 int64_t total_size = 0;
767 char *backing_file = NULL;
768 Error *local_err = NULL;
769 int ret;
770 BlockBackend *qcow_blk;
771 char *encryptfmt = NULL;
772 QDict *options;
773 QDict *encryptopts = NULL;
774 QCryptoBlockCreateOptions *crypto_opts = NULL;
775 QCryptoBlock *crypto = NULL;
776
777
778 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
779 BDRV_SECTOR_SIZE);
780 if (total_size == 0) {
781 error_setg(errp, "Image size is too small, cannot be zero length");
782 ret = -EINVAL;
783 goto cleanup;
784 }
785
786 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
787 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
788 if (encryptfmt) {
789 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
790 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
791 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
792 ret = -EINVAL;
793 goto cleanup;
794 }
795 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
796 encryptfmt = g_strdup("aes");
797 }
798
799 ret = bdrv_create_file(filename, opts, &local_err);
800 if (ret < 0) {
801 error_propagate(errp, local_err);
802 goto cleanup;
803 }
804
805 qcow_blk = blk_new_open(filename, NULL, NULL,
806 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
807 &local_err);
808 if (qcow_blk == NULL) {
809 error_propagate(errp, local_err);
810 ret = -EIO;
811 goto cleanup;
812 }
813
814 blk_set_allow_write_beyond_eof(qcow_blk, true);
815
816 ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp);
817 if (ret < 0) {
818 goto exit;
819 }
820
821 memset(&header, 0, sizeof(header));
822 header.magic = cpu_to_be32(QCOW_MAGIC);
823 header.version = cpu_to_be32(QCOW_VERSION);
824 header.size = cpu_to_be64(total_size);
825 header_size = sizeof(header);
826 backing_filename_len = 0;
827 if (backing_file) {
828 if (strcmp(backing_file, "fat:")) {
829 header.backing_file_offset = cpu_to_be64(header_size);
830 backing_filename_len = strlen(backing_file);
831 header.backing_file_size = cpu_to_be32(backing_filename_len);
832 header_size += backing_filename_len;
833 } else {
834
835 g_free(backing_file);
836 backing_file = NULL;
837 }
838 header.cluster_bits = 9;
839
840 header.l2_bits = 12;
841 } else {
842 header.cluster_bits = 12;
843 header.l2_bits = 9;
844 }
845 header_size = (header_size + 7) & ~7;
846 shift = header.cluster_bits + header.l2_bits;
847 l1_size = (total_size + (1LL << shift) - 1) >> shift;
848
849 header.l1_table_offset = cpu_to_be64(header_size);
850
851 options = qemu_opts_to_qdict(opts, NULL);
852 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
853 QDECREF(options);
854 if (encryptfmt) {
855 if (!g_str_equal(encryptfmt, "aes")) {
856 error_setg(errp, "Unknown encryption format '%s', expected 'aes'",
857 encryptfmt);
858 ret = -EINVAL;
859 goto exit;
860 }
861 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
862
863 crypto_opts = block_crypto_create_opts_init(
864 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
865 if (!crypto_opts) {
866 ret = -EINVAL;
867 goto exit;
868 }
869
870 crypto = qcrypto_block_create(crypto_opts, "encrypt.",
871 NULL, NULL, NULL, errp);
872 if (!crypto) {
873 ret = -EINVAL;
874 goto exit;
875 }
876 } else {
877 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
878 }
879
880
881 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
882 if (ret != sizeof(header)) {
883 goto exit;
884 }
885
886 if (backing_file) {
887 ret = blk_pwrite(qcow_blk, sizeof(header),
888 backing_file, backing_filename_len, 0);
889 if (ret != backing_filename_len) {
890 goto exit;
891 }
892 }
893
894 tmp = g_malloc0(BDRV_SECTOR_SIZE);
895 for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
896 i++) {
897 ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
898 tmp, BDRV_SECTOR_SIZE, 0);
899 if (ret != BDRV_SECTOR_SIZE) {
900 g_free(tmp);
901 goto exit;
902 }
903 }
904
905 g_free(tmp);
906 ret = 0;
907exit:
908 blk_unref(qcow_blk);
909cleanup:
910 QDECREF(encryptopts);
911 g_free(encryptfmt);
912 qcrypto_block_free(crypto);
913 qapi_free_QCryptoBlockCreateOptions(crypto_opts);
914 g_free(backing_file);
915 return ret;
916}
917
918static int qcow_make_empty(BlockDriverState *bs)
919{
920 BDRVQcowState *s = bs->opaque;
921 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
922 int ret;
923
924 memset(s->l1_table, 0, l1_length);
925 if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
926 l1_length) < 0)
927 return -1;
928 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length,
929 PREALLOC_MODE_OFF, NULL);
930 if (ret < 0)
931 return ret;
932
933 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
934 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
935 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
936
937 return 0;
938}
939
940
941
942static coroutine_fn int
943qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
944 uint64_t bytes, QEMUIOVector *qiov)
945{
946 BDRVQcowState *s = bs->opaque;
947 QEMUIOVector hd_qiov;
948 struct iovec iov;
949 z_stream strm;
950 int ret, out_len;
951 uint8_t *buf, *out_buf;
952 uint64_t cluster_offset;
953
954 buf = qemu_blockalign(bs, s->cluster_size);
955 if (bytes != s->cluster_size) {
956 if (bytes > s->cluster_size ||
957 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
958 {
959 qemu_vfree(buf);
960 return -EINVAL;
961 }
962
963 memset(buf + bytes, 0, s->cluster_size - bytes);
964 }
965 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
966
967 out_buf = g_malloc(s->cluster_size);
968
969
970 memset(&strm, 0, sizeof(strm));
971 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
972 Z_DEFLATED, -12,
973 9, Z_DEFAULT_STRATEGY);
974 if (ret != 0) {
975 ret = -EINVAL;
976 goto fail;
977 }
978
979 strm.avail_in = s->cluster_size;
980 strm.next_in = (uint8_t *)buf;
981 strm.avail_out = s->cluster_size;
982 strm.next_out = out_buf;
983
984 ret = deflate(&strm, Z_FINISH);
985 if (ret != Z_STREAM_END && ret != Z_OK) {
986 deflateEnd(&strm);
987 ret = -EINVAL;
988 goto fail;
989 }
990 out_len = strm.next_out - out_buf;
991
992 deflateEnd(&strm);
993
994 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
995
996 ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,
997 bytes >> BDRV_SECTOR_BITS, qiov);
998 if (ret < 0) {
999 goto fail;
1000 }
1001 goto success;
1002 }
1003 qemu_co_mutex_lock(&s->lock);
1004 cluster_offset = get_cluster_offset(bs, offset, 2, out_len, 0, 0);
1005 qemu_co_mutex_unlock(&s->lock);
1006 if (cluster_offset == 0) {
1007 ret = -EIO;
1008 goto fail;
1009 }
1010 cluster_offset &= s->cluster_offset_mask;
1011
1012 iov = (struct iovec) {
1013 .iov_base = out_buf,
1014 .iov_len = out_len,
1015 };
1016 qemu_iovec_init_external(&hd_qiov, &iov, 1);
1017 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
1018 if (ret < 0) {
1019 goto fail;
1020 }
1021success:
1022 ret = 0;
1023fail:
1024 qemu_vfree(buf);
1025 g_free(out_buf);
1026 return ret;
1027}
1028
1029static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1030{
1031 BDRVQcowState *s = bs->opaque;
1032 bdi->cluster_size = s->cluster_size;
1033 return 0;
1034}
1035
1036static QemuOptsList qcow_create_opts = {
1037 .name = "qcow-create-opts",
1038 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1039 .desc = {
1040 {
1041 .name = BLOCK_OPT_SIZE,
1042 .type = QEMU_OPT_SIZE,
1043 .help = "Virtual disk size"
1044 },
1045 {
1046 .name = BLOCK_OPT_BACKING_FILE,
1047 .type = QEMU_OPT_STRING,
1048 .help = "File name of a base image"
1049 },
1050 {
1051 .name = BLOCK_OPT_ENCRYPT,
1052 .type = QEMU_OPT_BOOL,
1053 .help = "Encrypt the image with format 'aes'. (Deprecated "
1054 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
1055 },
1056 {
1057 .name = BLOCK_OPT_ENCRYPT_FORMAT,
1058 .type = QEMU_OPT_STRING,
1059 .help = "Encrypt the image, format choices: 'aes'",
1060 },
1061 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
1062 { }
1063 }
1064};
1065
1066static BlockDriver bdrv_qcow = {
1067 .format_name = "qcow",
1068 .instance_size = sizeof(BDRVQcowState),
1069 .bdrv_probe = qcow_probe,
1070 .bdrv_open = qcow_open,
1071 .bdrv_close = qcow_close,
1072 .bdrv_child_perm = bdrv_format_default_perms,
1073 .bdrv_reopen_prepare = qcow_reopen_prepare,
1074 .bdrv_create = qcow_create,
1075 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1076 .supports_backing = true,
1077
1078 .bdrv_co_readv = qcow_co_readv,
1079 .bdrv_co_writev = qcow_co_writev,
1080 .bdrv_co_get_block_status = qcow_co_get_block_status,
1081
1082 .bdrv_make_empty = qcow_make_empty,
1083 .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed,
1084 .bdrv_get_info = qcow_get_info,
1085
1086 .create_opts = &qcow_create_opts,
1087};
1088
1089static void bdrv_qcow_init(void)
1090{
1091 bdrv_register(&bdrv_qcow);
1092}
1093
1094block_init(bdrv_qcow_init);
1095