xen-hvm.c: Always return -1 when failure occurs in xen_hvm_init()
[qemu/kevin.git] / block / qcow2.c
blob0daf25cb5840e015751f465b49bf1d4f7ec4995b
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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 "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qbool.h"
33 #include "qapi/util.h"
34 #include "trace.h"
35 #include "qemu/option_int.h"
38 Differences with QCOW:
40 - Support for multiple incremental snapshots.
41 - Memory management by reference counts.
42 - Clusters which have a reference count of one have the bit
43 QCOW_OFLAG_COPIED to optimize write performance.
44 - Size of compressed clusters is stored in sectors to reduce bit usage
45 in the cluster offsets.
46 - Support for storing additional data (such as the VM state) in the
47 snapshots.
48 - If a backing store is used, the cluster size is not constrained
49 (could be backported to QCOW).
50 - L2 tables have always a size of one cluster.
54 typedef struct {
55 uint32_t magic;
56 uint32_t len;
57 } QEMU_PACKED QCowExtension;
59 #define QCOW2_EXT_MAGIC_END 0
60 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
61 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
63 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
65 const QCowHeader *cow_header = (const void *)buf;
67 if (buf_size >= sizeof(QCowHeader) &&
68 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
69 be32_to_cpu(cow_header->version) >= 2)
70 return 100;
71 else
72 return 0;
76 /*
77 * read qcow2 extension and fill bs
78 * start reading from start_offset
79 * finish reading upon magic of value 0 or when end_offset reached
80 * unknown magic is skipped (future extension this version knows nothing about)
81 * return 0 upon success, non-0 otherwise
83 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
84 uint64_t end_offset, void **p_feature_table,
85 Error **errp)
87 BDRVQcowState *s = bs->opaque;
88 QCowExtension ext;
89 uint64_t offset;
90 int ret;
92 #ifdef DEBUG_EXT
93 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
94 #endif
95 offset = start_offset;
96 while (offset < end_offset) {
98 #ifdef DEBUG_EXT
99 /* Sanity check */
100 if (offset > s->cluster_size)
101 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
103 printf("attempting to read extended header in offset %lu\n", offset);
104 #endif
106 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
107 if (ret < 0) {
108 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
109 "pread fail from offset %" PRIu64, offset);
110 return 1;
112 be32_to_cpus(&ext.magic);
113 be32_to_cpus(&ext.len);
114 offset += sizeof(ext);
115 #ifdef DEBUG_EXT
116 printf("ext.magic = 0x%x\n", ext.magic);
117 #endif
118 if (ext.len > end_offset - offset) {
119 error_setg(errp, "Header extension too large");
120 return -EINVAL;
123 switch (ext.magic) {
124 case QCOW2_EXT_MAGIC_END:
125 return 0;
127 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
128 if (ext.len >= sizeof(bs->backing_format)) {
129 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
130 " too large (>=%zu)", ext.len,
131 sizeof(bs->backing_format));
132 return 2;
134 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
135 if (ret < 0) {
136 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
137 "Could not read format name");
138 return 3;
140 bs->backing_format[ext.len] = '\0';
141 #ifdef DEBUG_EXT
142 printf("Qcow2: Got format extension %s\n", bs->backing_format);
143 #endif
144 break;
146 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
147 if (p_feature_table != NULL) {
148 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
149 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
150 if (ret < 0) {
151 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
152 "Could not read table");
153 return ret;
156 *p_feature_table = feature_table;
158 break;
160 default:
161 /* unknown magic - save it in case we need to rewrite the header */
163 Qcow2UnknownHeaderExtension *uext;
165 uext = g_malloc0(sizeof(*uext) + ext.len);
166 uext->magic = ext.magic;
167 uext->len = ext.len;
168 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
170 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
171 if (ret < 0) {
172 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
173 "Could not read data");
174 return ret;
177 break;
180 offset += ((ext.len + 7) & ~7);
183 return 0;
186 static void cleanup_unknown_header_ext(BlockDriverState *bs)
188 BDRVQcowState *s = bs->opaque;
189 Qcow2UnknownHeaderExtension *uext, *next;
191 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
192 QLIST_REMOVE(uext, next);
193 g_free(uext);
197 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
198 Error **errp, const char *fmt, ...)
200 char msg[64];
201 va_list ap;
203 va_start(ap, fmt);
204 vsnprintf(msg, sizeof(msg), fmt, ap);
205 va_end(ap);
207 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
208 msg);
211 static void report_unsupported_feature(BlockDriverState *bs,
212 Error **errp, Qcow2Feature *table, uint64_t mask)
214 char *features = g_strdup("");
215 char *old;
217 while (table && table->name[0] != '\0') {
218 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
219 if (mask & (1ULL << table->bit)) {
220 old = features;
221 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
222 table->name);
223 g_free(old);
224 mask &= ~(1ULL << table->bit);
227 table++;
230 if (mask) {
231 old = features;
232 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
233 old, *old ? ", " : "", mask);
234 g_free(old);
237 report_unsupported(bs, errp, "%s", features);
238 g_free(features);
242 * Sets the dirty bit and flushes afterwards if necessary.
244 * The incompatible_features bit is only set if the image file header was
245 * updated successfully. Therefore it is not required to check the return
246 * value of this function.
248 int qcow2_mark_dirty(BlockDriverState *bs)
250 BDRVQcowState *s = bs->opaque;
251 uint64_t val;
252 int ret;
254 assert(s->qcow_version >= 3);
256 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
257 return 0; /* already dirty */
260 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
261 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
262 &val, sizeof(val));
263 if (ret < 0) {
264 return ret;
266 ret = bdrv_flush(bs->file);
267 if (ret < 0) {
268 return ret;
271 /* Only treat image as dirty if the header was updated successfully */
272 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
273 return 0;
277 * Clears the dirty bit and flushes before if necessary. Only call this
278 * function when there are no pending requests, it does not guard against
279 * concurrent requests dirtying the image.
281 static int qcow2_mark_clean(BlockDriverState *bs)
283 BDRVQcowState *s = bs->opaque;
285 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
286 int ret;
288 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
290 ret = bdrv_flush(bs);
291 if (ret < 0) {
292 return ret;
295 return qcow2_update_header(bs);
297 return 0;
301 * Marks the image as corrupt.
303 int qcow2_mark_corrupt(BlockDriverState *bs)
305 BDRVQcowState *s = bs->opaque;
307 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
308 return qcow2_update_header(bs);
312 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
313 * before if necessary.
315 int qcow2_mark_consistent(BlockDriverState *bs)
317 BDRVQcowState *s = bs->opaque;
319 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
320 int ret = bdrv_flush(bs);
321 if (ret < 0) {
322 return ret;
325 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
326 return qcow2_update_header(bs);
328 return 0;
331 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
332 BdrvCheckMode fix)
334 int ret = qcow2_check_refcounts(bs, result, fix);
335 if (ret < 0) {
336 return ret;
339 if (fix && result->check_errors == 0 && result->corruptions == 0) {
340 ret = qcow2_mark_clean(bs);
341 if (ret < 0) {
342 return ret;
344 return qcow2_mark_consistent(bs);
346 return ret;
349 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
350 uint64_t entries, size_t entry_len)
352 BDRVQcowState *s = bs->opaque;
353 uint64_t size;
355 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
356 * because values will be passed to qemu functions taking int64_t. */
357 if (entries > INT64_MAX / entry_len) {
358 return -EINVAL;
361 size = entries * entry_len;
363 if (INT64_MAX - size < offset) {
364 return -EINVAL;
367 /* Tables must be cluster aligned */
368 if (offset & (s->cluster_size - 1)) {
369 return -EINVAL;
372 return 0;
375 static QemuOptsList qcow2_runtime_opts = {
376 .name = "qcow2",
377 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
378 .desc = {
380 .name = QCOW2_OPT_LAZY_REFCOUNTS,
381 .type = QEMU_OPT_BOOL,
382 .help = "Postpone refcount updates",
385 .name = QCOW2_OPT_DISCARD_REQUEST,
386 .type = QEMU_OPT_BOOL,
387 .help = "Pass guest discard requests to the layer below",
390 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
391 .type = QEMU_OPT_BOOL,
392 .help = "Generate discard requests when snapshot related space "
393 "is freed",
396 .name = QCOW2_OPT_DISCARD_OTHER,
397 .type = QEMU_OPT_BOOL,
398 .help = "Generate discard requests when other clusters are freed",
401 .name = QCOW2_OPT_OVERLAP,
402 .type = QEMU_OPT_STRING,
403 .help = "Selects which overlap checks to perform from a range of "
404 "templates (none, constant, cached, all)",
407 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
408 .type = QEMU_OPT_BOOL,
409 .help = "Check for unintended writes into the main qcow2 header",
412 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
413 .type = QEMU_OPT_BOOL,
414 .help = "Check for unintended writes into the active L1 table",
417 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
418 .type = QEMU_OPT_BOOL,
419 .help = "Check for unintended writes into an active L2 table",
422 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
423 .type = QEMU_OPT_BOOL,
424 .help = "Check for unintended writes into the refcount table",
427 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
428 .type = QEMU_OPT_BOOL,
429 .help = "Check for unintended writes into a refcount block",
432 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
433 .type = QEMU_OPT_BOOL,
434 .help = "Check for unintended writes into the snapshot table",
437 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
438 .type = QEMU_OPT_BOOL,
439 .help = "Check for unintended writes into an inactive L1 table",
442 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
443 .type = QEMU_OPT_BOOL,
444 .help = "Check for unintended writes into an inactive L2 table",
447 .name = QCOW2_OPT_CACHE_SIZE,
448 .type = QEMU_OPT_SIZE,
449 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
450 "cache size",
453 .name = QCOW2_OPT_L2_CACHE_SIZE,
454 .type = QEMU_OPT_SIZE,
455 .help = "Maximum L2 table cache size",
458 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
459 .type = QEMU_OPT_SIZE,
460 .help = "Maximum refcount block cache size",
462 { /* end of list */ }
466 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
467 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
468 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
469 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
470 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
471 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
472 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
473 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
474 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
477 static void read_cache_sizes(QemuOpts *opts, uint64_t *l2_cache_size,
478 uint64_t *refcount_cache_size, Error **errp)
480 uint64_t combined_cache_size;
481 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
483 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
484 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
485 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
487 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
488 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
489 *refcount_cache_size = qemu_opt_get_size(opts,
490 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
492 if (combined_cache_size_set) {
493 if (l2_cache_size_set && refcount_cache_size_set) {
494 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
495 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
496 "the same time");
497 return;
498 } else if (*l2_cache_size > combined_cache_size) {
499 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
500 QCOW2_OPT_CACHE_SIZE);
501 return;
502 } else if (*refcount_cache_size > combined_cache_size) {
503 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
504 QCOW2_OPT_CACHE_SIZE);
505 return;
508 if (l2_cache_size_set) {
509 *refcount_cache_size = combined_cache_size - *l2_cache_size;
510 } else if (refcount_cache_size_set) {
511 *l2_cache_size = combined_cache_size - *refcount_cache_size;
512 } else {
513 *refcount_cache_size = combined_cache_size
514 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
515 *l2_cache_size = combined_cache_size - *refcount_cache_size;
517 } else {
518 if (!l2_cache_size_set && !refcount_cache_size_set) {
519 *l2_cache_size = DEFAULT_L2_CACHE_BYTE_SIZE;
520 *refcount_cache_size = *l2_cache_size
521 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
522 } else if (!l2_cache_size_set) {
523 *l2_cache_size = *refcount_cache_size
524 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
525 } else if (!refcount_cache_size_set) {
526 *refcount_cache_size = *l2_cache_size
527 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
532 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
533 Error **errp)
535 BDRVQcowState *s = bs->opaque;
536 unsigned int len, i;
537 int ret = 0;
538 QCowHeader header;
539 QemuOpts *opts;
540 Error *local_err = NULL;
541 uint64_t ext_end;
542 uint64_t l1_vm_state_index;
543 const char *opt_overlap_check;
544 int overlap_check_template = 0;
545 uint64_t l2_cache_size, refcount_cache_size;
547 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
548 if (ret < 0) {
549 error_setg_errno(errp, -ret, "Could not read qcow2 header");
550 goto fail;
552 be32_to_cpus(&header.magic);
553 be32_to_cpus(&header.version);
554 be64_to_cpus(&header.backing_file_offset);
555 be32_to_cpus(&header.backing_file_size);
556 be64_to_cpus(&header.size);
557 be32_to_cpus(&header.cluster_bits);
558 be32_to_cpus(&header.crypt_method);
559 be64_to_cpus(&header.l1_table_offset);
560 be32_to_cpus(&header.l1_size);
561 be64_to_cpus(&header.refcount_table_offset);
562 be32_to_cpus(&header.refcount_table_clusters);
563 be64_to_cpus(&header.snapshots_offset);
564 be32_to_cpus(&header.nb_snapshots);
566 if (header.magic != QCOW_MAGIC) {
567 error_setg(errp, "Image is not in qcow2 format");
568 ret = -EINVAL;
569 goto fail;
571 if (header.version < 2 || header.version > 3) {
572 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
573 ret = -ENOTSUP;
574 goto fail;
577 s->qcow_version = header.version;
579 /* Initialise cluster size */
580 if (header.cluster_bits < MIN_CLUSTER_BITS ||
581 header.cluster_bits > MAX_CLUSTER_BITS) {
582 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
583 header.cluster_bits);
584 ret = -EINVAL;
585 goto fail;
588 s->cluster_bits = header.cluster_bits;
589 s->cluster_size = 1 << s->cluster_bits;
590 s->cluster_sectors = 1 << (s->cluster_bits - 9);
592 /* Initialise version 3 header fields */
593 if (header.version == 2) {
594 header.incompatible_features = 0;
595 header.compatible_features = 0;
596 header.autoclear_features = 0;
597 header.refcount_order = 4;
598 header.header_length = 72;
599 } else {
600 be64_to_cpus(&header.incompatible_features);
601 be64_to_cpus(&header.compatible_features);
602 be64_to_cpus(&header.autoclear_features);
603 be32_to_cpus(&header.refcount_order);
604 be32_to_cpus(&header.header_length);
606 if (header.header_length < 104) {
607 error_setg(errp, "qcow2 header too short");
608 ret = -EINVAL;
609 goto fail;
613 if (header.header_length > s->cluster_size) {
614 error_setg(errp, "qcow2 header exceeds cluster size");
615 ret = -EINVAL;
616 goto fail;
619 if (header.header_length > sizeof(header)) {
620 s->unknown_header_fields_size = header.header_length - sizeof(header);
621 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
622 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
623 s->unknown_header_fields_size);
624 if (ret < 0) {
625 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
626 "fields");
627 goto fail;
631 if (header.backing_file_offset > s->cluster_size) {
632 error_setg(errp, "Invalid backing file offset");
633 ret = -EINVAL;
634 goto fail;
637 if (header.backing_file_offset) {
638 ext_end = header.backing_file_offset;
639 } else {
640 ext_end = 1 << header.cluster_bits;
643 /* Handle feature bits */
644 s->incompatible_features = header.incompatible_features;
645 s->compatible_features = header.compatible_features;
646 s->autoclear_features = header.autoclear_features;
648 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
649 void *feature_table = NULL;
650 qcow2_read_extensions(bs, header.header_length, ext_end,
651 &feature_table, NULL);
652 report_unsupported_feature(bs, errp, feature_table,
653 s->incompatible_features &
654 ~QCOW2_INCOMPAT_MASK);
655 ret = -ENOTSUP;
656 g_free(feature_table);
657 goto fail;
660 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
661 /* Corrupt images may not be written to unless they are being repaired
663 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
664 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
665 "read/write");
666 ret = -EACCES;
667 goto fail;
671 /* Check support for various header values */
672 if (header.refcount_order != 4) {
673 report_unsupported(bs, errp, "%d bit reference counts",
674 1 << header.refcount_order);
675 ret = -ENOTSUP;
676 goto fail;
678 s->refcount_order = header.refcount_order;
680 if (header.crypt_method > QCOW_CRYPT_AES) {
681 error_setg(errp, "Unsupported encryption method: %" PRIu32,
682 header.crypt_method);
683 ret = -EINVAL;
684 goto fail;
686 s->crypt_method_header = header.crypt_method;
687 if (s->crypt_method_header) {
688 bs->encrypted = 1;
691 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
692 s->l2_size = 1 << s->l2_bits;
693 bs->total_sectors = header.size / 512;
694 s->csize_shift = (62 - (s->cluster_bits - 8));
695 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
696 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
698 s->refcount_table_offset = header.refcount_table_offset;
699 s->refcount_table_size =
700 header.refcount_table_clusters << (s->cluster_bits - 3);
702 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
703 error_setg(errp, "Reference count table too large");
704 ret = -EINVAL;
705 goto fail;
708 ret = validate_table_offset(bs, s->refcount_table_offset,
709 s->refcount_table_size, sizeof(uint64_t));
710 if (ret < 0) {
711 error_setg(errp, "Invalid reference count table offset");
712 goto fail;
715 /* Snapshot table offset/length */
716 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
717 error_setg(errp, "Too many snapshots");
718 ret = -EINVAL;
719 goto fail;
722 ret = validate_table_offset(bs, header.snapshots_offset,
723 header.nb_snapshots,
724 sizeof(QCowSnapshotHeader));
725 if (ret < 0) {
726 error_setg(errp, "Invalid snapshot table offset");
727 goto fail;
730 /* read the level 1 table */
731 if (header.l1_size > QCOW_MAX_L1_SIZE) {
732 error_setg(errp, "Active L1 table too large");
733 ret = -EFBIG;
734 goto fail;
736 s->l1_size = header.l1_size;
738 l1_vm_state_index = size_to_l1(s, header.size);
739 if (l1_vm_state_index > INT_MAX) {
740 error_setg(errp, "Image is too big");
741 ret = -EFBIG;
742 goto fail;
744 s->l1_vm_state_index = l1_vm_state_index;
746 /* the L1 table must contain at least enough entries to put
747 header.size bytes */
748 if (s->l1_size < s->l1_vm_state_index) {
749 error_setg(errp, "L1 table is too small");
750 ret = -EINVAL;
751 goto fail;
754 ret = validate_table_offset(bs, header.l1_table_offset,
755 header.l1_size, sizeof(uint64_t));
756 if (ret < 0) {
757 error_setg(errp, "Invalid L1 table offset");
758 goto fail;
760 s->l1_table_offset = header.l1_table_offset;
763 if (s->l1_size > 0) {
764 s->l1_table = qemu_try_blockalign(bs->file,
765 align_offset(s->l1_size * sizeof(uint64_t), 512));
766 if (s->l1_table == NULL) {
767 error_setg(errp, "Could not allocate L1 table");
768 ret = -ENOMEM;
769 goto fail;
771 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
772 s->l1_size * sizeof(uint64_t));
773 if (ret < 0) {
774 error_setg_errno(errp, -ret, "Could not read L1 table");
775 goto fail;
777 for(i = 0;i < s->l1_size; i++) {
778 be64_to_cpus(&s->l1_table[i]);
782 /* get L2 table/refcount block cache size from command line options */
783 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
784 qemu_opts_absorb_qdict(opts, options, &local_err);
785 if (local_err) {
786 error_propagate(errp, local_err);
787 ret = -EINVAL;
788 goto fail;
791 read_cache_sizes(opts, &l2_cache_size, &refcount_cache_size, &local_err);
792 if (local_err) {
793 error_propagate(errp, local_err);
794 ret = -EINVAL;
795 goto fail;
798 l2_cache_size /= s->cluster_size;
799 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
800 l2_cache_size = MIN_L2_CACHE_SIZE;
802 if (l2_cache_size > INT_MAX) {
803 error_setg(errp, "L2 cache size too big");
804 ret = -EINVAL;
805 goto fail;
808 refcount_cache_size /= s->cluster_size;
809 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
810 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
812 if (refcount_cache_size > INT_MAX) {
813 error_setg(errp, "Refcount cache size too big");
814 ret = -EINVAL;
815 goto fail;
818 /* alloc L2 table/refcount block cache */
819 s->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
820 s->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
821 if (s->l2_table_cache == NULL || s->refcount_block_cache == NULL) {
822 error_setg(errp, "Could not allocate metadata caches");
823 ret = -ENOMEM;
824 goto fail;
827 s->cluster_cache = g_malloc(s->cluster_size);
828 /* one more sector for decompressed data alignment */
829 s->cluster_data = qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
830 * s->cluster_size + 512);
831 if (s->cluster_data == NULL) {
832 error_setg(errp, "Could not allocate temporary cluster buffer");
833 ret = -ENOMEM;
834 goto fail;
837 s->cluster_cache_offset = -1;
838 s->flags = flags;
840 ret = qcow2_refcount_init(bs);
841 if (ret != 0) {
842 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
843 goto fail;
846 QLIST_INIT(&s->cluster_allocs);
847 QTAILQ_INIT(&s->discards);
849 /* read qcow2 extensions */
850 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
851 &local_err)) {
852 error_propagate(errp, local_err);
853 ret = -EINVAL;
854 goto fail;
857 /* read the backing file name */
858 if (header.backing_file_offset != 0) {
859 len = header.backing_file_size;
860 if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
861 error_setg(errp, "Backing file name too long");
862 ret = -EINVAL;
863 goto fail;
865 ret = bdrv_pread(bs->file, header.backing_file_offset,
866 bs->backing_file, len);
867 if (ret < 0) {
868 error_setg_errno(errp, -ret, "Could not read backing file name");
869 goto fail;
871 bs->backing_file[len] = '\0';
874 /* Internal snapshots */
875 s->snapshots_offset = header.snapshots_offset;
876 s->nb_snapshots = header.nb_snapshots;
878 ret = qcow2_read_snapshots(bs);
879 if (ret < 0) {
880 error_setg_errno(errp, -ret, "Could not read snapshots");
881 goto fail;
884 /* Clear unknown autoclear feature bits */
885 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
886 s->autoclear_features = 0;
887 ret = qcow2_update_header(bs);
888 if (ret < 0) {
889 error_setg_errno(errp, -ret, "Could not update qcow2 header");
890 goto fail;
894 /* Initialise locks */
895 qemu_co_mutex_init(&s->lock);
897 /* Repair image if dirty */
898 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
899 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
900 BdrvCheckResult result = {0};
902 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
903 if (ret < 0) {
904 error_setg_errno(errp, -ret, "Could not repair dirty image");
905 goto fail;
909 /* Enable lazy_refcounts according to image and command line options */
910 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
911 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
913 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
914 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
915 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
916 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
917 flags & BDRV_O_UNMAP);
918 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
919 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
920 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
921 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
923 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
924 if (!strcmp(opt_overlap_check, "none")) {
925 overlap_check_template = 0;
926 } else if (!strcmp(opt_overlap_check, "constant")) {
927 overlap_check_template = QCOW2_OL_CONSTANT;
928 } else if (!strcmp(opt_overlap_check, "cached")) {
929 overlap_check_template = QCOW2_OL_CACHED;
930 } else if (!strcmp(opt_overlap_check, "all")) {
931 overlap_check_template = QCOW2_OL_ALL;
932 } else {
933 error_setg(errp, "Unsupported value '%s' for qcow2 option "
934 "'overlap-check'. Allowed are either of the following: "
935 "none, constant, cached, all", opt_overlap_check);
936 qemu_opts_del(opts);
937 ret = -EINVAL;
938 goto fail;
941 s->overlap_check = 0;
942 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
943 /* overlap-check defines a template bitmask, but every flag may be
944 * overwritten through the associated boolean option */
945 s->overlap_check |=
946 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
947 overlap_check_template & (1 << i)) << i;
950 qemu_opts_del(opts);
952 if (s->use_lazy_refcounts && s->qcow_version < 3) {
953 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
954 "qemu 1.1 compatibility level");
955 ret = -EINVAL;
956 goto fail;
959 #ifdef DEBUG_ALLOC
961 BdrvCheckResult result = {0};
962 qcow2_check_refcounts(bs, &result, 0);
964 #endif
965 return ret;
967 fail:
968 g_free(s->unknown_header_fields);
969 cleanup_unknown_header_ext(bs);
970 qcow2_free_snapshots(bs);
971 qcow2_refcount_close(bs);
972 qemu_vfree(s->l1_table);
973 /* else pre-write overlap checks in cache_destroy may crash */
974 s->l1_table = NULL;
975 if (s->l2_table_cache) {
976 qcow2_cache_destroy(bs, s->l2_table_cache);
978 if (s->refcount_block_cache) {
979 qcow2_cache_destroy(bs, s->refcount_block_cache);
981 g_free(s->cluster_cache);
982 qemu_vfree(s->cluster_data);
983 return ret;
986 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
988 BDRVQcowState *s = bs->opaque;
990 bs->bl.write_zeroes_alignment = s->cluster_sectors;
993 static int qcow2_set_key(BlockDriverState *bs, const char *key)
995 BDRVQcowState *s = bs->opaque;
996 uint8_t keybuf[16];
997 int len, i;
999 memset(keybuf, 0, 16);
1000 len = strlen(key);
1001 if (len > 16)
1002 len = 16;
1003 /* XXX: we could compress the chars to 7 bits to increase
1004 entropy */
1005 for(i = 0;i < len;i++) {
1006 keybuf[i] = key[i];
1008 s->crypt_method = s->crypt_method_header;
1010 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
1011 return -1;
1012 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
1013 return -1;
1014 #if 0
1015 /* test */
1017 uint8_t in[16];
1018 uint8_t out[16];
1019 uint8_t tmp[16];
1020 for(i=0;i<16;i++)
1021 in[i] = i;
1022 AES_encrypt(in, tmp, &s->aes_encrypt_key);
1023 AES_decrypt(tmp, out, &s->aes_decrypt_key);
1024 for(i = 0; i < 16; i++)
1025 printf(" %02x", tmp[i]);
1026 printf("\n");
1027 for(i = 0; i < 16; i++)
1028 printf(" %02x", out[i]);
1029 printf("\n");
1031 #endif
1032 return 0;
1035 /* We have no actual commit/abort logic for qcow2, but we need to write out any
1036 * unwritten data if we reopen read-only. */
1037 static int qcow2_reopen_prepare(BDRVReopenState *state,
1038 BlockReopenQueue *queue, Error **errp)
1040 int ret;
1042 if ((state->flags & BDRV_O_RDWR) == 0) {
1043 ret = bdrv_flush(state->bs);
1044 if (ret < 0) {
1045 return ret;
1048 ret = qcow2_mark_clean(state->bs);
1049 if (ret < 0) {
1050 return ret;
1054 return 0;
1057 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1058 int64_t sector_num, int nb_sectors, int *pnum)
1060 BDRVQcowState *s = bs->opaque;
1061 uint64_t cluster_offset;
1062 int index_in_cluster, ret;
1063 int64_t status = 0;
1065 *pnum = nb_sectors;
1066 qemu_co_mutex_lock(&s->lock);
1067 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1068 qemu_co_mutex_unlock(&s->lock);
1069 if (ret < 0) {
1070 return ret;
1073 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1074 !s->crypt_method) {
1075 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1076 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1077 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1079 if (ret == QCOW2_CLUSTER_ZERO) {
1080 status |= BDRV_BLOCK_ZERO;
1081 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1082 status |= BDRV_BLOCK_DATA;
1084 return status;
1087 /* handle reading after the end of the backing file */
1088 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1089 int64_t sector_num, int nb_sectors)
1091 int n1;
1092 if ((sector_num + nb_sectors) <= bs->total_sectors)
1093 return nb_sectors;
1094 if (sector_num >= bs->total_sectors)
1095 n1 = 0;
1096 else
1097 n1 = bs->total_sectors - sector_num;
1099 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1101 return n1;
1104 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1105 int remaining_sectors, QEMUIOVector *qiov)
1107 BDRVQcowState *s = bs->opaque;
1108 int index_in_cluster, n1;
1109 int ret;
1110 int cur_nr_sectors; /* number of sectors in current iteration */
1111 uint64_t cluster_offset = 0;
1112 uint64_t bytes_done = 0;
1113 QEMUIOVector hd_qiov;
1114 uint8_t *cluster_data = NULL;
1116 qemu_iovec_init(&hd_qiov, qiov->niov);
1118 qemu_co_mutex_lock(&s->lock);
1120 while (remaining_sectors != 0) {
1122 /* prepare next request */
1123 cur_nr_sectors = remaining_sectors;
1124 if (s->crypt_method) {
1125 cur_nr_sectors = MIN(cur_nr_sectors,
1126 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1129 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1130 &cur_nr_sectors, &cluster_offset);
1131 if (ret < 0) {
1132 goto fail;
1135 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1137 qemu_iovec_reset(&hd_qiov);
1138 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1139 cur_nr_sectors * 512);
1141 switch (ret) {
1142 case QCOW2_CLUSTER_UNALLOCATED:
1144 if (bs->backing_hd) {
1145 /* read from the base image */
1146 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1147 sector_num, cur_nr_sectors);
1148 if (n1 > 0) {
1149 QEMUIOVector local_qiov;
1151 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1152 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1153 n1 * BDRV_SECTOR_SIZE);
1155 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1156 qemu_co_mutex_unlock(&s->lock);
1157 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1158 n1, &local_qiov);
1159 qemu_co_mutex_lock(&s->lock);
1161 qemu_iovec_destroy(&local_qiov);
1163 if (ret < 0) {
1164 goto fail;
1167 } else {
1168 /* Note: in this case, no need to wait */
1169 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1171 break;
1173 case QCOW2_CLUSTER_ZERO:
1174 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1175 break;
1177 case QCOW2_CLUSTER_COMPRESSED:
1178 /* add AIO support for compressed blocks ? */
1179 ret = qcow2_decompress_cluster(bs, cluster_offset);
1180 if (ret < 0) {
1181 goto fail;
1184 qemu_iovec_from_buf(&hd_qiov, 0,
1185 s->cluster_cache + index_in_cluster * 512,
1186 512 * cur_nr_sectors);
1187 break;
1189 case QCOW2_CLUSTER_NORMAL:
1190 if ((cluster_offset & 511) != 0) {
1191 ret = -EIO;
1192 goto fail;
1195 if (s->crypt_method) {
1197 * For encrypted images, read everything into a temporary
1198 * contiguous buffer on which the AES functions can work.
1200 if (!cluster_data) {
1201 cluster_data =
1202 qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1203 * s->cluster_size);
1204 if (cluster_data == NULL) {
1205 ret = -ENOMEM;
1206 goto fail;
1210 assert(cur_nr_sectors <=
1211 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1212 qemu_iovec_reset(&hd_qiov);
1213 qemu_iovec_add(&hd_qiov, cluster_data,
1214 512 * cur_nr_sectors);
1217 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1218 qemu_co_mutex_unlock(&s->lock);
1219 ret = bdrv_co_readv(bs->file,
1220 (cluster_offset >> 9) + index_in_cluster,
1221 cur_nr_sectors, &hd_qiov);
1222 qemu_co_mutex_lock(&s->lock);
1223 if (ret < 0) {
1224 goto fail;
1226 if (s->crypt_method) {
1227 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1228 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1229 qemu_iovec_from_buf(qiov, bytes_done,
1230 cluster_data, 512 * cur_nr_sectors);
1232 break;
1234 default:
1235 g_assert_not_reached();
1236 ret = -EIO;
1237 goto fail;
1240 remaining_sectors -= cur_nr_sectors;
1241 sector_num += cur_nr_sectors;
1242 bytes_done += cur_nr_sectors * 512;
1244 ret = 0;
1246 fail:
1247 qemu_co_mutex_unlock(&s->lock);
1249 qemu_iovec_destroy(&hd_qiov);
1250 qemu_vfree(cluster_data);
1252 return ret;
1255 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1256 int64_t sector_num,
1257 int remaining_sectors,
1258 QEMUIOVector *qiov)
1260 BDRVQcowState *s = bs->opaque;
1261 int index_in_cluster;
1262 int ret;
1263 int cur_nr_sectors; /* number of sectors in current iteration */
1264 uint64_t cluster_offset;
1265 QEMUIOVector hd_qiov;
1266 uint64_t bytes_done = 0;
1267 uint8_t *cluster_data = NULL;
1268 QCowL2Meta *l2meta = NULL;
1270 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1271 remaining_sectors);
1273 qemu_iovec_init(&hd_qiov, qiov->niov);
1275 s->cluster_cache_offset = -1; /* disable compressed cache */
1277 qemu_co_mutex_lock(&s->lock);
1279 while (remaining_sectors != 0) {
1281 l2meta = NULL;
1283 trace_qcow2_writev_start_part(qemu_coroutine_self());
1284 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1285 cur_nr_sectors = remaining_sectors;
1286 if (s->crypt_method &&
1287 cur_nr_sectors >
1288 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1289 cur_nr_sectors =
1290 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1293 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1294 &cur_nr_sectors, &cluster_offset, &l2meta);
1295 if (ret < 0) {
1296 goto fail;
1299 assert((cluster_offset & 511) == 0);
1301 qemu_iovec_reset(&hd_qiov);
1302 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1303 cur_nr_sectors * 512);
1305 if (s->crypt_method) {
1306 if (!cluster_data) {
1307 cluster_data = qemu_try_blockalign(bs->file,
1308 QCOW_MAX_CRYPT_CLUSTERS
1309 * s->cluster_size);
1310 if (cluster_data == NULL) {
1311 ret = -ENOMEM;
1312 goto fail;
1316 assert(hd_qiov.size <=
1317 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1318 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1320 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1321 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1323 qemu_iovec_reset(&hd_qiov);
1324 qemu_iovec_add(&hd_qiov, cluster_data,
1325 cur_nr_sectors * 512);
1328 ret = qcow2_pre_write_overlap_check(bs, 0,
1329 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1330 cur_nr_sectors * BDRV_SECTOR_SIZE);
1331 if (ret < 0) {
1332 goto fail;
1335 qemu_co_mutex_unlock(&s->lock);
1336 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1337 trace_qcow2_writev_data(qemu_coroutine_self(),
1338 (cluster_offset >> 9) + index_in_cluster);
1339 ret = bdrv_co_writev(bs->file,
1340 (cluster_offset >> 9) + index_in_cluster,
1341 cur_nr_sectors, &hd_qiov);
1342 qemu_co_mutex_lock(&s->lock);
1343 if (ret < 0) {
1344 goto fail;
1347 while (l2meta != NULL) {
1348 QCowL2Meta *next;
1350 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1351 if (ret < 0) {
1352 goto fail;
1355 /* Take the request off the list of running requests */
1356 if (l2meta->nb_clusters != 0) {
1357 QLIST_REMOVE(l2meta, next_in_flight);
1360 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1362 next = l2meta->next;
1363 g_free(l2meta);
1364 l2meta = next;
1367 remaining_sectors -= cur_nr_sectors;
1368 sector_num += cur_nr_sectors;
1369 bytes_done += cur_nr_sectors * 512;
1370 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1372 ret = 0;
1374 fail:
1375 qemu_co_mutex_unlock(&s->lock);
1377 while (l2meta != NULL) {
1378 QCowL2Meta *next;
1380 if (l2meta->nb_clusters != 0) {
1381 QLIST_REMOVE(l2meta, next_in_flight);
1383 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1385 next = l2meta->next;
1386 g_free(l2meta);
1387 l2meta = next;
1390 qemu_iovec_destroy(&hd_qiov);
1391 qemu_vfree(cluster_data);
1392 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1394 return ret;
1397 static void qcow2_close(BlockDriverState *bs)
1399 BDRVQcowState *s = bs->opaque;
1400 qemu_vfree(s->l1_table);
1401 /* else pre-write overlap checks in cache_destroy may crash */
1402 s->l1_table = NULL;
1404 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1405 qcow2_cache_flush(bs, s->l2_table_cache);
1406 qcow2_cache_flush(bs, s->refcount_block_cache);
1408 qcow2_mark_clean(bs);
1411 qcow2_cache_destroy(bs, s->l2_table_cache);
1412 qcow2_cache_destroy(bs, s->refcount_block_cache);
1414 g_free(s->unknown_header_fields);
1415 cleanup_unknown_header_ext(bs);
1417 g_free(s->cluster_cache);
1418 qemu_vfree(s->cluster_data);
1419 qcow2_refcount_close(bs);
1420 qcow2_free_snapshots(bs);
1423 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1425 BDRVQcowState *s = bs->opaque;
1426 int flags = s->flags;
1427 AES_KEY aes_encrypt_key;
1428 AES_KEY aes_decrypt_key;
1429 uint32_t crypt_method = 0;
1430 QDict *options;
1431 Error *local_err = NULL;
1432 int ret;
1435 * Backing files are read-only which makes all of their metadata immutable,
1436 * that means we don't have to worry about reopening them here.
1439 if (s->crypt_method) {
1440 crypt_method = s->crypt_method;
1441 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1442 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1445 qcow2_close(bs);
1447 bdrv_invalidate_cache(bs->file, &local_err);
1448 if (local_err) {
1449 error_propagate(errp, local_err);
1450 return;
1453 memset(s, 0, sizeof(BDRVQcowState));
1454 options = qdict_clone_shallow(bs->options);
1456 ret = qcow2_open(bs, options, flags, &local_err);
1457 QDECREF(options);
1458 if (local_err) {
1459 error_setg(errp, "Could not reopen qcow2 layer: %s",
1460 error_get_pretty(local_err));
1461 error_free(local_err);
1462 return;
1463 } else if (ret < 0) {
1464 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1465 return;
1468 if (crypt_method) {
1469 s->crypt_method = crypt_method;
1470 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1471 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1475 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1476 size_t len, size_t buflen)
1478 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1479 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1481 if (buflen < ext_len) {
1482 return -ENOSPC;
1485 *ext_backing_fmt = (QCowExtension) {
1486 .magic = cpu_to_be32(magic),
1487 .len = cpu_to_be32(len),
1489 memcpy(buf + sizeof(QCowExtension), s, len);
1491 return ext_len;
1495 * Updates the qcow2 header, including the variable length parts of it, i.e.
1496 * the backing file name and all extensions. qcow2 was not designed to allow
1497 * such changes, so if we run out of space (we can only use the first cluster)
1498 * this function may fail.
1500 * Returns 0 on success, -errno in error cases.
1502 int qcow2_update_header(BlockDriverState *bs)
1504 BDRVQcowState *s = bs->opaque;
1505 QCowHeader *header;
1506 char *buf;
1507 size_t buflen = s->cluster_size;
1508 int ret;
1509 uint64_t total_size;
1510 uint32_t refcount_table_clusters;
1511 size_t header_length;
1512 Qcow2UnknownHeaderExtension *uext;
1514 buf = qemu_blockalign(bs, buflen);
1516 /* Header structure */
1517 header = (QCowHeader*) buf;
1519 if (buflen < sizeof(*header)) {
1520 ret = -ENOSPC;
1521 goto fail;
1524 header_length = sizeof(*header) + s->unknown_header_fields_size;
1525 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1526 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1528 *header = (QCowHeader) {
1529 /* Version 2 fields */
1530 .magic = cpu_to_be32(QCOW_MAGIC),
1531 .version = cpu_to_be32(s->qcow_version),
1532 .backing_file_offset = 0,
1533 .backing_file_size = 0,
1534 .cluster_bits = cpu_to_be32(s->cluster_bits),
1535 .size = cpu_to_be64(total_size),
1536 .crypt_method = cpu_to_be32(s->crypt_method_header),
1537 .l1_size = cpu_to_be32(s->l1_size),
1538 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1539 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1540 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1541 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1542 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1544 /* Version 3 fields */
1545 .incompatible_features = cpu_to_be64(s->incompatible_features),
1546 .compatible_features = cpu_to_be64(s->compatible_features),
1547 .autoclear_features = cpu_to_be64(s->autoclear_features),
1548 .refcount_order = cpu_to_be32(s->refcount_order),
1549 .header_length = cpu_to_be32(header_length),
1552 /* For older versions, write a shorter header */
1553 switch (s->qcow_version) {
1554 case 2:
1555 ret = offsetof(QCowHeader, incompatible_features);
1556 break;
1557 case 3:
1558 ret = sizeof(*header);
1559 break;
1560 default:
1561 ret = -EINVAL;
1562 goto fail;
1565 buf += ret;
1566 buflen -= ret;
1567 memset(buf, 0, buflen);
1569 /* Preserve any unknown field in the header */
1570 if (s->unknown_header_fields_size) {
1571 if (buflen < s->unknown_header_fields_size) {
1572 ret = -ENOSPC;
1573 goto fail;
1576 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1577 buf += s->unknown_header_fields_size;
1578 buflen -= s->unknown_header_fields_size;
1581 /* Backing file format header extension */
1582 if (*bs->backing_format) {
1583 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1584 bs->backing_format, strlen(bs->backing_format),
1585 buflen);
1586 if (ret < 0) {
1587 goto fail;
1590 buf += ret;
1591 buflen -= ret;
1594 /* Feature table */
1595 Qcow2Feature features[] = {
1597 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1598 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1599 .name = "dirty bit",
1602 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1603 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1604 .name = "corrupt bit",
1607 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1608 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1609 .name = "lazy refcounts",
1613 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1614 features, sizeof(features), buflen);
1615 if (ret < 0) {
1616 goto fail;
1618 buf += ret;
1619 buflen -= ret;
1621 /* Keep unknown header extensions */
1622 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1623 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1624 if (ret < 0) {
1625 goto fail;
1628 buf += ret;
1629 buflen -= ret;
1632 /* End of header extensions */
1633 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1634 if (ret < 0) {
1635 goto fail;
1638 buf += ret;
1639 buflen -= ret;
1641 /* Backing file name */
1642 if (*bs->backing_file) {
1643 size_t backing_file_len = strlen(bs->backing_file);
1645 if (buflen < backing_file_len) {
1646 ret = -ENOSPC;
1647 goto fail;
1650 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1651 strncpy(buf, bs->backing_file, buflen);
1653 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1654 header->backing_file_size = cpu_to_be32(backing_file_len);
1657 /* Write the new header */
1658 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1659 if (ret < 0) {
1660 goto fail;
1663 ret = 0;
1664 fail:
1665 qemu_vfree(header);
1666 return ret;
1669 static int qcow2_change_backing_file(BlockDriverState *bs,
1670 const char *backing_file, const char *backing_fmt)
1672 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1673 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1675 return qcow2_update_header(bs);
1678 static int preallocate(BlockDriverState *bs)
1680 uint64_t nb_sectors;
1681 uint64_t offset;
1682 uint64_t host_offset = 0;
1683 int num;
1684 int ret;
1685 QCowL2Meta *meta;
1687 nb_sectors = bdrv_nb_sectors(bs);
1688 offset = 0;
1690 while (nb_sectors) {
1691 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1692 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1693 &host_offset, &meta);
1694 if (ret < 0) {
1695 return ret;
1698 while (meta) {
1699 QCowL2Meta *next = meta->next;
1701 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1702 if (ret < 0) {
1703 qcow2_free_any_clusters(bs, meta->alloc_offset,
1704 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1705 return ret;
1708 /* There are no dependent requests, but we need to remove our
1709 * request from the list of in-flight requests */
1710 QLIST_REMOVE(meta, next_in_flight);
1712 g_free(meta);
1713 meta = next;
1716 /* TODO Preallocate data if requested */
1718 nb_sectors -= num;
1719 offset += num << BDRV_SECTOR_BITS;
1723 * It is expected that the image file is large enough to actually contain
1724 * all of the allocated clusters (otherwise we get failing reads after
1725 * EOF). Extend the image to the last allocated sector.
1727 if (host_offset != 0) {
1728 uint8_t buf[BDRV_SECTOR_SIZE];
1729 memset(buf, 0, BDRV_SECTOR_SIZE);
1730 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1731 buf, 1);
1732 if (ret < 0) {
1733 return ret;
1737 return 0;
1740 static int qcow2_create2(const char *filename, int64_t total_size,
1741 const char *backing_file, const char *backing_format,
1742 int flags, size_t cluster_size, PreallocMode prealloc,
1743 QemuOpts *opts, int version,
1744 Error **errp)
1746 /* Calculate cluster_bits */
1747 int cluster_bits;
1748 cluster_bits = ffs(cluster_size) - 1;
1749 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1750 (1 << cluster_bits) != cluster_size)
1752 error_setg(errp, "Cluster size must be a power of two between %d and "
1753 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1754 return -EINVAL;
1758 * Open the image file and write a minimal qcow2 header.
1760 * We keep things simple and start with a zero-sized image. We also
1761 * do without refcount blocks or a L1 table for now. We'll fix the
1762 * inconsistency later.
1764 * We do need a refcount table because growing the refcount table means
1765 * allocating two new refcount blocks - the seconds of which would be at
1766 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1767 * size for any qcow2 image.
1769 BlockDriverState* bs;
1770 QCowHeader *header;
1771 uint64_t* refcount_table;
1772 Error *local_err = NULL;
1773 int ret;
1775 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
1776 int64_t meta_size = 0;
1777 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
1778 int64_t aligned_total_size = align_offset(total_size, cluster_size);
1780 /* header: 1 cluster */
1781 meta_size += cluster_size;
1783 /* total size of L2 tables */
1784 nl2e = aligned_total_size / cluster_size;
1785 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
1786 meta_size += nl2e * sizeof(uint64_t);
1788 /* total size of L1 tables */
1789 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
1790 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
1791 meta_size += nl1e * sizeof(uint64_t);
1793 /* total size of refcount blocks
1795 * note: every host cluster is reference-counted, including metadata
1796 * (even refcount blocks are recursively included).
1797 * Let:
1798 * a = total_size (this is the guest disk size)
1799 * m = meta size not including refcount blocks and refcount tables
1800 * c = cluster size
1801 * y1 = number of refcount blocks entries
1802 * y2 = meta size including everything
1803 * then,
1804 * y1 = (y2 + a)/c
1805 * y2 = y1 * sizeof(u16) + y1 * sizeof(u16) * sizeof(u64) / c + m
1806 * we can get y1:
1807 * y1 = (a + m) / (c - sizeof(u16) - sizeof(u16) * sizeof(u64) / c)
1809 nrefblocke = (aligned_total_size + meta_size + cluster_size) /
1810 (cluster_size - sizeof(uint16_t) -
1811 1.0 * sizeof(uint16_t) * sizeof(uint64_t) / cluster_size);
1812 nrefblocke = align_offset(nrefblocke, cluster_size / sizeof(uint16_t));
1813 meta_size += nrefblocke * sizeof(uint16_t);
1815 /* total size of refcount tables */
1816 nreftablee = nrefblocke * sizeof(uint16_t) / cluster_size;
1817 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
1818 meta_size += nreftablee * sizeof(uint64_t);
1820 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
1821 aligned_total_size + meta_size);
1822 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc]);
1825 ret = bdrv_create_file(filename, opts, &local_err);
1826 if (ret < 0) {
1827 error_propagate(errp, local_err);
1828 return ret;
1831 bs = NULL;
1832 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1833 NULL, &local_err);
1834 if (ret < 0) {
1835 error_propagate(errp, local_err);
1836 return ret;
1839 /* Write the header */
1840 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1841 header = g_malloc0(cluster_size);
1842 *header = (QCowHeader) {
1843 .magic = cpu_to_be32(QCOW_MAGIC),
1844 .version = cpu_to_be32(version),
1845 .cluster_bits = cpu_to_be32(cluster_bits),
1846 .size = cpu_to_be64(0),
1847 .l1_table_offset = cpu_to_be64(0),
1848 .l1_size = cpu_to_be32(0),
1849 .refcount_table_offset = cpu_to_be64(cluster_size),
1850 .refcount_table_clusters = cpu_to_be32(1),
1851 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1852 .header_length = cpu_to_be32(sizeof(*header)),
1855 if (flags & BLOCK_FLAG_ENCRYPT) {
1856 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1857 } else {
1858 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1861 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1862 header->compatible_features |=
1863 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1866 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1867 g_free(header);
1868 if (ret < 0) {
1869 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1870 goto out;
1873 /* Write a refcount table with one refcount block */
1874 refcount_table = g_malloc0(2 * cluster_size);
1875 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1876 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
1877 g_free(refcount_table);
1879 if (ret < 0) {
1880 error_setg_errno(errp, -ret, "Could not write refcount table");
1881 goto out;
1884 bdrv_unref(bs);
1885 bs = NULL;
1888 * And now open the image and make it consistent first (i.e. increase the
1889 * refcount of the cluster that is occupied by the header and the refcount
1890 * table)
1892 BlockDriver* drv = bdrv_find_format("qcow2");
1893 assert(drv != NULL);
1894 ret = bdrv_open(&bs, filename, NULL, NULL,
1895 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1896 if (ret < 0) {
1897 error_propagate(errp, local_err);
1898 goto out;
1901 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1902 if (ret < 0) {
1903 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1904 "header and refcount table");
1905 goto out;
1907 } else if (ret != 0) {
1908 error_report("Huh, first cluster in empty image is already in use?");
1909 abort();
1912 /* Okay, now that we have a valid image, let's give it the right size */
1913 ret = bdrv_truncate(bs, total_size);
1914 if (ret < 0) {
1915 error_setg_errno(errp, -ret, "Could not resize image");
1916 goto out;
1919 /* Want a backing file? There you go.*/
1920 if (backing_file) {
1921 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1922 if (ret < 0) {
1923 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1924 "with format '%s'", backing_file, backing_format);
1925 goto out;
1929 /* And if we're supposed to preallocate metadata, do that now */
1930 if (prealloc != PREALLOC_MODE_OFF) {
1931 BDRVQcowState *s = bs->opaque;
1932 qemu_co_mutex_lock(&s->lock);
1933 ret = preallocate(bs);
1934 qemu_co_mutex_unlock(&s->lock);
1935 if (ret < 0) {
1936 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1937 goto out;
1941 bdrv_unref(bs);
1942 bs = NULL;
1944 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1945 ret = bdrv_open(&bs, filename, NULL, NULL,
1946 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1947 drv, &local_err);
1948 if (local_err) {
1949 error_propagate(errp, local_err);
1950 goto out;
1953 ret = 0;
1954 out:
1955 if (bs) {
1956 bdrv_unref(bs);
1958 return ret;
1961 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
1963 char *backing_file = NULL;
1964 char *backing_fmt = NULL;
1965 char *buf = NULL;
1966 uint64_t size = 0;
1967 int flags = 0;
1968 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1969 PreallocMode prealloc;
1970 int version = 3;
1971 Error *local_err = NULL;
1972 int ret;
1974 /* Read out options */
1975 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1976 BDRV_SECTOR_SIZE);
1977 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1978 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
1979 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
1980 flags |= BLOCK_FLAG_ENCRYPT;
1982 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
1983 DEFAULT_CLUSTER_SIZE);
1984 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1985 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1986 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1987 &local_err);
1988 if (local_err) {
1989 error_propagate(errp, local_err);
1990 ret = -EINVAL;
1991 goto finish;
1993 g_free(buf);
1994 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
1995 if (!buf) {
1996 /* keep the default */
1997 } else if (!strcmp(buf, "0.10")) {
1998 version = 2;
1999 } else if (!strcmp(buf, "1.1")) {
2000 version = 3;
2001 } else {
2002 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2003 ret = -EINVAL;
2004 goto finish;
2007 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2008 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2011 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2012 error_setg(errp, "Backing file and preallocation cannot be used at "
2013 "the same time");
2014 ret = -EINVAL;
2015 goto finish;
2018 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2019 error_setg(errp, "Lazy refcounts only supported with compatibility "
2020 "level 1.1 and above (use compat=1.1 or greater)");
2021 ret = -EINVAL;
2022 goto finish;
2025 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2026 cluster_size, prealloc, opts, version, &local_err);
2027 if (local_err) {
2028 error_propagate(errp, local_err);
2031 finish:
2032 g_free(backing_file);
2033 g_free(backing_fmt);
2034 g_free(buf);
2035 return ret;
2038 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2039 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2041 int ret;
2042 BDRVQcowState *s = bs->opaque;
2044 /* Emulate misaligned zero writes */
2045 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2046 return -ENOTSUP;
2049 /* Whatever is left can use real zero clusters */
2050 qemu_co_mutex_lock(&s->lock);
2051 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2052 nb_sectors);
2053 qemu_co_mutex_unlock(&s->lock);
2055 return ret;
2058 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2059 int64_t sector_num, int nb_sectors)
2061 int ret;
2062 BDRVQcowState *s = bs->opaque;
2064 qemu_co_mutex_lock(&s->lock);
2065 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2066 nb_sectors, QCOW2_DISCARD_REQUEST);
2067 qemu_co_mutex_unlock(&s->lock);
2068 return ret;
2071 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2073 BDRVQcowState *s = bs->opaque;
2074 int64_t new_l1_size;
2075 int ret;
2077 if (offset & 511) {
2078 error_report("The new size must be a multiple of 512");
2079 return -EINVAL;
2082 /* cannot proceed if image has snapshots */
2083 if (s->nb_snapshots) {
2084 error_report("Can't resize an image which has snapshots");
2085 return -ENOTSUP;
2088 /* shrinking is currently not supported */
2089 if (offset < bs->total_sectors * 512) {
2090 error_report("qcow2 doesn't support shrinking images yet");
2091 return -ENOTSUP;
2094 new_l1_size = size_to_l1(s, offset);
2095 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2096 if (ret < 0) {
2097 return ret;
2100 /* write updated header.size */
2101 offset = cpu_to_be64(offset);
2102 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2103 &offset, sizeof(uint64_t));
2104 if (ret < 0) {
2105 return ret;
2108 s->l1_vm_state_index = new_l1_size;
2109 return 0;
2112 /* XXX: put compressed sectors first, then all the cluster aligned
2113 tables to avoid losing bytes in alignment */
2114 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2115 const uint8_t *buf, int nb_sectors)
2117 BDRVQcowState *s = bs->opaque;
2118 z_stream strm;
2119 int ret, out_len;
2120 uint8_t *out_buf;
2121 uint64_t cluster_offset;
2123 if (nb_sectors == 0) {
2124 /* align end of file to a sector boundary to ease reading with
2125 sector based I/Os */
2126 cluster_offset = bdrv_getlength(bs->file);
2127 bdrv_truncate(bs->file, cluster_offset);
2128 return 0;
2131 if (nb_sectors != s->cluster_sectors) {
2132 ret = -EINVAL;
2134 /* Zero-pad last write if image size is not cluster aligned */
2135 if (sector_num + nb_sectors == bs->total_sectors &&
2136 nb_sectors < s->cluster_sectors) {
2137 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2138 memset(pad_buf, 0, s->cluster_size);
2139 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2140 ret = qcow2_write_compressed(bs, sector_num,
2141 pad_buf, s->cluster_sectors);
2142 qemu_vfree(pad_buf);
2144 return ret;
2147 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2149 /* best compression, small window, no zlib header */
2150 memset(&strm, 0, sizeof(strm));
2151 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2152 Z_DEFLATED, -12,
2153 9, Z_DEFAULT_STRATEGY);
2154 if (ret != 0) {
2155 ret = -EINVAL;
2156 goto fail;
2159 strm.avail_in = s->cluster_size;
2160 strm.next_in = (uint8_t *)buf;
2161 strm.avail_out = s->cluster_size;
2162 strm.next_out = out_buf;
2164 ret = deflate(&strm, Z_FINISH);
2165 if (ret != Z_STREAM_END && ret != Z_OK) {
2166 deflateEnd(&strm);
2167 ret = -EINVAL;
2168 goto fail;
2170 out_len = strm.next_out - out_buf;
2172 deflateEnd(&strm);
2174 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2175 /* could not compress: write normal cluster */
2176 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2177 if (ret < 0) {
2178 goto fail;
2180 } else {
2181 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2182 sector_num << 9, out_len);
2183 if (!cluster_offset) {
2184 ret = -EIO;
2185 goto fail;
2187 cluster_offset &= s->cluster_offset_mask;
2189 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2190 if (ret < 0) {
2191 goto fail;
2194 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2195 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2196 if (ret < 0) {
2197 goto fail;
2201 ret = 0;
2202 fail:
2203 g_free(out_buf);
2204 return ret;
2207 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2209 BDRVQcowState *s = bs->opaque;
2210 int ret;
2212 qemu_co_mutex_lock(&s->lock);
2213 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2214 if (ret < 0) {
2215 qemu_co_mutex_unlock(&s->lock);
2216 return ret;
2219 if (qcow2_need_accurate_refcounts(s)) {
2220 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2221 if (ret < 0) {
2222 qemu_co_mutex_unlock(&s->lock);
2223 return ret;
2226 qemu_co_mutex_unlock(&s->lock);
2228 return 0;
2231 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2233 BDRVQcowState *s = bs->opaque;
2234 bdi->unallocated_blocks_are_zero = true;
2235 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2236 bdi->cluster_size = s->cluster_size;
2237 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2238 return 0;
2241 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2243 BDRVQcowState *s = bs->opaque;
2244 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2246 *spec_info = (ImageInfoSpecific){
2247 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2249 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2252 if (s->qcow_version == 2) {
2253 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2254 .compat = g_strdup("0.10"),
2256 } else if (s->qcow_version == 3) {
2257 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2258 .compat = g_strdup("1.1"),
2259 .lazy_refcounts = s->compatible_features &
2260 QCOW2_COMPAT_LAZY_REFCOUNTS,
2261 .has_lazy_refcounts = true,
2265 return spec_info;
2268 #if 0
2269 static void dump_refcounts(BlockDriverState *bs)
2271 BDRVQcowState *s = bs->opaque;
2272 int64_t nb_clusters, k, k1, size;
2273 int refcount;
2275 size = bdrv_getlength(bs->file);
2276 nb_clusters = size_to_clusters(s, size);
2277 for(k = 0; k < nb_clusters;) {
2278 k1 = k;
2279 refcount = get_refcount(bs, k);
2280 k++;
2281 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2282 k++;
2283 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2284 k - k1);
2287 #endif
2289 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2290 int64_t pos)
2292 BDRVQcowState *s = bs->opaque;
2293 int64_t total_sectors = bs->total_sectors;
2294 int growable = bs->growable;
2295 bool zero_beyond_eof = bs->zero_beyond_eof;
2296 int ret;
2298 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2299 bs->growable = 1;
2300 bs->zero_beyond_eof = false;
2301 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2302 bs->growable = growable;
2303 bs->zero_beyond_eof = zero_beyond_eof;
2305 /* bdrv_co_do_writev will have increased the total_sectors value to include
2306 * the VM state - the VM state is however not an actual part of the block
2307 * device, therefore, we need to restore the old value. */
2308 bs->total_sectors = total_sectors;
2310 return ret;
2313 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2314 int64_t pos, int size)
2316 BDRVQcowState *s = bs->opaque;
2317 int growable = bs->growable;
2318 bool zero_beyond_eof = bs->zero_beyond_eof;
2319 int ret;
2321 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2322 bs->growable = 1;
2323 bs->zero_beyond_eof = false;
2324 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2325 bs->growable = growable;
2326 bs->zero_beyond_eof = zero_beyond_eof;
2328 return ret;
2332 * Downgrades an image's version. To achieve this, any incompatible features
2333 * have to be removed.
2335 static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2337 BDRVQcowState *s = bs->opaque;
2338 int current_version = s->qcow_version;
2339 int ret;
2341 if (target_version == current_version) {
2342 return 0;
2343 } else if (target_version > current_version) {
2344 return -EINVAL;
2345 } else if (target_version != 2) {
2346 return -EINVAL;
2349 if (s->refcount_order != 4) {
2350 /* we would have to convert the image to a refcount_order == 4 image
2351 * here; however, since qemu (at the time of writing this) does not
2352 * support anything different than 4 anyway, there is no point in doing
2353 * so right now; however, we should error out (if qemu supports this in
2354 * the future and this code has not been adapted) */
2355 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2356 "currently not supported.");
2357 return -ENOTSUP;
2360 /* clear incompatible features */
2361 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2362 ret = qcow2_mark_clean(bs);
2363 if (ret < 0) {
2364 return ret;
2368 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2369 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2370 * best thing to do anyway */
2372 if (s->incompatible_features) {
2373 return -ENOTSUP;
2376 /* since we can ignore compatible features, we can set them to 0 as well */
2377 s->compatible_features = 0;
2378 /* if lazy refcounts have been used, they have already been fixed through
2379 * clearing the dirty flag */
2381 /* clearing autoclear features is trivial */
2382 s->autoclear_features = 0;
2384 ret = qcow2_expand_zero_clusters(bs);
2385 if (ret < 0) {
2386 return ret;
2389 s->qcow_version = target_version;
2390 ret = qcow2_update_header(bs);
2391 if (ret < 0) {
2392 s->qcow_version = current_version;
2393 return ret;
2395 return 0;
2398 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts)
2400 BDRVQcowState *s = bs->opaque;
2401 int old_version = s->qcow_version, new_version = old_version;
2402 uint64_t new_size = 0;
2403 const char *backing_file = NULL, *backing_format = NULL;
2404 bool lazy_refcounts = s->use_lazy_refcounts;
2405 const char *compat = NULL;
2406 uint64_t cluster_size = s->cluster_size;
2407 bool encrypt;
2408 int ret;
2409 QemuOptDesc *desc = opts->list->desc;
2411 while (desc && desc->name) {
2412 if (!qemu_opt_find(opts, desc->name)) {
2413 /* only change explicitly defined options */
2414 desc++;
2415 continue;
2418 if (!strcmp(desc->name, "compat")) {
2419 compat = qemu_opt_get(opts, "compat");
2420 if (!compat) {
2421 /* preserve default */
2422 } else if (!strcmp(compat, "0.10")) {
2423 new_version = 2;
2424 } else if (!strcmp(compat, "1.1")) {
2425 new_version = 3;
2426 } else {
2427 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
2428 return -EINVAL;
2430 } else if (!strcmp(desc->name, "preallocation")) {
2431 fprintf(stderr, "Cannot change preallocation mode.\n");
2432 return -ENOTSUP;
2433 } else if (!strcmp(desc->name, "size")) {
2434 new_size = qemu_opt_get_size(opts, "size", 0);
2435 } else if (!strcmp(desc->name, "backing_file")) {
2436 backing_file = qemu_opt_get(opts, "backing_file");
2437 } else if (!strcmp(desc->name, "backing_fmt")) {
2438 backing_format = qemu_opt_get(opts, "backing_fmt");
2439 } else if (!strcmp(desc->name, "encryption")) {
2440 encrypt = qemu_opt_get_bool(opts, "encryption", s->crypt_method);
2441 if (encrypt != !!s->crypt_method) {
2442 fprintf(stderr, "Changing the encryption flag is not "
2443 "supported.\n");
2444 return -ENOTSUP;
2446 } else if (!strcmp(desc->name, "cluster_size")) {
2447 cluster_size = qemu_opt_get_size(opts, "cluster_size",
2448 cluster_size);
2449 if (cluster_size != s->cluster_size) {
2450 fprintf(stderr, "Changing the cluster size is not "
2451 "supported.\n");
2452 return -ENOTSUP;
2454 } else if (!strcmp(desc->name, "lazy_refcounts")) {
2455 lazy_refcounts = qemu_opt_get_bool(opts, "lazy_refcounts",
2456 lazy_refcounts);
2457 } else {
2458 /* if this assertion fails, this probably means a new option was
2459 * added without having it covered here */
2460 assert(false);
2463 desc++;
2466 if (new_version != old_version) {
2467 if (new_version > old_version) {
2468 /* Upgrade */
2469 s->qcow_version = new_version;
2470 ret = qcow2_update_header(bs);
2471 if (ret < 0) {
2472 s->qcow_version = old_version;
2473 return ret;
2475 } else {
2476 ret = qcow2_downgrade(bs, new_version);
2477 if (ret < 0) {
2478 return ret;
2483 if (backing_file || backing_format) {
2484 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2485 backing_format ?: bs->backing_format);
2486 if (ret < 0) {
2487 return ret;
2491 if (s->use_lazy_refcounts != lazy_refcounts) {
2492 if (lazy_refcounts) {
2493 if (s->qcow_version < 3) {
2494 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2495 "level 1.1 and above (use compat=1.1 or greater)\n");
2496 return -EINVAL;
2498 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2499 ret = qcow2_update_header(bs);
2500 if (ret < 0) {
2501 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2502 return ret;
2504 s->use_lazy_refcounts = true;
2505 } else {
2506 /* make image clean first */
2507 ret = qcow2_mark_clean(bs);
2508 if (ret < 0) {
2509 return ret;
2511 /* now disallow lazy refcounts */
2512 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2513 ret = qcow2_update_header(bs);
2514 if (ret < 0) {
2515 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2516 return ret;
2518 s->use_lazy_refcounts = false;
2522 if (new_size) {
2523 ret = bdrv_truncate(bs, new_size);
2524 if (ret < 0) {
2525 return ret;
2529 return 0;
2532 static QemuOptsList qcow2_create_opts = {
2533 .name = "qcow2-create-opts",
2534 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2535 .desc = {
2537 .name = BLOCK_OPT_SIZE,
2538 .type = QEMU_OPT_SIZE,
2539 .help = "Virtual disk size"
2542 .name = BLOCK_OPT_COMPAT_LEVEL,
2543 .type = QEMU_OPT_STRING,
2544 .help = "Compatibility level (0.10 or 1.1)"
2547 .name = BLOCK_OPT_BACKING_FILE,
2548 .type = QEMU_OPT_STRING,
2549 .help = "File name of a base image"
2552 .name = BLOCK_OPT_BACKING_FMT,
2553 .type = QEMU_OPT_STRING,
2554 .help = "Image format of the base image"
2557 .name = BLOCK_OPT_ENCRYPT,
2558 .type = QEMU_OPT_BOOL,
2559 .help = "Encrypt the image",
2560 .def_value_str = "off"
2563 .name = BLOCK_OPT_CLUSTER_SIZE,
2564 .type = QEMU_OPT_SIZE,
2565 .help = "qcow2 cluster size",
2566 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
2569 .name = BLOCK_OPT_PREALLOC,
2570 .type = QEMU_OPT_STRING,
2571 .help = "Preallocation mode (allowed values: off, metadata, "
2572 "falloc, full)"
2575 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2576 .type = QEMU_OPT_BOOL,
2577 .help = "Postpone refcount updates",
2578 .def_value_str = "off"
2580 { /* end of list */ }
2584 static BlockDriver bdrv_qcow2 = {
2585 .format_name = "qcow2",
2586 .instance_size = sizeof(BDRVQcowState),
2587 .bdrv_probe = qcow2_probe,
2588 .bdrv_open = qcow2_open,
2589 .bdrv_close = qcow2_close,
2590 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2591 .bdrv_create = qcow2_create,
2592 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2593 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2594 .bdrv_set_key = qcow2_set_key,
2596 .bdrv_co_readv = qcow2_co_readv,
2597 .bdrv_co_writev = qcow2_co_writev,
2598 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2600 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2601 .bdrv_co_discard = qcow2_co_discard,
2602 .bdrv_truncate = qcow2_truncate,
2603 .bdrv_write_compressed = qcow2_write_compressed,
2605 .bdrv_snapshot_create = qcow2_snapshot_create,
2606 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2607 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2608 .bdrv_snapshot_list = qcow2_snapshot_list,
2609 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2610 .bdrv_get_info = qcow2_get_info,
2611 .bdrv_get_specific_info = qcow2_get_specific_info,
2613 .bdrv_save_vmstate = qcow2_save_vmstate,
2614 .bdrv_load_vmstate = qcow2_load_vmstate,
2616 .supports_backing = true,
2617 .bdrv_change_backing_file = qcow2_change_backing_file,
2619 .bdrv_refresh_limits = qcow2_refresh_limits,
2620 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2622 .create_opts = &qcow2_create_opts,
2623 .bdrv_check = qcow2_check,
2624 .bdrv_amend_options = qcow2_amend_options,
2627 static void bdrv_qcow2_init(void)
2629 bdrv_register(&bdrv_qcow2);
2632 block_init(bdrv_qcow2_init);