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