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