]> git.proxmox.com Git - mirror_qemu.git/blob - block/qcow2.c
qcow2: Validate snapshot table offset/size (CVE-2014-0144)
[mirror_qemu.git] / block / qcow2.c
1 /*
2 * Block driver for the QCOW version 2 format
3 *
4 * Copyright (c) 2004-2006 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include "qemu-common.h"
25 #include "block/block_int.h"
26 #include "qemu/module.h"
27 #include <zlib.h>
28 #include "qemu/aes.h"
29 #include "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qbool.h"
33 #include "trace.h"
34
35 /*
36 Differences with QCOW:
37
38 - Support for multiple incremental snapshots.
39 - Memory management by reference counts.
40 - Clusters which have a reference count of one have the bit
41 QCOW_OFLAG_COPIED to optimize write performance.
42 - Size of compressed clusters is stored in sectors to reduce bit usage
43 in the cluster offsets.
44 - Support for storing additional data (such as the VM state) in the
45 snapshots.
46 - If a backing store is used, the cluster size is not constrained
47 (could be backported to QCOW).
48 - L2 tables have always a size of one cluster.
49 */
50
51
52 typedef struct {
53 uint32_t magic;
54 uint32_t len;
55 } QEMU_PACKED QCowExtension;
56
57 #define QCOW2_EXT_MAGIC_END 0
58 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
59 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
60
61 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
62 {
63 const QCowHeader *cow_header = (const void *)buf;
64
65 if (buf_size >= sizeof(QCowHeader) &&
66 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
67 be32_to_cpu(cow_header->version) >= 2)
68 return 100;
69 else
70 return 0;
71 }
72
73
74 /*
75 * read qcow2 extension and fill bs
76 * start reading from start_offset
77 * finish reading upon magic of value 0 or when end_offset reached
78 * unknown magic is skipped (future extension this version knows nothing about)
79 * return 0 upon success, non-0 otherwise
80 */
81 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
82 uint64_t end_offset, void **p_feature_table,
83 Error **errp)
84 {
85 BDRVQcowState *s = bs->opaque;
86 QCowExtension ext;
87 uint64_t offset;
88 int ret;
89
90 #ifdef DEBUG_EXT
91 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
92 #endif
93 offset = start_offset;
94 while (offset < end_offset) {
95
96 #ifdef DEBUG_EXT
97 /* Sanity check */
98 if (offset > s->cluster_size)
99 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
100
101 printf("attempting to read extended header in offset %lu\n", offset);
102 #endif
103
104 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
105 if (ret < 0) {
106 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
107 "pread fail from offset %" PRIu64, offset);
108 return 1;
109 }
110 be32_to_cpus(&ext.magic);
111 be32_to_cpus(&ext.len);
112 offset += sizeof(ext);
113 #ifdef DEBUG_EXT
114 printf("ext.magic = 0x%x\n", ext.magic);
115 #endif
116 if (ext.len > end_offset - offset) {
117 error_setg(errp, "Header extension too large");
118 return -EINVAL;
119 }
120
121 switch (ext.magic) {
122 case QCOW2_EXT_MAGIC_END:
123 return 0;
124
125 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
126 if (ext.len >= sizeof(bs->backing_format)) {
127 error_setg(errp, "ERROR: ext_backing_format: len=%u too large"
128 " (>=%zu)", ext.len, sizeof(bs->backing_format));
129 return 2;
130 }
131 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
132 if (ret < 0) {
133 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
134 "Could not read format name");
135 return 3;
136 }
137 bs->backing_format[ext.len] = '\0';
138 #ifdef DEBUG_EXT
139 printf("Qcow2: Got format extension %s\n", bs->backing_format);
140 #endif
141 break;
142
143 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
144 if (p_feature_table != NULL) {
145 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
146 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
147 if (ret < 0) {
148 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
149 "Could not read table");
150 return ret;
151 }
152
153 *p_feature_table = feature_table;
154 }
155 break;
156
157 default:
158 /* unknown magic - save it in case we need to rewrite the header */
159 {
160 Qcow2UnknownHeaderExtension *uext;
161
162 uext = g_malloc0(sizeof(*uext) + ext.len);
163 uext->magic = ext.magic;
164 uext->len = ext.len;
165 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
166
167 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
168 if (ret < 0) {
169 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
170 "Could not read data");
171 return ret;
172 }
173 }
174 break;
175 }
176
177 offset += ((ext.len + 7) & ~7);
178 }
179
180 return 0;
181 }
182
183 static void cleanup_unknown_header_ext(BlockDriverState *bs)
184 {
185 BDRVQcowState *s = bs->opaque;
186 Qcow2UnknownHeaderExtension *uext, *next;
187
188 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
189 QLIST_REMOVE(uext, next);
190 g_free(uext);
191 }
192 }
193
194 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
195 Error **errp, const char *fmt, ...)
196 {
197 char msg[64];
198 va_list ap;
199
200 va_start(ap, fmt);
201 vsnprintf(msg, sizeof(msg), fmt, ap);
202 va_end(ap);
203
204 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
205 msg);
206 }
207
208 static void report_unsupported_feature(BlockDriverState *bs,
209 Error **errp, Qcow2Feature *table, uint64_t mask)
210 {
211 while (table && table->name[0] != '\0') {
212 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
213 if (mask & (1 << table->bit)) {
214 report_unsupported(bs, errp, "%.46s", table->name);
215 mask &= ~(1 << table->bit);
216 }
217 }
218 table++;
219 }
220
221 if (mask) {
222 report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64,
223 mask);
224 }
225 }
226
227 /*
228 * Sets the dirty bit and flushes afterwards if necessary.
229 *
230 * The incompatible_features bit is only set if the image file header was
231 * updated successfully. Therefore it is not required to check the return
232 * value of this function.
233 */
234 int qcow2_mark_dirty(BlockDriverState *bs)
235 {
236 BDRVQcowState *s = bs->opaque;
237 uint64_t val;
238 int ret;
239
240 assert(s->qcow_version >= 3);
241
242 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
243 return 0; /* already dirty */
244 }
245
246 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
247 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
248 &val, sizeof(val));
249 if (ret < 0) {
250 return ret;
251 }
252 ret = bdrv_flush(bs->file);
253 if (ret < 0) {
254 return ret;
255 }
256
257 /* Only treat image as dirty if the header was updated successfully */
258 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
259 return 0;
260 }
261
262 /*
263 * Clears the dirty bit and flushes before if necessary. Only call this
264 * function when there are no pending requests, it does not guard against
265 * concurrent requests dirtying the image.
266 */
267 static int qcow2_mark_clean(BlockDriverState *bs)
268 {
269 BDRVQcowState *s = bs->opaque;
270
271 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
272 int ret = bdrv_flush(bs);
273 if (ret < 0) {
274 return ret;
275 }
276
277 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
278 return qcow2_update_header(bs);
279 }
280 return 0;
281 }
282
283 /*
284 * Marks the image as corrupt.
285 */
286 int qcow2_mark_corrupt(BlockDriverState *bs)
287 {
288 BDRVQcowState *s = bs->opaque;
289
290 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
291 return qcow2_update_header(bs);
292 }
293
294 /*
295 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
296 * before if necessary.
297 */
298 int qcow2_mark_consistent(BlockDriverState *bs)
299 {
300 BDRVQcowState *s = bs->opaque;
301
302 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
303 int ret = bdrv_flush(bs);
304 if (ret < 0) {
305 return ret;
306 }
307
308 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
309 return qcow2_update_header(bs);
310 }
311 return 0;
312 }
313
314 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
315 BdrvCheckMode fix)
316 {
317 int ret = qcow2_check_refcounts(bs, result, fix);
318 if (ret < 0) {
319 return ret;
320 }
321
322 if (fix && result->check_errors == 0 && result->corruptions == 0) {
323 ret = qcow2_mark_clean(bs);
324 if (ret < 0) {
325 return ret;
326 }
327 return qcow2_mark_consistent(bs);
328 }
329 return ret;
330 }
331
332 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
333 uint64_t entries, size_t entry_len)
334 {
335 BDRVQcowState *s = bs->opaque;
336 uint64_t size;
337
338 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
339 * because values will be passed to qemu functions taking int64_t. */
340 if (entries > INT64_MAX / entry_len) {
341 return -EINVAL;
342 }
343
344 size = entries * entry_len;
345
346 if (INT64_MAX - size < offset) {
347 return -EINVAL;
348 }
349
350 /* Tables must be cluster aligned */
351 if (offset & (s->cluster_size - 1)) {
352 return -EINVAL;
353 }
354
355 return 0;
356 }
357
358 static QemuOptsList qcow2_runtime_opts = {
359 .name = "qcow2",
360 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
361 .desc = {
362 {
363 .name = QCOW2_OPT_LAZY_REFCOUNTS,
364 .type = QEMU_OPT_BOOL,
365 .help = "Postpone refcount updates",
366 },
367 {
368 .name = QCOW2_OPT_DISCARD_REQUEST,
369 .type = QEMU_OPT_BOOL,
370 .help = "Pass guest discard requests to the layer below",
371 },
372 {
373 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
374 .type = QEMU_OPT_BOOL,
375 .help = "Generate discard requests when snapshot related space "
376 "is freed",
377 },
378 {
379 .name = QCOW2_OPT_DISCARD_OTHER,
380 .type = QEMU_OPT_BOOL,
381 .help = "Generate discard requests when other clusters are freed",
382 },
383 {
384 .name = QCOW2_OPT_OVERLAP,
385 .type = QEMU_OPT_STRING,
386 .help = "Selects which overlap checks to perform from a range of "
387 "templates (none, constant, cached, all)",
388 },
389 {
390 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
391 .type = QEMU_OPT_BOOL,
392 .help = "Check for unintended writes into the main qcow2 header",
393 },
394 {
395 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
396 .type = QEMU_OPT_BOOL,
397 .help = "Check for unintended writes into the active L1 table",
398 },
399 {
400 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
401 .type = QEMU_OPT_BOOL,
402 .help = "Check for unintended writes into an active L2 table",
403 },
404 {
405 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
406 .type = QEMU_OPT_BOOL,
407 .help = "Check for unintended writes into the refcount table",
408 },
409 {
410 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
411 .type = QEMU_OPT_BOOL,
412 .help = "Check for unintended writes into a refcount block",
413 },
414 {
415 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
416 .type = QEMU_OPT_BOOL,
417 .help = "Check for unintended writes into the snapshot table",
418 },
419 {
420 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
421 .type = QEMU_OPT_BOOL,
422 .help = "Check for unintended writes into an inactive L1 table",
423 },
424 {
425 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
426 .type = QEMU_OPT_BOOL,
427 .help = "Check for unintended writes into an inactive L2 table",
428 },
429 { /* end of list */ }
430 },
431 };
432
433 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
434 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
435 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
436 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
437 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
438 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
439 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
440 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
441 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
442 };
443
444 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
445 Error **errp)
446 {
447 BDRVQcowState *s = bs->opaque;
448 int len, i, ret = 0;
449 QCowHeader header;
450 QemuOpts *opts;
451 Error *local_err = NULL;
452 uint64_t ext_end;
453 uint64_t l1_vm_state_index;
454 const char *opt_overlap_check;
455 int overlap_check_template = 0;
456
457 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
458 if (ret < 0) {
459 error_setg_errno(errp, -ret, "Could not read qcow2 header");
460 goto fail;
461 }
462 be32_to_cpus(&header.magic);
463 be32_to_cpus(&header.version);
464 be64_to_cpus(&header.backing_file_offset);
465 be32_to_cpus(&header.backing_file_size);
466 be64_to_cpus(&header.size);
467 be32_to_cpus(&header.cluster_bits);
468 be32_to_cpus(&header.crypt_method);
469 be64_to_cpus(&header.l1_table_offset);
470 be32_to_cpus(&header.l1_size);
471 be64_to_cpus(&header.refcount_table_offset);
472 be32_to_cpus(&header.refcount_table_clusters);
473 be64_to_cpus(&header.snapshots_offset);
474 be32_to_cpus(&header.nb_snapshots);
475
476 if (header.magic != QCOW_MAGIC) {
477 error_setg(errp, "Image is not in qcow2 format");
478 ret = -EINVAL;
479 goto fail;
480 }
481 if (header.version < 2 || header.version > 3) {
482 report_unsupported(bs, errp, "QCOW version %d", header.version);
483 ret = -ENOTSUP;
484 goto fail;
485 }
486
487 s->qcow_version = header.version;
488
489 /* Initialise cluster size */
490 if (header.cluster_bits < MIN_CLUSTER_BITS ||
491 header.cluster_bits > MAX_CLUSTER_BITS) {
492 error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
493 ret = -EINVAL;
494 goto fail;
495 }
496
497 s->cluster_bits = header.cluster_bits;
498 s->cluster_size = 1 << s->cluster_bits;
499 s->cluster_sectors = 1 << (s->cluster_bits - 9);
500
501 /* Initialise version 3 header fields */
502 if (header.version == 2) {
503 header.incompatible_features = 0;
504 header.compatible_features = 0;
505 header.autoclear_features = 0;
506 header.refcount_order = 4;
507 header.header_length = 72;
508 } else {
509 be64_to_cpus(&header.incompatible_features);
510 be64_to_cpus(&header.compatible_features);
511 be64_to_cpus(&header.autoclear_features);
512 be32_to_cpus(&header.refcount_order);
513 be32_to_cpus(&header.header_length);
514
515 if (header.header_length < 104) {
516 error_setg(errp, "qcow2 header too short");
517 ret = -EINVAL;
518 goto fail;
519 }
520 }
521
522 if (header.header_length > s->cluster_size) {
523 error_setg(errp, "qcow2 header exceeds cluster size");
524 ret = -EINVAL;
525 goto fail;
526 }
527
528 if (header.header_length > sizeof(header)) {
529 s->unknown_header_fields_size = header.header_length - sizeof(header);
530 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
531 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
532 s->unknown_header_fields_size);
533 if (ret < 0) {
534 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
535 "fields");
536 goto fail;
537 }
538 }
539
540 if (header.backing_file_offset > s->cluster_size) {
541 error_setg(errp, "Invalid backing file offset");
542 ret = -EINVAL;
543 goto fail;
544 }
545
546 if (header.backing_file_offset) {
547 ext_end = header.backing_file_offset;
548 } else {
549 ext_end = 1 << header.cluster_bits;
550 }
551
552 /* Handle feature bits */
553 s->incompatible_features = header.incompatible_features;
554 s->compatible_features = header.compatible_features;
555 s->autoclear_features = header.autoclear_features;
556
557 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
558 void *feature_table = NULL;
559 qcow2_read_extensions(bs, header.header_length, ext_end,
560 &feature_table, NULL);
561 report_unsupported_feature(bs, errp, feature_table,
562 s->incompatible_features &
563 ~QCOW2_INCOMPAT_MASK);
564 ret = -ENOTSUP;
565 g_free(feature_table);
566 goto fail;
567 }
568
569 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
570 /* Corrupt images may not be written to unless they are being repaired
571 */
572 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
573 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
574 "read/write");
575 ret = -EACCES;
576 goto fail;
577 }
578 }
579
580 /* Check support for various header values */
581 if (header.refcount_order != 4) {
582 report_unsupported(bs, errp, "%d bit reference counts",
583 1 << header.refcount_order);
584 ret = -ENOTSUP;
585 goto fail;
586 }
587 s->refcount_order = header.refcount_order;
588
589 if (header.crypt_method > QCOW_CRYPT_AES) {
590 error_setg(errp, "Unsupported encryption method: %i",
591 header.crypt_method);
592 ret = -EINVAL;
593 goto fail;
594 }
595 s->crypt_method_header = header.crypt_method;
596 if (s->crypt_method_header) {
597 bs->encrypted = 1;
598 }
599
600 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
601 s->l2_size = 1 << s->l2_bits;
602 bs->total_sectors = header.size / 512;
603 s->csize_shift = (62 - (s->cluster_bits - 8));
604 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
605 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
606
607 s->refcount_table_offset = header.refcount_table_offset;
608 s->refcount_table_size =
609 header.refcount_table_clusters << (s->cluster_bits - 3);
610
611 if (header.refcount_table_clusters > (0x800000 >> s->cluster_bits)) {
612 /* 8 MB refcount table is enough for 2 PB images at 64k cluster size
613 * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
614 error_setg(errp, "Reference count table too large");
615 ret = -EINVAL;
616 goto fail;
617 }
618
619 ret = validate_table_offset(bs, s->refcount_table_offset,
620 s->refcount_table_size, sizeof(uint64_t));
621 if (ret < 0) {
622 error_setg(errp, "Invalid reference count table offset");
623 goto fail;
624 }
625
626 /* Snapshot table offset/length */
627 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
628 error_setg(errp, "Too many snapshots");
629 ret = -EINVAL;
630 goto fail;
631 }
632
633 ret = validate_table_offset(bs, header.snapshots_offset,
634 header.nb_snapshots,
635 sizeof(QCowSnapshotHeader));
636 if (ret < 0) {
637 error_setg(errp, "Invalid snapshot table offset");
638 goto fail;
639 }
640
641 s->snapshots_offset = header.snapshots_offset;
642 s->nb_snapshots = header.nb_snapshots;
643
644 /* read the level 1 table */
645 s->l1_size = header.l1_size;
646
647 l1_vm_state_index = size_to_l1(s, header.size);
648 if (l1_vm_state_index > INT_MAX) {
649 error_setg(errp, "Image is too big");
650 ret = -EFBIG;
651 goto fail;
652 }
653 s->l1_vm_state_index = l1_vm_state_index;
654
655 /* the L1 table must contain at least enough entries to put
656 header.size bytes */
657 if (s->l1_size < s->l1_vm_state_index) {
658 error_setg(errp, "L1 table is too small");
659 ret = -EINVAL;
660 goto fail;
661 }
662 s->l1_table_offset = header.l1_table_offset;
663 if (s->l1_size > 0) {
664 s->l1_table = g_malloc0(
665 align_offset(s->l1_size * sizeof(uint64_t), 512));
666 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
667 s->l1_size * sizeof(uint64_t));
668 if (ret < 0) {
669 error_setg_errno(errp, -ret, "Could not read L1 table");
670 goto fail;
671 }
672 for(i = 0;i < s->l1_size; i++) {
673 be64_to_cpus(&s->l1_table[i]);
674 }
675 }
676
677 /* alloc L2 table/refcount block cache */
678 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
679 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
680
681 s->cluster_cache = g_malloc(s->cluster_size);
682 /* one more sector for decompressed data alignment */
683 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
684 + 512);
685 s->cluster_cache_offset = -1;
686 s->flags = flags;
687
688 ret = qcow2_refcount_init(bs);
689 if (ret != 0) {
690 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
691 goto fail;
692 }
693
694 QLIST_INIT(&s->cluster_allocs);
695 QTAILQ_INIT(&s->discards);
696
697 /* read qcow2 extensions */
698 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
699 &local_err)) {
700 error_propagate(errp, local_err);
701 ret = -EINVAL;
702 goto fail;
703 }
704
705 /* read the backing file name */
706 if (header.backing_file_offset != 0) {
707 len = header.backing_file_size;
708 if (len > 1023) {
709 len = 1023;
710 }
711 ret = bdrv_pread(bs->file, header.backing_file_offset,
712 bs->backing_file, len);
713 if (ret < 0) {
714 error_setg_errno(errp, -ret, "Could not read backing file name");
715 goto fail;
716 }
717 bs->backing_file[len] = '\0';
718 }
719
720 ret = qcow2_read_snapshots(bs);
721 if (ret < 0) {
722 error_setg_errno(errp, -ret, "Could not read snapshots");
723 goto fail;
724 }
725
726 /* Clear unknown autoclear feature bits */
727 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
728 s->autoclear_features = 0;
729 ret = qcow2_update_header(bs);
730 if (ret < 0) {
731 error_setg_errno(errp, -ret, "Could not update qcow2 header");
732 goto fail;
733 }
734 }
735
736 /* Initialise locks */
737 qemu_co_mutex_init(&s->lock);
738
739 /* Repair image if dirty */
740 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
741 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
742 BdrvCheckResult result = {0};
743
744 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
745 if (ret < 0) {
746 error_setg_errno(errp, -ret, "Could not repair dirty image");
747 goto fail;
748 }
749 }
750
751 /* Enable lazy_refcounts according to image and command line options */
752 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
753 qemu_opts_absorb_qdict(opts, options, &local_err);
754 if (local_err) {
755 error_propagate(errp, local_err);
756 ret = -EINVAL;
757 goto fail;
758 }
759
760 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
761 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
762
763 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
764 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
765 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
766 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
767 flags & BDRV_O_UNMAP);
768 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
769 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
770 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
771 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
772
773 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
774 if (!strcmp(opt_overlap_check, "none")) {
775 overlap_check_template = 0;
776 } else if (!strcmp(opt_overlap_check, "constant")) {
777 overlap_check_template = QCOW2_OL_CONSTANT;
778 } else if (!strcmp(opt_overlap_check, "cached")) {
779 overlap_check_template = QCOW2_OL_CACHED;
780 } else if (!strcmp(opt_overlap_check, "all")) {
781 overlap_check_template = QCOW2_OL_ALL;
782 } else {
783 error_setg(errp, "Unsupported value '%s' for qcow2 option "
784 "'overlap-check'. Allowed are either of the following: "
785 "none, constant, cached, all", opt_overlap_check);
786 qemu_opts_del(opts);
787 ret = -EINVAL;
788 goto fail;
789 }
790
791 s->overlap_check = 0;
792 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
793 /* overlap-check defines a template bitmask, but every flag may be
794 * overwritten through the associated boolean option */
795 s->overlap_check |=
796 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
797 overlap_check_template & (1 << i)) << i;
798 }
799
800 qemu_opts_del(opts);
801
802 if (s->use_lazy_refcounts && s->qcow_version < 3) {
803 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
804 "qemu 1.1 compatibility level");
805 ret = -EINVAL;
806 goto fail;
807 }
808
809 #ifdef DEBUG_ALLOC
810 {
811 BdrvCheckResult result = {0};
812 qcow2_check_refcounts(bs, &result, 0);
813 }
814 #endif
815 return ret;
816
817 fail:
818 g_free(s->unknown_header_fields);
819 cleanup_unknown_header_ext(bs);
820 qcow2_free_snapshots(bs);
821 qcow2_refcount_close(bs);
822 g_free(s->l1_table);
823 /* else pre-write overlap checks in cache_destroy may crash */
824 s->l1_table = NULL;
825 if (s->l2_table_cache) {
826 qcow2_cache_destroy(bs, s->l2_table_cache);
827 }
828 if (s->refcount_block_cache) {
829 qcow2_cache_destroy(bs, s->refcount_block_cache);
830 }
831 g_free(s->cluster_cache);
832 qemu_vfree(s->cluster_data);
833 return ret;
834 }
835
836 static int qcow2_refresh_limits(BlockDriverState *bs)
837 {
838 BDRVQcowState *s = bs->opaque;
839
840 bs->bl.write_zeroes_alignment = s->cluster_sectors;
841
842 return 0;
843 }
844
845 static int qcow2_set_key(BlockDriverState *bs, const char *key)
846 {
847 BDRVQcowState *s = bs->opaque;
848 uint8_t keybuf[16];
849 int len, i;
850
851 memset(keybuf, 0, 16);
852 len = strlen(key);
853 if (len > 16)
854 len = 16;
855 /* XXX: we could compress the chars to 7 bits to increase
856 entropy */
857 for(i = 0;i < len;i++) {
858 keybuf[i] = key[i];
859 }
860 s->crypt_method = s->crypt_method_header;
861
862 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
863 return -1;
864 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
865 return -1;
866 #if 0
867 /* test */
868 {
869 uint8_t in[16];
870 uint8_t out[16];
871 uint8_t tmp[16];
872 for(i=0;i<16;i++)
873 in[i] = i;
874 AES_encrypt(in, tmp, &s->aes_encrypt_key);
875 AES_decrypt(tmp, out, &s->aes_decrypt_key);
876 for(i = 0; i < 16; i++)
877 printf(" %02x", tmp[i]);
878 printf("\n");
879 for(i = 0; i < 16; i++)
880 printf(" %02x", out[i]);
881 printf("\n");
882 }
883 #endif
884 return 0;
885 }
886
887 /* We have nothing to do for QCOW2 reopen, stubs just return
888 * success */
889 static int qcow2_reopen_prepare(BDRVReopenState *state,
890 BlockReopenQueue *queue, Error **errp)
891 {
892 return 0;
893 }
894
895 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
896 int64_t sector_num, int nb_sectors, int *pnum)
897 {
898 BDRVQcowState *s = bs->opaque;
899 uint64_t cluster_offset;
900 int index_in_cluster, ret;
901 int64_t status = 0;
902
903 *pnum = nb_sectors;
904 qemu_co_mutex_lock(&s->lock);
905 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
906 qemu_co_mutex_unlock(&s->lock);
907 if (ret < 0) {
908 return ret;
909 }
910
911 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
912 !s->crypt_method) {
913 index_in_cluster = sector_num & (s->cluster_sectors - 1);
914 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
915 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
916 }
917 if (ret == QCOW2_CLUSTER_ZERO) {
918 status |= BDRV_BLOCK_ZERO;
919 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
920 status |= BDRV_BLOCK_DATA;
921 }
922 return status;
923 }
924
925 /* handle reading after the end of the backing file */
926 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
927 int64_t sector_num, int nb_sectors)
928 {
929 int n1;
930 if ((sector_num + nb_sectors) <= bs->total_sectors)
931 return nb_sectors;
932 if (sector_num >= bs->total_sectors)
933 n1 = 0;
934 else
935 n1 = bs->total_sectors - sector_num;
936
937 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
938
939 return n1;
940 }
941
942 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
943 int remaining_sectors, QEMUIOVector *qiov)
944 {
945 BDRVQcowState *s = bs->opaque;
946 int index_in_cluster, n1;
947 int ret;
948 int cur_nr_sectors; /* number of sectors in current iteration */
949 uint64_t cluster_offset = 0;
950 uint64_t bytes_done = 0;
951 QEMUIOVector hd_qiov;
952 uint8_t *cluster_data = NULL;
953
954 qemu_iovec_init(&hd_qiov, qiov->niov);
955
956 qemu_co_mutex_lock(&s->lock);
957
958 while (remaining_sectors != 0) {
959
960 /* prepare next request */
961 cur_nr_sectors = remaining_sectors;
962 if (s->crypt_method) {
963 cur_nr_sectors = MIN(cur_nr_sectors,
964 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
965 }
966
967 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
968 &cur_nr_sectors, &cluster_offset);
969 if (ret < 0) {
970 goto fail;
971 }
972
973 index_in_cluster = sector_num & (s->cluster_sectors - 1);
974
975 qemu_iovec_reset(&hd_qiov);
976 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
977 cur_nr_sectors * 512);
978
979 switch (ret) {
980 case QCOW2_CLUSTER_UNALLOCATED:
981
982 if (bs->backing_hd) {
983 /* read from the base image */
984 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
985 sector_num, cur_nr_sectors);
986 if (n1 > 0) {
987 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
988 qemu_co_mutex_unlock(&s->lock);
989 ret = bdrv_co_readv(bs->backing_hd, sector_num,
990 n1, &hd_qiov);
991 qemu_co_mutex_lock(&s->lock);
992 if (ret < 0) {
993 goto fail;
994 }
995 }
996 } else {
997 /* Note: in this case, no need to wait */
998 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
999 }
1000 break;
1001
1002 case QCOW2_CLUSTER_ZERO:
1003 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1004 break;
1005
1006 case QCOW2_CLUSTER_COMPRESSED:
1007 /* add AIO support for compressed blocks ? */
1008 ret = qcow2_decompress_cluster(bs, cluster_offset);
1009 if (ret < 0) {
1010 goto fail;
1011 }
1012
1013 qemu_iovec_from_buf(&hd_qiov, 0,
1014 s->cluster_cache + index_in_cluster * 512,
1015 512 * cur_nr_sectors);
1016 break;
1017
1018 case QCOW2_CLUSTER_NORMAL:
1019 if ((cluster_offset & 511) != 0) {
1020 ret = -EIO;
1021 goto fail;
1022 }
1023
1024 if (s->crypt_method) {
1025 /*
1026 * For encrypted images, read everything into a temporary
1027 * contiguous buffer on which the AES functions can work.
1028 */
1029 if (!cluster_data) {
1030 cluster_data =
1031 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1032 }
1033
1034 assert(cur_nr_sectors <=
1035 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1036 qemu_iovec_reset(&hd_qiov);
1037 qemu_iovec_add(&hd_qiov, cluster_data,
1038 512 * cur_nr_sectors);
1039 }
1040
1041 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1042 qemu_co_mutex_unlock(&s->lock);
1043 ret = bdrv_co_readv(bs->file,
1044 (cluster_offset >> 9) + index_in_cluster,
1045 cur_nr_sectors, &hd_qiov);
1046 qemu_co_mutex_lock(&s->lock);
1047 if (ret < 0) {
1048 goto fail;
1049 }
1050 if (s->crypt_method) {
1051 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1052 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1053 qemu_iovec_from_buf(qiov, bytes_done,
1054 cluster_data, 512 * cur_nr_sectors);
1055 }
1056 break;
1057
1058 default:
1059 g_assert_not_reached();
1060 ret = -EIO;
1061 goto fail;
1062 }
1063
1064 remaining_sectors -= cur_nr_sectors;
1065 sector_num += cur_nr_sectors;
1066 bytes_done += cur_nr_sectors * 512;
1067 }
1068 ret = 0;
1069
1070 fail:
1071 qemu_co_mutex_unlock(&s->lock);
1072
1073 qemu_iovec_destroy(&hd_qiov);
1074 qemu_vfree(cluster_data);
1075
1076 return ret;
1077 }
1078
1079 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1080 int64_t sector_num,
1081 int remaining_sectors,
1082 QEMUIOVector *qiov)
1083 {
1084 BDRVQcowState *s = bs->opaque;
1085 int index_in_cluster;
1086 int ret;
1087 int cur_nr_sectors; /* number of sectors in current iteration */
1088 uint64_t cluster_offset;
1089 QEMUIOVector hd_qiov;
1090 uint64_t bytes_done = 0;
1091 uint8_t *cluster_data = NULL;
1092 QCowL2Meta *l2meta = NULL;
1093
1094 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1095 remaining_sectors);
1096
1097 qemu_iovec_init(&hd_qiov, qiov->niov);
1098
1099 s->cluster_cache_offset = -1; /* disable compressed cache */
1100
1101 qemu_co_mutex_lock(&s->lock);
1102
1103 while (remaining_sectors != 0) {
1104
1105 l2meta = NULL;
1106
1107 trace_qcow2_writev_start_part(qemu_coroutine_self());
1108 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1109 cur_nr_sectors = remaining_sectors;
1110 if (s->crypt_method &&
1111 cur_nr_sectors >
1112 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1113 cur_nr_sectors =
1114 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1115 }
1116
1117 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1118 &cur_nr_sectors, &cluster_offset, &l2meta);
1119 if (ret < 0) {
1120 goto fail;
1121 }
1122
1123 assert((cluster_offset & 511) == 0);
1124
1125 qemu_iovec_reset(&hd_qiov);
1126 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1127 cur_nr_sectors * 512);
1128
1129 if (s->crypt_method) {
1130 if (!cluster_data) {
1131 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1132 s->cluster_size);
1133 }
1134
1135 assert(hd_qiov.size <=
1136 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1137 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1138
1139 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1140 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1141
1142 qemu_iovec_reset(&hd_qiov);
1143 qemu_iovec_add(&hd_qiov, cluster_data,
1144 cur_nr_sectors * 512);
1145 }
1146
1147 ret = qcow2_pre_write_overlap_check(bs, 0,
1148 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1149 cur_nr_sectors * BDRV_SECTOR_SIZE);
1150 if (ret < 0) {
1151 goto fail;
1152 }
1153
1154 qemu_co_mutex_unlock(&s->lock);
1155 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1156 trace_qcow2_writev_data(qemu_coroutine_self(),
1157 (cluster_offset >> 9) + index_in_cluster);
1158 ret = bdrv_co_writev(bs->file,
1159 (cluster_offset >> 9) + index_in_cluster,
1160 cur_nr_sectors, &hd_qiov);
1161 qemu_co_mutex_lock(&s->lock);
1162 if (ret < 0) {
1163 goto fail;
1164 }
1165
1166 while (l2meta != NULL) {
1167 QCowL2Meta *next;
1168
1169 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1170 if (ret < 0) {
1171 goto fail;
1172 }
1173
1174 /* Take the request off the list of running requests */
1175 if (l2meta->nb_clusters != 0) {
1176 QLIST_REMOVE(l2meta, next_in_flight);
1177 }
1178
1179 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1180
1181 next = l2meta->next;
1182 g_free(l2meta);
1183 l2meta = next;
1184 }
1185
1186 remaining_sectors -= cur_nr_sectors;
1187 sector_num += cur_nr_sectors;
1188 bytes_done += cur_nr_sectors * 512;
1189 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1190 }
1191 ret = 0;
1192
1193 fail:
1194 qemu_co_mutex_unlock(&s->lock);
1195
1196 while (l2meta != NULL) {
1197 QCowL2Meta *next;
1198
1199 if (l2meta->nb_clusters != 0) {
1200 QLIST_REMOVE(l2meta, next_in_flight);
1201 }
1202 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1203
1204 next = l2meta->next;
1205 g_free(l2meta);
1206 l2meta = next;
1207 }
1208
1209 qemu_iovec_destroy(&hd_qiov);
1210 qemu_vfree(cluster_data);
1211 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1212
1213 return ret;
1214 }
1215
1216 static void qcow2_close(BlockDriverState *bs)
1217 {
1218 BDRVQcowState *s = bs->opaque;
1219 g_free(s->l1_table);
1220 /* else pre-write overlap checks in cache_destroy may crash */
1221 s->l1_table = NULL;
1222
1223 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1224 qcow2_cache_flush(bs, s->l2_table_cache);
1225 qcow2_cache_flush(bs, s->refcount_block_cache);
1226
1227 qcow2_mark_clean(bs);
1228 }
1229
1230 qcow2_cache_destroy(bs, s->l2_table_cache);
1231 qcow2_cache_destroy(bs, s->refcount_block_cache);
1232
1233 g_free(s->unknown_header_fields);
1234 cleanup_unknown_header_ext(bs);
1235
1236 g_free(s->cluster_cache);
1237 qemu_vfree(s->cluster_data);
1238 qcow2_refcount_close(bs);
1239 qcow2_free_snapshots(bs);
1240 }
1241
1242 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1243 {
1244 BDRVQcowState *s = bs->opaque;
1245 int flags = s->flags;
1246 AES_KEY aes_encrypt_key;
1247 AES_KEY aes_decrypt_key;
1248 uint32_t crypt_method = 0;
1249 QDict *options;
1250 Error *local_err = NULL;
1251 int ret;
1252
1253 /*
1254 * Backing files are read-only which makes all of their metadata immutable,
1255 * that means we don't have to worry about reopening them here.
1256 */
1257
1258 if (s->crypt_method) {
1259 crypt_method = s->crypt_method;
1260 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1261 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1262 }
1263
1264 qcow2_close(bs);
1265
1266 bdrv_invalidate_cache(bs->file, &local_err);
1267 if (local_err) {
1268 error_propagate(errp, local_err);
1269 return;
1270 }
1271
1272 memset(s, 0, sizeof(BDRVQcowState));
1273 options = qdict_clone_shallow(bs->options);
1274
1275 ret = qcow2_open(bs, options, flags, &local_err);
1276 if (local_err) {
1277 error_setg(errp, "Could not reopen qcow2 layer: %s",
1278 error_get_pretty(local_err));
1279 error_free(local_err);
1280 return;
1281 } else if (ret < 0) {
1282 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1283 return;
1284 }
1285
1286 QDECREF(options);
1287
1288 if (crypt_method) {
1289 s->crypt_method = crypt_method;
1290 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1291 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1292 }
1293 }
1294
1295 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1296 size_t len, size_t buflen)
1297 {
1298 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1299 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1300
1301 if (buflen < ext_len) {
1302 return -ENOSPC;
1303 }
1304
1305 *ext_backing_fmt = (QCowExtension) {
1306 .magic = cpu_to_be32(magic),
1307 .len = cpu_to_be32(len),
1308 };
1309 memcpy(buf + sizeof(QCowExtension), s, len);
1310
1311 return ext_len;
1312 }
1313
1314 /*
1315 * Updates the qcow2 header, including the variable length parts of it, i.e.
1316 * the backing file name and all extensions. qcow2 was not designed to allow
1317 * such changes, so if we run out of space (we can only use the first cluster)
1318 * this function may fail.
1319 *
1320 * Returns 0 on success, -errno in error cases.
1321 */
1322 int qcow2_update_header(BlockDriverState *bs)
1323 {
1324 BDRVQcowState *s = bs->opaque;
1325 QCowHeader *header;
1326 char *buf;
1327 size_t buflen = s->cluster_size;
1328 int ret;
1329 uint64_t total_size;
1330 uint32_t refcount_table_clusters;
1331 size_t header_length;
1332 Qcow2UnknownHeaderExtension *uext;
1333
1334 buf = qemu_blockalign(bs, buflen);
1335
1336 /* Header structure */
1337 header = (QCowHeader*) buf;
1338
1339 if (buflen < sizeof(*header)) {
1340 ret = -ENOSPC;
1341 goto fail;
1342 }
1343
1344 header_length = sizeof(*header) + s->unknown_header_fields_size;
1345 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1346 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1347
1348 *header = (QCowHeader) {
1349 /* Version 2 fields */
1350 .magic = cpu_to_be32(QCOW_MAGIC),
1351 .version = cpu_to_be32(s->qcow_version),
1352 .backing_file_offset = 0,
1353 .backing_file_size = 0,
1354 .cluster_bits = cpu_to_be32(s->cluster_bits),
1355 .size = cpu_to_be64(total_size),
1356 .crypt_method = cpu_to_be32(s->crypt_method_header),
1357 .l1_size = cpu_to_be32(s->l1_size),
1358 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1359 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1360 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1361 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1362 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1363
1364 /* Version 3 fields */
1365 .incompatible_features = cpu_to_be64(s->incompatible_features),
1366 .compatible_features = cpu_to_be64(s->compatible_features),
1367 .autoclear_features = cpu_to_be64(s->autoclear_features),
1368 .refcount_order = cpu_to_be32(s->refcount_order),
1369 .header_length = cpu_to_be32(header_length),
1370 };
1371
1372 /* For older versions, write a shorter header */
1373 switch (s->qcow_version) {
1374 case 2:
1375 ret = offsetof(QCowHeader, incompatible_features);
1376 break;
1377 case 3:
1378 ret = sizeof(*header);
1379 break;
1380 default:
1381 ret = -EINVAL;
1382 goto fail;
1383 }
1384
1385 buf += ret;
1386 buflen -= ret;
1387 memset(buf, 0, buflen);
1388
1389 /* Preserve any unknown field in the header */
1390 if (s->unknown_header_fields_size) {
1391 if (buflen < s->unknown_header_fields_size) {
1392 ret = -ENOSPC;
1393 goto fail;
1394 }
1395
1396 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1397 buf += s->unknown_header_fields_size;
1398 buflen -= s->unknown_header_fields_size;
1399 }
1400
1401 /* Backing file format header extension */
1402 if (*bs->backing_format) {
1403 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1404 bs->backing_format, strlen(bs->backing_format),
1405 buflen);
1406 if (ret < 0) {
1407 goto fail;
1408 }
1409
1410 buf += ret;
1411 buflen -= ret;
1412 }
1413
1414 /* Feature table */
1415 Qcow2Feature features[] = {
1416 {
1417 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1418 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1419 .name = "dirty bit",
1420 },
1421 {
1422 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1423 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1424 .name = "corrupt bit",
1425 },
1426 {
1427 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1428 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1429 .name = "lazy refcounts",
1430 },
1431 };
1432
1433 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1434 features, sizeof(features), buflen);
1435 if (ret < 0) {
1436 goto fail;
1437 }
1438 buf += ret;
1439 buflen -= ret;
1440
1441 /* Keep unknown header extensions */
1442 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1443 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1444 if (ret < 0) {
1445 goto fail;
1446 }
1447
1448 buf += ret;
1449 buflen -= ret;
1450 }
1451
1452 /* End of header extensions */
1453 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1454 if (ret < 0) {
1455 goto fail;
1456 }
1457
1458 buf += ret;
1459 buflen -= ret;
1460
1461 /* Backing file name */
1462 if (*bs->backing_file) {
1463 size_t backing_file_len = strlen(bs->backing_file);
1464
1465 if (buflen < backing_file_len) {
1466 ret = -ENOSPC;
1467 goto fail;
1468 }
1469
1470 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1471 strncpy(buf, bs->backing_file, buflen);
1472
1473 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1474 header->backing_file_size = cpu_to_be32(backing_file_len);
1475 }
1476
1477 /* Write the new header */
1478 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1479 if (ret < 0) {
1480 goto fail;
1481 }
1482
1483 ret = 0;
1484 fail:
1485 qemu_vfree(header);
1486 return ret;
1487 }
1488
1489 static int qcow2_change_backing_file(BlockDriverState *bs,
1490 const char *backing_file, const char *backing_fmt)
1491 {
1492 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1493 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1494
1495 return qcow2_update_header(bs);
1496 }
1497
1498 static int preallocate(BlockDriverState *bs)
1499 {
1500 uint64_t nb_sectors;
1501 uint64_t offset;
1502 uint64_t host_offset = 0;
1503 int num;
1504 int ret;
1505 QCowL2Meta *meta;
1506
1507 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1508 offset = 0;
1509
1510 while (nb_sectors) {
1511 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1512 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1513 &host_offset, &meta);
1514 if (ret < 0) {
1515 return ret;
1516 }
1517
1518 if (meta != NULL) {
1519 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1520 if (ret < 0) {
1521 qcow2_free_any_clusters(bs, meta->alloc_offset,
1522 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1523 return ret;
1524 }
1525
1526 /* There are no dependent requests, but we need to remove our
1527 * request from the list of in-flight requests */
1528 QLIST_REMOVE(meta, next_in_flight);
1529 }
1530
1531 /* TODO Preallocate data if requested */
1532
1533 nb_sectors -= num;
1534 offset += num << BDRV_SECTOR_BITS;
1535 }
1536
1537 /*
1538 * It is expected that the image file is large enough to actually contain
1539 * all of the allocated clusters (otherwise we get failing reads after
1540 * EOF). Extend the image to the last allocated sector.
1541 */
1542 if (host_offset != 0) {
1543 uint8_t buf[BDRV_SECTOR_SIZE];
1544 memset(buf, 0, BDRV_SECTOR_SIZE);
1545 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1546 buf, 1);
1547 if (ret < 0) {
1548 return ret;
1549 }
1550 }
1551
1552 return 0;
1553 }
1554
1555 static int qcow2_create2(const char *filename, int64_t total_size,
1556 const char *backing_file, const char *backing_format,
1557 int flags, size_t cluster_size, int prealloc,
1558 QEMUOptionParameter *options, int version,
1559 Error **errp)
1560 {
1561 /* Calculate cluster_bits */
1562 int cluster_bits;
1563 cluster_bits = ffs(cluster_size) - 1;
1564 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1565 (1 << cluster_bits) != cluster_size)
1566 {
1567 error_setg(errp, "Cluster size must be a power of two between %d and "
1568 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1569 return -EINVAL;
1570 }
1571
1572 /*
1573 * Open the image file and write a minimal qcow2 header.
1574 *
1575 * We keep things simple and start with a zero-sized image. We also
1576 * do without refcount blocks or a L1 table for now. We'll fix the
1577 * inconsistency later.
1578 *
1579 * We do need a refcount table because growing the refcount table means
1580 * allocating two new refcount blocks - the seconds of which would be at
1581 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1582 * size for any qcow2 image.
1583 */
1584 BlockDriverState* bs;
1585 QCowHeader *header;
1586 uint8_t* refcount_table;
1587 Error *local_err = NULL;
1588 int ret;
1589
1590 ret = bdrv_create_file(filename, options, &local_err);
1591 if (ret < 0) {
1592 error_propagate(errp, local_err);
1593 return ret;
1594 }
1595
1596 bs = NULL;
1597 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1598 NULL, &local_err);
1599 if (ret < 0) {
1600 error_propagate(errp, local_err);
1601 return ret;
1602 }
1603
1604 /* Write the header */
1605 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1606 header = g_malloc0(cluster_size);
1607 *header = (QCowHeader) {
1608 .magic = cpu_to_be32(QCOW_MAGIC),
1609 .version = cpu_to_be32(version),
1610 .cluster_bits = cpu_to_be32(cluster_bits),
1611 .size = cpu_to_be64(0),
1612 .l1_table_offset = cpu_to_be64(0),
1613 .l1_size = cpu_to_be32(0),
1614 .refcount_table_offset = cpu_to_be64(cluster_size),
1615 .refcount_table_clusters = cpu_to_be32(1),
1616 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1617 .header_length = cpu_to_be32(sizeof(*header)),
1618 };
1619
1620 if (flags & BLOCK_FLAG_ENCRYPT) {
1621 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1622 } else {
1623 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1624 }
1625
1626 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1627 header->compatible_features |=
1628 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1629 }
1630
1631 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1632 g_free(header);
1633 if (ret < 0) {
1634 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1635 goto out;
1636 }
1637
1638 /* Write an empty refcount table */
1639 refcount_table = g_malloc0(cluster_size);
1640 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
1641 g_free(refcount_table);
1642
1643 if (ret < 0) {
1644 error_setg_errno(errp, -ret, "Could not write refcount table");
1645 goto out;
1646 }
1647
1648 bdrv_unref(bs);
1649 bs = NULL;
1650
1651 /*
1652 * And now open the image and make it consistent first (i.e. increase the
1653 * refcount of the cluster that is occupied by the header and the refcount
1654 * table)
1655 */
1656 BlockDriver* drv = bdrv_find_format("qcow2");
1657 assert(drv != NULL);
1658 ret = bdrv_open(&bs, filename, NULL, NULL,
1659 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1660 if (ret < 0) {
1661 error_propagate(errp, local_err);
1662 goto out;
1663 }
1664
1665 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1666 if (ret < 0) {
1667 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1668 "header and refcount table");
1669 goto out;
1670
1671 } else if (ret != 0) {
1672 error_report("Huh, first cluster in empty image is already in use?");
1673 abort();
1674 }
1675
1676 /* Okay, now that we have a valid image, let's give it the right size */
1677 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1678 if (ret < 0) {
1679 error_setg_errno(errp, -ret, "Could not resize image");
1680 goto out;
1681 }
1682
1683 /* Want a backing file? There you go.*/
1684 if (backing_file) {
1685 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1686 if (ret < 0) {
1687 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1688 "with format '%s'", backing_file, backing_format);
1689 goto out;
1690 }
1691 }
1692
1693 /* And if we're supposed to preallocate metadata, do that now */
1694 if (prealloc) {
1695 BDRVQcowState *s = bs->opaque;
1696 qemu_co_mutex_lock(&s->lock);
1697 ret = preallocate(bs);
1698 qemu_co_mutex_unlock(&s->lock);
1699 if (ret < 0) {
1700 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1701 goto out;
1702 }
1703 }
1704
1705 bdrv_unref(bs);
1706 bs = NULL;
1707
1708 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1709 ret = bdrv_open(&bs, filename, NULL, NULL,
1710 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1711 drv, &local_err);
1712 if (local_err) {
1713 error_propagate(errp, local_err);
1714 goto out;
1715 }
1716
1717 ret = 0;
1718 out:
1719 if (bs) {
1720 bdrv_unref(bs);
1721 }
1722 return ret;
1723 }
1724
1725 static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1726 Error **errp)
1727 {
1728 const char *backing_file = NULL;
1729 const char *backing_fmt = NULL;
1730 uint64_t sectors = 0;
1731 int flags = 0;
1732 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1733 int prealloc = 0;
1734 int version = 3;
1735 Error *local_err = NULL;
1736 int ret;
1737
1738 /* Read out options */
1739 while (options && options->name) {
1740 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1741 sectors = options->value.n / 512;
1742 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1743 backing_file = options->value.s;
1744 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1745 backing_fmt = options->value.s;
1746 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1747 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1748 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1749 if (options->value.n) {
1750 cluster_size = options->value.n;
1751 }
1752 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1753 if (!options->value.s || !strcmp(options->value.s, "off")) {
1754 prealloc = 0;
1755 } else if (!strcmp(options->value.s, "metadata")) {
1756 prealloc = 1;
1757 } else {
1758 error_setg(errp, "Invalid preallocation mode: '%s'",
1759 options->value.s);
1760 return -EINVAL;
1761 }
1762 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1763 if (!options->value.s) {
1764 /* keep the default */
1765 } else if (!strcmp(options->value.s, "0.10")) {
1766 version = 2;
1767 } else if (!strcmp(options->value.s, "1.1")) {
1768 version = 3;
1769 } else {
1770 error_setg(errp, "Invalid compatibility level: '%s'",
1771 options->value.s);
1772 return -EINVAL;
1773 }
1774 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1775 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1776 }
1777 options++;
1778 }
1779
1780 if (backing_file && prealloc) {
1781 error_setg(errp, "Backing file and preallocation cannot be used at "
1782 "the same time");
1783 return -EINVAL;
1784 }
1785
1786 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1787 error_setg(errp, "Lazy refcounts only supported with compatibility "
1788 "level 1.1 and above (use compat=1.1 or greater)");
1789 return -EINVAL;
1790 }
1791
1792 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1793 cluster_size, prealloc, options, version, &local_err);
1794 if (local_err) {
1795 error_propagate(errp, local_err);
1796 }
1797 return ret;
1798 }
1799
1800 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1801 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1802 {
1803 int ret;
1804 BDRVQcowState *s = bs->opaque;
1805
1806 /* Emulate misaligned zero writes */
1807 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1808 return -ENOTSUP;
1809 }
1810
1811 /* Whatever is left can use real zero clusters */
1812 qemu_co_mutex_lock(&s->lock);
1813 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1814 nb_sectors);
1815 qemu_co_mutex_unlock(&s->lock);
1816
1817 return ret;
1818 }
1819
1820 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1821 int64_t sector_num, int nb_sectors)
1822 {
1823 int ret;
1824 BDRVQcowState *s = bs->opaque;
1825
1826 qemu_co_mutex_lock(&s->lock);
1827 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1828 nb_sectors, QCOW2_DISCARD_REQUEST);
1829 qemu_co_mutex_unlock(&s->lock);
1830 return ret;
1831 }
1832
1833 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1834 {
1835 BDRVQcowState *s = bs->opaque;
1836 int64_t new_l1_size;
1837 int ret;
1838
1839 if (offset & 511) {
1840 error_report("The new size must be a multiple of 512");
1841 return -EINVAL;
1842 }
1843
1844 /* cannot proceed if image has snapshots */
1845 if (s->nb_snapshots) {
1846 error_report("Can't resize an image which has snapshots");
1847 return -ENOTSUP;
1848 }
1849
1850 /* shrinking is currently not supported */
1851 if (offset < bs->total_sectors * 512) {
1852 error_report("qcow2 doesn't support shrinking images yet");
1853 return -ENOTSUP;
1854 }
1855
1856 new_l1_size = size_to_l1(s, offset);
1857 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1858 if (ret < 0) {
1859 return ret;
1860 }
1861
1862 /* write updated header.size */
1863 offset = cpu_to_be64(offset);
1864 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1865 &offset, sizeof(uint64_t));
1866 if (ret < 0) {
1867 return ret;
1868 }
1869
1870 s->l1_vm_state_index = new_l1_size;
1871 return 0;
1872 }
1873
1874 /* XXX: put compressed sectors first, then all the cluster aligned
1875 tables to avoid losing bytes in alignment */
1876 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1877 const uint8_t *buf, int nb_sectors)
1878 {
1879 BDRVQcowState *s = bs->opaque;
1880 z_stream strm;
1881 int ret, out_len;
1882 uint8_t *out_buf;
1883 uint64_t cluster_offset;
1884
1885 if (nb_sectors == 0) {
1886 /* align end of file to a sector boundary to ease reading with
1887 sector based I/Os */
1888 cluster_offset = bdrv_getlength(bs->file);
1889 cluster_offset = (cluster_offset + 511) & ~511;
1890 bdrv_truncate(bs->file, cluster_offset);
1891 return 0;
1892 }
1893
1894 if (nb_sectors != s->cluster_sectors) {
1895 ret = -EINVAL;
1896
1897 /* Zero-pad last write if image size is not cluster aligned */
1898 if (sector_num + nb_sectors == bs->total_sectors &&
1899 nb_sectors < s->cluster_sectors) {
1900 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1901 memset(pad_buf, 0, s->cluster_size);
1902 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1903 ret = qcow2_write_compressed(bs, sector_num,
1904 pad_buf, s->cluster_sectors);
1905 qemu_vfree(pad_buf);
1906 }
1907 return ret;
1908 }
1909
1910 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1911
1912 /* best compression, small window, no zlib header */
1913 memset(&strm, 0, sizeof(strm));
1914 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1915 Z_DEFLATED, -12,
1916 9, Z_DEFAULT_STRATEGY);
1917 if (ret != 0) {
1918 ret = -EINVAL;
1919 goto fail;
1920 }
1921
1922 strm.avail_in = s->cluster_size;
1923 strm.next_in = (uint8_t *)buf;
1924 strm.avail_out = s->cluster_size;
1925 strm.next_out = out_buf;
1926
1927 ret = deflate(&strm, Z_FINISH);
1928 if (ret != Z_STREAM_END && ret != Z_OK) {
1929 deflateEnd(&strm);
1930 ret = -EINVAL;
1931 goto fail;
1932 }
1933 out_len = strm.next_out - out_buf;
1934
1935 deflateEnd(&strm);
1936
1937 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1938 /* could not compress: write normal cluster */
1939 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1940 if (ret < 0) {
1941 goto fail;
1942 }
1943 } else {
1944 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1945 sector_num << 9, out_len);
1946 if (!cluster_offset) {
1947 ret = -EIO;
1948 goto fail;
1949 }
1950 cluster_offset &= s->cluster_offset_mask;
1951
1952 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
1953 if (ret < 0) {
1954 goto fail;
1955 }
1956
1957 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1958 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1959 if (ret < 0) {
1960 goto fail;
1961 }
1962 }
1963
1964 ret = 0;
1965 fail:
1966 g_free(out_buf);
1967 return ret;
1968 }
1969
1970 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1971 {
1972 BDRVQcowState *s = bs->opaque;
1973 int ret;
1974
1975 qemu_co_mutex_lock(&s->lock);
1976 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1977 if (ret < 0) {
1978 qemu_co_mutex_unlock(&s->lock);
1979 return ret;
1980 }
1981
1982 if (qcow2_need_accurate_refcounts(s)) {
1983 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1984 if (ret < 0) {
1985 qemu_co_mutex_unlock(&s->lock);
1986 return ret;
1987 }
1988 }
1989 qemu_co_mutex_unlock(&s->lock);
1990
1991 return 0;
1992 }
1993
1994 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1995 {
1996 BDRVQcowState *s = bs->opaque;
1997 bdi->unallocated_blocks_are_zero = true;
1998 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
1999 bdi->cluster_size = s->cluster_size;
2000 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2001 return 0;
2002 }
2003
2004 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2005 {
2006 BDRVQcowState *s = bs->opaque;
2007 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2008
2009 *spec_info = (ImageInfoSpecific){
2010 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2011 {
2012 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2013 },
2014 };
2015 if (s->qcow_version == 2) {
2016 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2017 .compat = g_strdup("0.10"),
2018 };
2019 } else if (s->qcow_version == 3) {
2020 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2021 .compat = g_strdup("1.1"),
2022 .lazy_refcounts = s->compatible_features &
2023 QCOW2_COMPAT_LAZY_REFCOUNTS,
2024 .has_lazy_refcounts = true,
2025 };
2026 }
2027
2028 return spec_info;
2029 }
2030
2031 #if 0
2032 static void dump_refcounts(BlockDriverState *bs)
2033 {
2034 BDRVQcowState *s = bs->opaque;
2035 int64_t nb_clusters, k, k1, size;
2036 int refcount;
2037
2038 size = bdrv_getlength(bs->file);
2039 nb_clusters = size_to_clusters(s, size);
2040 for(k = 0; k < nb_clusters;) {
2041 k1 = k;
2042 refcount = get_refcount(bs, k);
2043 k++;
2044 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2045 k++;
2046 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2047 k - k1);
2048 }
2049 }
2050 #endif
2051
2052 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2053 int64_t pos)
2054 {
2055 BDRVQcowState *s = bs->opaque;
2056 int64_t total_sectors = bs->total_sectors;
2057 int growable = bs->growable;
2058 bool zero_beyond_eof = bs->zero_beyond_eof;
2059 int ret;
2060
2061 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2062 bs->growable = 1;
2063 bs->zero_beyond_eof = false;
2064 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2065 bs->growable = growable;
2066 bs->zero_beyond_eof = zero_beyond_eof;
2067
2068 /* bdrv_co_do_writev will have increased the total_sectors value to include
2069 * the VM state - the VM state is however not an actual part of the block
2070 * device, therefore, we need to restore the old value. */
2071 bs->total_sectors = total_sectors;
2072
2073 return ret;
2074 }
2075
2076 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2077 int64_t pos, int size)
2078 {
2079 BDRVQcowState *s = bs->opaque;
2080 int growable = bs->growable;
2081 bool zero_beyond_eof = bs->zero_beyond_eof;
2082 int ret;
2083
2084 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2085 bs->growable = 1;
2086 bs->zero_beyond_eof = false;
2087 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2088 bs->growable = growable;
2089 bs->zero_beyond_eof = zero_beyond_eof;
2090
2091 return ret;
2092 }
2093
2094 /*
2095 * Downgrades an image's version. To achieve this, any incompatible features
2096 * have to be removed.
2097 */
2098 static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2099 {
2100 BDRVQcowState *s = bs->opaque;
2101 int current_version = s->qcow_version;
2102 int ret;
2103
2104 if (target_version == current_version) {
2105 return 0;
2106 } else if (target_version > current_version) {
2107 return -EINVAL;
2108 } else if (target_version != 2) {
2109 return -EINVAL;
2110 }
2111
2112 if (s->refcount_order != 4) {
2113 /* we would have to convert the image to a refcount_order == 4 image
2114 * here; however, since qemu (at the time of writing this) does not
2115 * support anything different than 4 anyway, there is no point in doing
2116 * so right now; however, we should error out (if qemu supports this in
2117 * the future and this code has not been adapted) */
2118 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2119 "currently not supported.");
2120 return -ENOTSUP;
2121 }
2122
2123 /* clear incompatible features */
2124 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2125 ret = qcow2_mark_clean(bs);
2126 if (ret < 0) {
2127 return ret;
2128 }
2129 }
2130
2131 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2132 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2133 * best thing to do anyway */
2134
2135 if (s->incompatible_features) {
2136 return -ENOTSUP;
2137 }
2138
2139 /* since we can ignore compatible features, we can set them to 0 as well */
2140 s->compatible_features = 0;
2141 /* if lazy refcounts have been used, they have already been fixed through
2142 * clearing the dirty flag */
2143
2144 /* clearing autoclear features is trivial */
2145 s->autoclear_features = 0;
2146
2147 ret = qcow2_expand_zero_clusters(bs);
2148 if (ret < 0) {
2149 return ret;
2150 }
2151
2152 s->qcow_version = target_version;
2153 ret = qcow2_update_header(bs);
2154 if (ret < 0) {
2155 s->qcow_version = current_version;
2156 return ret;
2157 }
2158 return 0;
2159 }
2160
2161 static int qcow2_amend_options(BlockDriverState *bs,
2162 QEMUOptionParameter *options)
2163 {
2164 BDRVQcowState *s = bs->opaque;
2165 int old_version = s->qcow_version, new_version = old_version;
2166 uint64_t new_size = 0;
2167 const char *backing_file = NULL, *backing_format = NULL;
2168 bool lazy_refcounts = s->use_lazy_refcounts;
2169 int ret;
2170 int i;
2171
2172 for (i = 0; options[i].name; i++)
2173 {
2174 if (!options[i].assigned) {
2175 /* only change explicitly defined options */
2176 continue;
2177 }
2178
2179 if (!strcmp(options[i].name, "compat")) {
2180 if (!options[i].value.s) {
2181 /* preserve default */
2182 } else if (!strcmp(options[i].value.s, "0.10")) {
2183 new_version = 2;
2184 } else if (!strcmp(options[i].value.s, "1.1")) {
2185 new_version = 3;
2186 } else {
2187 fprintf(stderr, "Unknown compatibility level %s.\n",
2188 options[i].value.s);
2189 return -EINVAL;
2190 }
2191 } else if (!strcmp(options[i].name, "preallocation")) {
2192 fprintf(stderr, "Cannot change preallocation mode.\n");
2193 return -ENOTSUP;
2194 } else if (!strcmp(options[i].name, "size")) {
2195 new_size = options[i].value.n;
2196 } else if (!strcmp(options[i].name, "backing_file")) {
2197 backing_file = options[i].value.s;
2198 } else if (!strcmp(options[i].name, "backing_fmt")) {
2199 backing_format = options[i].value.s;
2200 } else if (!strcmp(options[i].name, "encryption")) {
2201 if ((options[i].value.n != !!s->crypt_method)) {
2202 fprintf(stderr, "Changing the encryption flag is not "
2203 "supported.\n");
2204 return -ENOTSUP;
2205 }
2206 } else if (!strcmp(options[i].name, "cluster_size")) {
2207 if (options[i].value.n != s->cluster_size) {
2208 fprintf(stderr, "Changing the cluster size is not "
2209 "supported.\n");
2210 return -ENOTSUP;
2211 }
2212 } else if (!strcmp(options[i].name, "lazy_refcounts")) {
2213 lazy_refcounts = options[i].value.n;
2214 } else {
2215 /* if this assertion fails, this probably means a new option was
2216 * added without having it covered here */
2217 assert(false);
2218 }
2219 }
2220
2221 if (new_version != old_version) {
2222 if (new_version > old_version) {
2223 /* Upgrade */
2224 s->qcow_version = new_version;
2225 ret = qcow2_update_header(bs);
2226 if (ret < 0) {
2227 s->qcow_version = old_version;
2228 return ret;
2229 }
2230 } else {
2231 ret = qcow2_downgrade(bs, new_version);
2232 if (ret < 0) {
2233 return ret;
2234 }
2235 }
2236 }
2237
2238 if (backing_file || backing_format) {
2239 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2240 backing_format ?: bs->backing_format);
2241 if (ret < 0) {
2242 return ret;
2243 }
2244 }
2245
2246 if (s->use_lazy_refcounts != lazy_refcounts) {
2247 if (lazy_refcounts) {
2248 if (s->qcow_version < 3) {
2249 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2250 "level 1.1 and above (use compat=1.1 or greater)\n");
2251 return -EINVAL;
2252 }
2253 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2254 ret = qcow2_update_header(bs);
2255 if (ret < 0) {
2256 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2257 return ret;
2258 }
2259 s->use_lazy_refcounts = true;
2260 } else {
2261 /* make image clean first */
2262 ret = qcow2_mark_clean(bs);
2263 if (ret < 0) {
2264 return ret;
2265 }
2266 /* now disallow lazy refcounts */
2267 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2268 ret = qcow2_update_header(bs);
2269 if (ret < 0) {
2270 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2271 return ret;
2272 }
2273 s->use_lazy_refcounts = false;
2274 }
2275 }
2276
2277 if (new_size) {
2278 ret = bdrv_truncate(bs, new_size);
2279 if (ret < 0) {
2280 return ret;
2281 }
2282 }
2283
2284 return 0;
2285 }
2286
2287 static QEMUOptionParameter qcow2_create_options[] = {
2288 {
2289 .name = BLOCK_OPT_SIZE,
2290 .type = OPT_SIZE,
2291 .help = "Virtual disk size"
2292 },
2293 {
2294 .name = BLOCK_OPT_COMPAT_LEVEL,
2295 .type = OPT_STRING,
2296 .help = "Compatibility level (0.10 or 1.1)"
2297 },
2298 {
2299 .name = BLOCK_OPT_BACKING_FILE,
2300 .type = OPT_STRING,
2301 .help = "File name of a base image"
2302 },
2303 {
2304 .name = BLOCK_OPT_BACKING_FMT,
2305 .type = OPT_STRING,
2306 .help = "Image format of the base image"
2307 },
2308 {
2309 .name = BLOCK_OPT_ENCRYPT,
2310 .type = OPT_FLAG,
2311 .help = "Encrypt the image"
2312 },
2313 {
2314 .name = BLOCK_OPT_CLUSTER_SIZE,
2315 .type = OPT_SIZE,
2316 .help = "qcow2 cluster size",
2317 .value = { .n = DEFAULT_CLUSTER_SIZE },
2318 },
2319 {
2320 .name = BLOCK_OPT_PREALLOC,
2321 .type = OPT_STRING,
2322 .help = "Preallocation mode (allowed values: off, metadata)"
2323 },
2324 {
2325 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2326 .type = OPT_FLAG,
2327 .help = "Postpone refcount updates",
2328 },
2329 { NULL }
2330 };
2331
2332 static BlockDriver bdrv_qcow2 = {
2333 .format_name = "qcow2",
2334 .instance_size = sizeof(BDRVQcowState),
2335 .bdrv_probe = qcow2_probe,
2336 .bdrv_open = qcow2_open,
2337 .bdrv_close = qcow2_close,
2338 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2339 .bdrv_create = qcow2_create,
2340 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2341 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2342 .bdrv_set_key = qcow2_set_key,
2343
2344 .bdrv_co_readv = qcow2_co_readv,
2345 .bdrv_co_writev = qcow2_co_writev,
2346 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2347
2348 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2349 .bdrv_co_discard = qcow2_co_discard,
2350 .bdrv_truncate = qcow2_truncate,
2351 .bdrv_write_compressed = qcow2_write_compressed,
2352
2353 .bdrv_snapshot_create = qcow2_snapshot_create,
2354 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2355 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2356 .bdrv_snapshot_list = qcow2_snapshot_list,
2357 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2358 .bdrv_get_info = qcow2_get_info,
2359 .bdrv_get_specific_info = qcow2_get_specific_info,
2360
2361 .bdrv_save_vmstate = qcow2_save_vmstate,
2362 .bdrv_load_vmstate = qcow2_load_vmstate,
2363
2364 .bdrv_change_backing_file = qcow2_change_backing_file,
2365
2366 .bdrv_refresh_limits = qcow2_refresh_limits,
2367 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2368
2369 .create_options = qcow2_create_options,
2370 .bdrv_check = qcow2_check,
2371 .bdrv_amend_options = qcow2_amend_options,
2372 };
2373
2374 static void bdrv_qcow2_init(void)
2375 {
2376 bdrv_register(&bdrv_qcow2);
2377 }
2378
2379 block_init(bdrv_qcow2_init);