]> git.proxmox.com Git - mirror_qemu.git/blob - block/qcow2.c
Merge remote-tracking branch 'remotes/ehabkost/tags/x86-pull-request' into staging
[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/osdep.h"
25 #include "block/block_int.h"
26 #include "sysemu/block-backend.h"
27 #include "qemu/module.h"
28 #include <zlib.h>
29 #include "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qbool.h"
33 #include "qapi/util.h"
34 #include "qapi/qmp/types.h"
35 #include "qapi-event.h"
36 #include "trace.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
40
41 /*
42 Differences with QCOW:
43
44 - Support for multiple incremental snapshots.
45 - Memory management by reference counts.
46 - Clusters which have a reference count of one have the bit
47 QCOW_OFLAG_COPIED to optimize write performance.
48 - Size of compressed clusters is stored in sectors to reduce bit usage
49 in the cluster offsets.
50 - Support for storing additional data (such as the VM state) in the
51 snapshots.
52 - If a backing store is used, the cluster size is not constrained
53 (could be backported to QCOW).
54 - L2 tables have always a size of one cluster.
55 */
56
57
58 typedef struct {
59 uint32_t magic;
60 uint32_t len;
61 } QEMU_PACKED QCowExtension;
62
63 #define QCOW2_EXT_MAGIC_END 0
64 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
65 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
66
67 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
68 {
69 const QCowHeader *cow_header = (const void *)buf;
70
71 if (buf_size >= sizeof(QCowHeader) &&
72 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
73 be32_to_cpu(cow_header->version) >= 2)
74 return 100;
75 else
76 return 0;
77 }
78
79
80 /*
81 * read qcow2 extension and fill bs
82 * start reading from start_offset
83 * finish reading upon magic of value 0 or when end_offset reached
84 * unknown magic is skipped (future extension this version knows nothing about)
85 * return 0 upon success, non-0 otherwise
86 */
87 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
88 uint64_t end_offset, void **p_feature_table,
89 Error **errp)
90 {
91 BDRVQcow2State *s = bs->opaque;
92 QCowExtension ext;
93 uint64_t offset;
94 int ret;
95
96 #ifdef DEBUG_EXT
97 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
98 #endif
99 offset = start_offset;
100 while (offset < end_offset) {
101
102 #ifdef DEBUG_EXT
103 /* Sanity check */
104 if (offset > s->cluster_size)
105 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
106
107 printf("attempting to read extended header in offset %lu\n", offset);
108 #endif
109
110 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
111 if (ret < 0) {
112 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
113 "pread fail from offset %" PRIu64, offset);
114 return 1;
115 }
116 be32_to_cpus(&ext.magic);
117 be32_to_cpus(&ext.len);
118 offset += sizeof(ext);
119 #ifdef DEBUG_EXT
120 printf("ext.magic = 0x%x\n", ext.magic);
121 #endif
122 if (offset > end_offset || ext.len > end_offset - offset) {
123 error_setg(errp, "Header extension too large");
124 return -EINVAL;
125 }
126
127 switch (ext.magic) {
128 case QCOW2_EXT_MAGIC_END:
129 return 0;
130
131 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
132 if (ext.len >= sizeof(bs->backing_format)) {
133 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
134 " too large (>=%zu)", ext.len,
135 sizeof(bs->backing_format));
136 return 2;
137 }
138 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
139 if (ret < 0) {
140 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
141 "Could not read format name");
142 return 3;
143 }
144 bs->backing_format[ext.len] = '\0';
145 s->image_backing_format = g_strdup(bs->backing_format);
146 #ifdef DEBUG_EXT
147 printf("Qcow2: Got format extension %s\n", bs->backing_format);
148 #endif
149 break;
150
151 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
152 if (p_feature_table != NULL) {
153 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
154 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
155 if (ret < 0) {
156 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
157 "Could not read table");
158 return ret;
159 }
160
161 *p_feature_table = feature_table;
162 }
163 break;
164
165 default:
166 /* unknown magic - save it in case we need to rewrite the header */
167 {
168 Qcow2UnknownHeaderExtension *uext;
169
170 uext = g_malloc0(sizeof(*uext) + ext.len);
171 uext->magic = ext.magic;
172 uext->len = ext.len;
173 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
174
175 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
176 if (ret < 0) {
177 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
178 "Could not read data");
179 return ret;
180 }
181 }
182 break;
183 }
184
185 offset += ((ext.len + 7) & ~7);
186 }
187
188 return 0;
189 }
190
191 static void cleanup_unknown_header_ext(BlockDriverState *bs)
192 {
193 BDRVQcow2State *s = bs->opaque;
194 Qcow2UnknownHeaderExtension *uext, *next;
195
196 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
197 QLIST_REMOVE(uext, next);
198 g_free(uext);
199 }
200 }
201
202 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
203 uint64_t mask)
204 {
205 char *features = g_strdup("");
206 char *old;
207
208 while (table && table->name[0] != '\0') {
209 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
210 if (mask & (1ULL << table->bit)) {
211 old = features;
212 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
213 table->name);
214 g_free(old);
215 mask &= ~(1ULL << table->bit);
216 }
217 }
218 table++;
219 }
220
221 if (mask) {
222 old = features;
223 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
224 old, *old ? ", " : "", mask);
225 g_free(old);
226 }
227
228 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
229 g_free(features);
230 }
231
232 /*
233 * Sets the dirty bit and flushes afterwards if necessary.
234 *
235 * The incompatible_features bit is only set if the image file header was
236 * updated successfully. Therefore it is not required to check the return
237 * value of this function.
238 */
239 int qcow2_mark_dirty(BlockDriverState *bs)
240 {
241 BDRVQcow2State *s = bs->opaque;
242 uint64_t val;
243 int ret;
244
245 assert(s->qcow_version >= 3);
246
247 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
248 return 0; /* already dirty */
249 }
250
251 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
252 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
253 &val, sizeof(val));
254 if (ret < 0) {
255 return ret;
256 }
257 ret = bdrv_flush(bs->file->bs);
258 if (ret < 0) {
259 return ret;
260 }
261
262 /* Only treat image as dirty if the header was updated successfully */
263 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
264 return 0;
265 }
266
267 /*
268 * Clears the dirty bit and flushes before if necessary. Only call this
269 * function when there are no pending requests, it does not guard against
270 * concurrent requests dirtying the image.
271 */
272 static int qcow2_mark_clean(BlockDriverState *bs)
273 {
274 BDRVQcow2State *s = bs->opaque;
275
276 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
277 int ret;
278
279 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
280
281 ret = bdrv_flush(bs);
282 if (ret < 0) {
283 return ret;
284 }
285
286 return qcow2_update_header(bs);
287 }
288 return 0;
289 }
290
291 /*
292 * Marks the image as corrupt.
293 */
294 int qcow2_mark_corrupt(BlockDriverState *bs)
295 {
296 BDRVQcow2State *s = bs->opaque;
297
298 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
299 return qcow2_update_header(bs);
300 }
301
302 /*
303 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
304 * before if necessary.
305 */
306 int qcow2_mark_consistent(BlockDriverState *bs)
307 {
308 BDRVQcow2State *s = bs->opaque;
309
310 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
311 int ret = bdrv_flush(bs);
312 if (ret < 0) {
313 return ret;
314 }
315
316 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
317 return qcow2_update_header(bs);
318 }
319 return 0;
320 }
321
322 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
323 BdrvCheckMode fix)
324 {
325 int ret = qcow2_check_refcounts(bs, result, fix);
326 if (ret < 0) {
327 return ret;
328 }
329
330 if (fix && result->check_errors == 0 && result->corruptions == 0) {
331 ret = qcow2_mark_clean(bs);
332 if (ret < 0) {
333 return ret;
334 }
335 return qcow2_mark_consistent(bs);
336 }
337 return ret;
338 }
339
340 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
341 uint64_t entries, size_t entry_len)
342 {
343 BDRVQcow2State *s = bs->opaque;
344 uint64_t size;
345
346 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
347 * because values will be passed to qemu functions taking int64_t. */
348 if (entries > INT64_MAX / entry_len) {
349 return -EINVAL;
350 }
351
352 size = entries * entry_len;
353
354 if (INT64_MAX - size < offset) {
355 return -EINVAL;
356 }
357
358 /* Tables must be cluster aligned */
359 if (offset & (s->cluster_size - 1)) {
360 return -EINVAL;
361 }
362
363 return 0;
364 }
365
366 static QemuOptsList qcow2_runtime_opts = {
367 .name = "qcow2",
368 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
369 .desc = {
370 {
371 .name = QCOW2_OPT_LAZY_REFCOUNTS,
372 .type = QEMU_OPT_BOOL,
373 .help = "Postpone refcount updates",
374 },
375 {
376 .name = QCOW2_OPT_DISCARD_REQUEST,
377 .type = QEMU_OPT_BOOL,
378 .help = "Pass guest discard requests to the layer below",
379 },
380 {
381 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
382 .type = QEMU_OPT_BOOL,
383 .help = "Generate discard requests when snapshot related space "
384 "is freed",
385 },
386 {
387 .name = QCOW2_OPT_DISCARD_OTHER,
388 .type = QEMU_OPT_BOOL,
389 .help = "Generate discard requests when other clusters are freed",
390 },
391 {
392 .name = QCOW2_OPT_OVERLAP,
393 .type = QEMU_OPT_STRING,
394 .help = "Selects which overlap checks to perform from a range of "
395 "templates (none, constant, cached, all)",
396 },
397 {
398 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
399 .type = QEMU_OPT_STRING,
400 .help = "Selects which overlap checks to perform from a range of "
401 "templates (none, constant, cached, all)",
402 },
403 {
404 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
405 .type = QEMU_OPT_BOOL,
406 .help = "Check for unintended writes into the main qcow2 header",
407 },
408 {
409 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
410 .type = QEMU_OPT_BOOL,
411 .help = "Check for unintended writes into the active L1 table",
412 },
413 {
414 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
415 .type = QEMU_OPT_BOOL,
416 .help = "Check for unintended writes into an active L2 table",
417 },
418 {
419 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
420 .type = QEMU_OPT_BOOL,
421 .help = "Check for unintended writes into the refcount table",
422 },
423 {
424 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
425 .type = QEMU_OPT_BOOL,
426 .help = "Check for unintended writes into a refcount block",
427 },
428 {
429 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
430 .type = QEMU_OPT_BOOL,
431 .help = "Check for unintended writes into the snapshot table",
432 },
433 {
434 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
435 .type = QEMU_OPT_BOOL,
436 .help = "Check for unintended writes into an inactive L1 table",
437 },
438 {
439 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
440 .type = QEMU_OPT_BOOL,
441 .help = "Check for unintended writes into an inactive L2 table",
442 },
443 {
444 .name = QCOW2_OPT_CACHE_SIZE,
445 .type = QEMU_OPT_SIZE,
446 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
447 "cache size",
448 },
449 {
450 .name = QCOW2_OPT_L2_CACHE_SIZE,
451 .type = QEMU_OPT_SIZE,
452 .help = "Maximum L2 table cache size",
453 },
454 {
455 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
456 .type = QEMU_OPT_SIZE,
457 .help = "Maximum refcount block cache size",
458 },
459 {
460 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
461 .type = QEMU_OPT_NUMBER,
462 .help = "Clean unused cache entries after this time (in seconds)",
463 },
464 { /* end of list */ }
465 },
466 };
467
468 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
469 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
470 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
471 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
472 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
473 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
474 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
475 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
476 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
477 };
478
479 static void cache_clean_timer_cb(void *opaque)
480 {
481 BlockDriverState *bs = opaque;
482 BDRVQcow2State *s = bs->opaque;
483 qcow2_cache_clean_unused(bs, s->l2_table_cache);
484 qcow2_cache_clean_unused(bs, s->refcount_block_cache);
485 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
486 (int64_t) s->cache_clean_interval * 1000);
487 }
488
489 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
490 {
491 BDRVQcow2State *s = bs->opaque;
492 if (s->cache_clean_interval > 0) {
493 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
494 SCALE_MS, cache_clean_timer_cb,
495 bs);
496 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
497 (int64_t) s->cache_clean_interval * 1000);
498 }
499 }
500
501 static void cache_clean_timer_del(BlockDriverState *bs)
502 {
503 BDRVQcow2State *s = bs->opaque;
504 if (s->cache_clean_timer) {
505 timer_del(s->cache_clean_timer);
506 timer_free(s->cache_clean_timer);
507 s->cache_clean_timer = NULL;
508 }
509 }
510
511 static void qcow2_detach_aio_context(BlockDriverState *bs)
512 {
513 cache_clean_timer_del(bs);
514 }
515
516 static void qcow2_attach_aio_context(BlockDriverState *bs,
517 AioContext *new_context)
518 {
519 cache_clean_timer_init(bs, new_context);
520 }
521
522 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
523 uint64_t *l2_cache_size,
524 uint64_t *refcount_cache_size, Error **errp)
525 {
526 BDRVQcow2State *s = bs->opaque;
527 uint64_t combined_cache_size;
528 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
529
530 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
531 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
532 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
533
534 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
535 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
536 *refcount_cache_size = qemu_opt_get_size(opts,
537 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
538
539 if (combined_cache_size_set) {
540 if (l2_cache_size_set && refcount_cache_size_set) {
541 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
542 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
543 "the same time");
544 return;
545 } else if (*l2_cache_size > combined_cache_size) {
546 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
547 QCOW2_OPT_CACHE_SIZE);
548 return;
549 } else if (*refcount_cache_size > combined_cache_size) {
550 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
551 QCOW2_OPT_CACHE_SIZE);
552 return;
553 }
554
555 if (l2_cache_size_set) {
556 *refcount_cache_size = combined_cache_size - *l2_cache_size;
557 } else if (refcount_cache_size_set) {
558 *l2_cache_size = combined_cache_size - *refcount_cache_size;
559 } else {
560 *refcount_cache_size = combined_cache_size
561 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
562 *l2_cache_size = combined_cache_size - *refcount_cache_size;
563 }
564 } else {
565 if (!l2_cache_size_set && !refcount_cache_size_set) {
566 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
567 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
568 * s->cluster_size);
569 *refcount_cache_size = *l2_cache_size
570 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
571 } else if (!l2_cache_size_set) {
572 *l2_cache_size = *refcount_cache_size
573 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
574 } else if (!refcount_cache_size_set) {
575 *refcount_cache_size = *l2_cache_size
576 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
577 }
578 }
579 }
580
581 typedef struct Qcow2ReopenState {
582 Qcow2Cache *l2_table_cache;
583 Qcow2Cache *refcount_block_cache;
584 bool use_lazy_refcounts;
585 int overlap_check;
586 bool discard_passthrough[QCOW2_DISCARD_MAX];
587 uint64_t cache_clean_interval;
588 } Qcow2ReopenState;
589
590 static int qcow2_update_options_prepare(BlockDriverState *bs,
591 Qcow2ReopenState *r,
592 QDict *options, int flags,
593 Error **errp)
594 {
595 BDRVQcow2State *s = bs->opaque;
596 QemuOpts *opts = NULL;
597 const char *opt_overlap_check, *opt_overlap_check_template;
598 int overlap_check_template = 0;
599 uint64_t l2_cache_size, refcount_cache_size;
600 int i;
601 Error *local_err = NULL;
602 int ret;
603
604 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
605 qemu_opts_absorb_qdict(opts, options, &local_err);
606 if (local_err) {
607 error_propagate(errp, local_err);
608 ret = -EINVAL;
609 goto fail;
610 }
611
612 /* get L2 table/refcount block cache size from command line options */
613 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
614 &local_err);
615 if (local_err) {
616 error_propagate(errp, local_err);
617 ret = -EINVAL;
618 goto fail;
619 }
620
621 l2_cache_size /= s->cluster_size;
622 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
623 l2_cache_size = MIN_L2_CACHE_SIZE;
624 }
625 if (l2_cache_size > INT_MAX) {
626 error_setg(errp, "L2 cache size too big");
627 ret = -EINVAL;
628 goto fail;
629 }
630
631 refcount_cache_size /= s->cluster_size;
632 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
633 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
634 }
635 if (refcount_cache_size > INT_MAX) {
636 error_setg(errp, "Refcount cache size too big");
637 ret = -EINVAL;
638 goto fail;
639 }
640
641 /* alloc new L2 table/refcount block cache, flush old one */
642 if (s->l2_table_cache) {
643 ret = qcow2_cache_flush(bs, s->l2_table_cache);
644 if (ret) {
645 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
646 goto fail;
647 }
648 }
649
650 if (s->refcount_block_cache) {
651 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
652 if (ret) {
653 error_setg_errno(errp, -ret,
654 "Failed to flush the refcount block cache");
655 goto fail;
656 }
657 }
658
659 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
660 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
661 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
662 error_setg(errp, "Could not allocate metadata caches");
663 ret = -ENOMEM;
664 goto fail;
665 }
666
667 /* New interval for cache cleanup timer */
668 r->cache_clean_interval =
669 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
670 s->cache_clean_interval);
671 if (r->cache_clean_interval > UINT_MAX) {
672 error_setg(errp, "Cache clean interval too big");
673 ret = -EINVAL;
674 goto fail;
675 }
676
677 /* lazy-refcounts; flush if going from enabled to disabled */
678 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
679 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
680 if (r->use_lazy_refcounts && s->qcow_version < 3) {
681 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
682 "qemu 1.1 compatibility level");
683 ret = -EINVAL;
684 goto fail;
685 }
686
687 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
688 ret = qcow2_mark_clean(bs);
689 if (ret < 0) {
690 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
691 goto fail;
692 }
693 }
694
695 /* Overlap check options */
696 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
697 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
698 if (opt_overlap_check_template && opt_overlap_check &&
699 strcmp(opt_overlap_check_template, opt_overlap_check))
700 {
701 error_setg(errp, "Conflicting values for qcow2 options '"
702 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
703 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
704 ret = -EINVAL;
705 goto fail;
706 }
707 if (!opt_overlap_check) {
708 opt_overlap_check = opt_overlap_check_template ?: "cached";
709 }
710
711 if (!strcmp(opt_overlap_check, "none")) {
712 overlap_check_template = 0;
713 } else if (!strcmp(opt_overlap_check, "constant")) {
714 overlap_check_template = QCOW2_OL_CONSTANT;
715 } else if (!strcmp(opt_overlap_check, "cached")) {
716 overlap_check_template = QCOW2_OL_CACHED;
717 } else if (!strcmp(opt_overlap_check, "all")) {
718 overlap_check_template = QCOW2_OL_ALL;
719 } else {
720 error_setg(errp, "Unsupported value '%s' for qcow2 option "
721 "'overlap-check'. Allowed are any of the following: "
722 "none, constant, cached, all", opt_overlap_check);
723 ret = -EINVAL;
724 goto fail;
725 }
726
727 r->overlap_check = 0;
728 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
729 /* overlap-check defines a template bitmask, but every flag may be
730 * overwritten through the associated boolean option */
731 r->overlap_check |=
732 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
733 overlap_check_template & (1 << i)) << i;
734 }
735
736 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
737 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
738 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
739 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
740 flags & BDRV_O_UNMAP);
741 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
742 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
743 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
744 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
745
746 ret = 0;
747 fail:
748 qemu_opts_del(opts);
749 opts = NULL;
750 return ret;
751 }
752
753 static void qcow2_update_options_commit(BlockDriverState *bs,
754 Qcow2ReopenState *r)
755 {
756 BDRVQcow2State *s = bs->opaque;
757 int i;
758
759 if (s->l2_table_cache) {
760 qcow2_cache_destroy(bs, s->l2_table_cache);
761 }
762 if (s->refcount_block_cache) {
763 qcow2_cache_destroy(bs, s->refcount_block_cache);
764 }
765 s->l2_table_cache = r->l2_table_cache;
766 s->refcount_block_cache = r->refcount_block_cache;
767
768 s->overlap_check = r->overlap_check;
769 s->use_lazy_refcounts = r->use_lazy_refcounts;
770
771 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
772 s->discard_passthrough[i] = r->discard_passthrough[i];
773 }
774
775 if (s->cache_clean_interval != r->cache_clean_interval) {
776 cache_clean_timer_del(bs);
777 s->cache_clean_interval = r->cache_clean_interval;
778 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
779 }
780 }
781
782 static void qcow2_update_options_abort(BlockDriverState *bs,
783 Qcow2ReopenState *r)
784 {
785 if (r->l2_table_cache) {
786 qcow2_cache_destroy(bs, r->l2_table_cache);
787 }
788 if (r->refcount_block_cache) {
789 qcow2_cache_destroy(bs, r->refcount_block_cache);
790 }
791 }
792
793 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
794 int flags, Error **errp)
795 {
796 Qcow2ReopenState r = {};
797 int ret;
798
799 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
800 if (ret >= 0) {
801 qcow2_update_options_commit(bs, &r);
802 } else {
803 qcow2_update_options_abort(bs, &r);
804 }
805
806 return ret;
807 }
808
809 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
810 Error **errp)
811 {
812 BDRVQcow2State *s = bs->opaque;
813 unsigned int len, i;
814 int ret = 0;
815 QCowHeader header;
816 Error *local_err = NULL;
817 uint64_t ext_end;
818 uint64_t l1_vm_state_index;
819
820 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
821 if (ret < 0) {
822 error_setg_errno(errp, -ret, "Could not read qcow2 header");
823 goto fail;
824 }
825 be32_to_cpus(&header.magic);
826 be32_to_cpus(&header.version);
827 be64_to_cpus(&header.backing_file_offset);
828 be32_to_cpus(&header.backing_file_size);
829 be64_to_cpus(&header.size);
830 be32_to_cpus(&header.cluster_bits);
831 be32_to_cpus(&header.crypt_method);
832 be64_to_cpus(&header.l1_table_offset);
833 be32_to_cpus(&header.l1_size);
834 be64_to_cpus(&header.refcount_table_offset);
835 be32_to_cpus(&header.refcount_table_clusters);
836 be64_to_cpus(&header.snapshots_offset);
837 be32_to_cpus(&header.nb_snapshots);
838
839 if (header.magic != QCOW_MAGIC) {
840 error_setg(errp, "Image is not in qcow2 format");
841 ret = -EINVAL;
842 goto fail;
843 }
844 if (header.version < 2 || header.version > 3) {
845 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
846 ret = -ENOTSUP;
847 goto fail;
848 }
849
850 s->qcow_version = header.version;
851
852 /* Initialise cluster size */
853 if (header.cluster_bits < MIN_CLUSTER_BITS ||
854 header.cluster_bits > MAX_CLUSTER_BITS) {
855 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
856 header.cluster_bits);
857 ret = -EINVAL;
858 goto fail;
859 }
860
861 s->cluster_bits = header.cluster_bits;
862 s->cluster_size = 1 << s->cluster_bits;
863 s->cluster_sectors = 1 << (s->cluster_bits - 9);
864
865 /* Initialise version 3 header fields */
866 if (header.version == 2) {
867 header.incompatible_features = 0;
868 header.compatible_features = 0;
869 header.autoclear_features = 0;
870 header.refcount_order = 4;
871 header.header_length = 72;
872 } else {
873 be64_to_cpus(&header.incompatible_features);
874 be64_to_cpus(&header.compatible_features);
875 be64_to_cpus(&header.autoclear_features);
876 be32_to_cpus(&header.refcount_order);
877 be32_to_cpus(&header.header_length);
878
879 if (header.header_length < 104) {
880 error_setg(errp, "qcow2 header too short");
881 ret = -EINVAL;
882 goto fail;
883 }
884 }
885
886 if (header.header_length > s->cluster_size) {
887 error_setg(errp, "qcow2 header exceeds cluster size");
888 ret = -EINVAL;
889 goto fail;
890 }
891
892 if (header.header_length > sizeof(header)) {
893 s->unknown_header_fields_size = header.header_length - sizeof(header);
894 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
895 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
896 s->unknown_header_fields_size);
897 if (ret < 0) {
898 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
899 "fields");
900 goto fail;
901 }
902 }
903
904 if (header.backing_file_offset > s->cluster_size) {
905 error_setg(errp, "Invalid backing file offset");
906 ret = -EINVAL;
907 goto fail;
908 }
909
910 if (header.backing_file_offset) {
911 ext_end = header.backing_file_offset;
912 } else {
913 ext_end = 1 << header.cluster_bits;
914 }
915
916 /* Handle feature bits */
917 s->incompatible_features = header.incompatible_features;
918 s->compatible_features = header.compatible_features;
919 s->autoclear_features = header.autoclear_features;
920
921 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
922 void *feature_table = NULL;
923 qcow2_read_extensions(bs, header.header_length, ext_end,
924 &feature_table, NULL);
925 report_unsupported_feature(errp, feature_table,
926 s->incompatible_features &
927 ~QCOW2_INCOMPAT_MASK);
928 ret = -ENOTSUP;
929 g_free(feature_table);
930 goto fail;
931 }
932
933 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
934 /* Corrupt images may not be written to unless they are being repaired
935 */
936 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
937 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
938 "read/write");
939 ret = -EACCES;
940 goto fail;
941 }
942 }
943
944 /* Check support for various header values */
945 if (header.refcount_order > 6) {
946 error_setg(errp, "Reference count entry width too large; may not "
947 "exceed 64 bits");
948 ret = -EINVAL;
949 goto fail;
950 }
951 s->refcount_order = header.refcount_order;
952 s->refcount_bits = 1 << s->refcount_order;
953 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
954 s->refcount_max += s->refcount_max - 1;
955
956 if (header.crypt_method > QCOW_CRYPT_AES) {
957 error_setg(errp, "Unsupported encryption method: %" PRIu32,
958 header.crypt_method);
959 ret = -EINVAL;
960 goto fail;
961 }
962 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128,
963 QCRYPTO_CIPHER_MODE_CBC)) {
964 error_setg(errp, "AES cipher not available");
965 ret = -EINVAL;
966 goto fail;
967 }
968 s->crypt_method_header = header.crypt_method;
969 if (s->crypt_method_header) {
970 if (bdrv_uses_whitelist() &&
971 s->crypt_method_header == QCOW_CRYPT_AES) {
972 error_setg(errp,
973 "Use of AES-CBC encrypted qcow2 images is no longer "
974 "supported in system emulators");
975 error_append_hint(errp,
976 "You can use 'qemu-img convert' to convert your "
977 "image to an alternative supported format, such "
978 "as unencrypted qcow2, or raw with the LUKS "
979 "format instead.\n");
980 ret = -ENOSYS;
981 goto fail;
982 }
983
984 bs->encrypted = true;
985 }
986
987 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
988 s->l2_size = 1 << s->l2_bits;
989 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
990 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
991 s->refcount_block_size = 1 << s->refcount_block_bits;
992 bs->total_sectors = header.size / 512;
993 s->csize_shift = (62 - (s->cluster_bits - 8));
994 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
995 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
996
997 s->refcount_table_offset = header.refcount_table_offset;
998 s->refcount_table_size =
999 header.refcount_table_clusters << (s->cluster_bits - 3);
1000
1001 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
1002 error_setg(errp, "Reference count table too large");
1003 ret = -EINVAL;
1004 goto fail;
1005 }
1006
1007 ret = validate_table_offset(bs, s->refcount_table_offset,
1008 s->refcount_table_size, sizeof(uint64_t));
1009 if (ret < 0) {
1010 error_setg(errp, "Invalid reference count table offset");
1011 goto fail;
1012 }
1013
1014 /* Snapshot table offset/length */
1015 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1016 error_setg(errp, "Too many snapshots");
1017 ret = -EINVAL;
1018 goto fail;
1019 }
1020
1021 ret = validate_table_offset(bs, header.snapshots_offset,
1022 header.nb_snapshots,
1023 sizeof(QCowSnapshotHeader));
1024 if (ret < 0) {
1025 error_setg(errp, "Invalid snapshot table offset");
1026 goto fail;
1027 }
1028
1029 /* read the level 1 table */
1030 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1031 error_setg(errp, "Active L1 table too large");
1032 ret = -EFBIG;
1033 goto fail;
1034 }
1035 s->l1_size = header.l1_size;
1036
1037 l1_vm_state_index = size_to_l1(s, header.size);
1038 if (l1_vm_state_index > INT_MAX) {
1039 error_setg(errp, "Image is too big");
1040 ret = -EFBIG;
1041 goto fail;
1042 }
1043 s->l1_vm_state_index = l1_vm_state_index;
1044
1045 /* the L1 table must contain at least enough entries to put
1046 header.size bytes */
1047 if (s->l1_size < s->l1_vm_state_index) {
1048 error_setg(errp, "L1 table is too small");
1049 ret = -EINVAL;
1050 goto fail;
1051 }
1052
1053 ret = validate_table_offset(bs, header.l1_table_offset,
1054 header.l1_size, sizeof(uint64_t));
1055 if (ret < 0) {
1056 error_setg(errp, "Invalid L1 table offset");
1057 goto fail;
1058 }
1059 s->l1_table_offset = header.l1_table_offset;
1060
1061
1062 if (s->l1_size > 0) {
1063 s->l1_table = qemu_try_blockalign(bs->file->bs,
1064 align_offset(s->l1_size * sizeof(uint64_t), 512));
1065 if (s->l1_table == NULL) {
1066 error_setg(errp, "Could not allocate L1 table");
1067 ret = -ENOMEM;
1068 goto fail;
1069 }
1070 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1071 s->l1_size * sizeof(uint64_t));
1072 if (ret < 0) {
1073 error_setg_errno(errp, -ret, "Could not read L1 table");
1074 goto fail;
1075 }
1076 for(i = 0;i < s->l1_size; i++) {
1077 be64_to_cpus(&s->l1_table[i]);
1078 }
1079 }
1080
1081 /* Parse driver-specific options */
1082 ret = qcow2_update_options(bs, options, flags, errp);
1083 if (ret < 0) {
1084 goto fail;
1085 }
1086
1087 s->cluster_cache = g_malloc(s->cluster_size);
1088 /* one more sector for decompressed data alignment */
1089 s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1090 * s->cluster_size + 512);
1091 if (s->cluster_data == NULL) {
1092 error_setg(errp, "Could not allocate temporary cluster buffer");
1093 ret = -ENOMEM;
1094 goto fail;
1095 }
1096
1097 s->cluster_cache_offset = -1;
1098 s->flags = flags;
1099
1100 ret = qcow2_refcount_init(bs);
1101 if (ret != 0) {
1102 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1103 goto fail;
1104 }
1105
1106 QLIST_INIT(&s->cluster_allocs);
1107 QTAILQ_INIT(&s->discards);
1108
1109 /* read qcow2 extensions */
1110 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1111 &local_err)) {
1112 error_propagate(errp, local_err);
1113 ret = -EINVAL;
1114 goto fail;
1115 }
1116
1117 /* read the backing file name */
1118 if (header.backing_file_offset != 0) {
1119 len = header.backing_file_size;
1120 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1121 len >= sizeof(bs->backing_file)) {
1122 error_setg(errp, "Backing file name too long");
1123 ret = -EINVAL;
1124 goto fail;
1125 }
1126 ret = bdrv_pread(bs->file, header.backing_file_offset,
1127 bs->backing_file, len);
1128 if (ret < 0) {
1129 error_setg_errno(errp, -ret, "Could not read backing file name");
1130 goto fail;
1131 }
1132 bs->backing_file[len] = '\0';
1133 s->image_backing_file = g_strdup(bs->backing_file);
1134 }
1135
1136 /* Internal snapshots */
1137 s->snapshots_offset = header.snapshots_offset;
1138 s->nb_snapshots = header.nb_snapshots;
1139
1140 ret = qcow2_read_snapshots(bs);
1141 if (ret < 0) {
1142 error_setg_errno(errp, -ret, "Could not read snapshots");
1143 goto fail;
1144 }
1145
1146 /* Clear unknown autoclear feature bits */
1147 if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1148 s->autoclear_features = 0;
1149 ret = qcow2_update_header(bs);
1150 if (ret < 0) {
1151 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1152 goto fail;
1153 }
1154 }
1155
1156 /* Initialise locks */
1157 qemu_co_mutex_init(&s->lock);
1158 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1159
1160 /* Repair image if dirty */
1161 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1162 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1163 BdrvCheckResult result = {0};
1164
1165 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1166 if (ret < 0) {
1167 error_setg_errno(errp, -ret, "Could not repair dirty image");
1168 goto fail;
1169 }
1170 }
1171
1172 #ifdef DEBUG_ALLOC
1173 {
1174 BdrvCheckResult result = {0};
1175 qcow2_check_refcounts(bs, &result, 0);
1176 }
1177 #endif
1178 return ret;
1179
1180 fail:
1181 g_free(s->unknown_header_fields);
1182 cleanup_unknown_header_ext(bs);
1183 qcow2_free_snapshots(bs);
1184 qcow2_refcount_close(bs);
1185 qemu_vfree(s->l1_table);
1186 /* else pre-write overlap checks in cache_destroy may crash */
1187 s->l1_table = NULL;
1188 cache_clean_timer_del(bs);
1189 if (s->l2_table_cache) {
1190 qcow2_cache_destroy(bs, s->l2_table_cache);
1191 }
1192 if (s->refcount_block_cache) {
1193 qcow2_cache_destroy(bs, s->refcount_block_cache);
1194 }
1195 g_free(s->cluster_cache);
1196 qemu_vfree(s->cluster_data);
1197 return ret;
1198 }
1199
1200 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1201 {
1202 BDRVQcow2State *s = bs->opaque;
1203
1204 if (bs->encrypted) {
1205 /* Encryption works on a sector granularity */
1206 bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1207 }
1208 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1209 }
1210
1211 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1212 {
1213 BDRVQcow2State *s = bs->opaque;
1214 uint8_t keybuf[16];
1215 int len, i;
1216 Error *err = NULL;
1217
1218 memset(keybuf, 0, 16);
1219 len = strlen(key);
1220 if (len > 16)
1221 len = 16;
1222 /* XXX: we could compress the chars to 7 bits to increase
1223 entropy */
1224 for(i = 0;i < len;i++) {
1225 keybuf[i] = key[i];
1226 }
1227 assert(bs->encrypted);
1228
1229 qcrypto_cipher_free(s->cipher);
1230 s->cipher = qcrypto_cipher_new(
1231 QCRYPTO_CIPHER_ALG_AES_128,
1232 QCRYPTO_CIPHER_MODE_CBC,
1233 keybuf, G_N_ELEMENTS(keybuf),
1234 &err);
1235
1236 if (!s->cipher) {
1237 /* XXX would be nice if errors in this method could
1238 * be properly propagate to the caller. Would need
1239 * the bdrv_set_key() API signature to be fixed. */
1240 error_free(err);
1241 return -1;
1242 }
1243 return 0;
1244 }
1245
1246 static int qcow2_reopen_prepare(BDRVReopenState *state,
1247 BlockReopenQueue *queue, Error **errp)
1248 {
1249 Qcow2ReopenState *r;
1250 int ret;
1251
1252 r = g_new0(Qcow2ReopenState, 1);
1253 state->opaque = r;
1254
1255 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1256 state->flags, errp);
1257 if (ret < 0) {
1258 goto fail;
1259 }
1260
1261 /* We need to write out any unwritten data if we reopen read-only. */
1262 if ((state->flags & BDRV_O_RDWR) == 0) {
1263 ret = bdrv_flush(state->bs);
1264 if (ret < 0) {
1265 goto fail;
1266 }
1267
1268 ret = qcow2_mark_clean(state->bs);
1269 if (ret < 0) {
1270 goto fail;
1271 }
1272 }
1273
1274 return 0;
1275
1276 fail:
1277 qcow2_update_options_abort(state->bs, r);
1278 g_free(r);
1279 return ret;
1280 }
1281
1282 static void qcow2_reopen_commit(BDRVReopenState *state)
1283 {
1284 qcow2_update_options_commit(state->bs, state->opaque);
1285 g_free(state->opaque);
1286 }
1287
1288 static void qcow2_reopen_abort(BDRVReopenState *state)
1289 {
1290 qcow2_update_options_abort(state->bs, state->opaque);
1291 g_free(state->opaque);
1292 }
1293
1294 static void qcow2_join_options(QDict *options, QDict *old_options)
1295 {
1296 bool has_new_overlap_template =
1297 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1298 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1299 bool has_new_total_cache_size =
1300 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1301 bool has_all_cache_options;
1302
1303 /* New overlap template overrides all old overlap options */
1304 if (has_new_overlap_template) {
1305 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1306 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1307 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1308 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1309 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1310 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1311 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1312 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1313 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1314 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1315 }
1316
1317 /* New total cache size overrides all old options */
1318 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1319 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1320 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1321 }
1322
1323 qdict_join(options, old_options, false);
1324
1325 /*
1326 * If after merging all cache size options are set, an old total size is
1327 * overwritten. Do keep all options, however, if all three are new. The
1328 * resulting error message is what we want to happen.
1329 */
1330 has_all_cache_options =
1331 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1332 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1333 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1334
1335 if (has_all_cache_options && !has_new_total_cache_size) {
1336 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1337 }
1338 }
1339
1340 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1341 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1342 {
1343 BDRVQcow2State *s = bs->opaque;
1344 uint64_t cluster_offset;
1345 int index_in_cluster, ret;
1346 unsigned int bytes;
1347 int64_t status = 0;
1348
1349 bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);
1350 qemu_co_mutex_lock(&s->lock);
1351 ret = qcow2_get_cluster_offset(bs, sector_num << 9, &bytes,
1352 &cluster_offset);
1353 qemu_co_mutex_unlock(&s->lock);
1354 if (ret < 0) {
1355 return ret;
1356 }
1357
1358 *pnum = bytes >> BDRV_SECTOR_BITS;
1359
1360 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1361 !s->cipher) {
1362 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1363 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1364 *file = bs->file->bs;
1365 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1366 }
1367 if (ret == QCOW2_CLUSTER_ZERO) {
1368 status |= BDRV_BLOCK_ZERO;
1369 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1370 status |= BDRV_BLOCK_DATA;
1371 }
1372 return status;
1373 }
1374
1375 /* handle reading after the end of the backing file */
1376 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1377 int64_t offset, int bytes)
1378 {
1379 uint64_t bs_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1380 int n1;
1381
1382 if ((offset + bytes) <= bs_size) {
1383 return bytes;
1384 }
1385
1386 if (offset >= bs_size) {
1387 n1 = 0;
1388 } else {
1389 n1 = bs_size - offset;
1390 }
1391
1392 qemu_iovec_memset(qiov, n1, 0, bytes - n1);
1393
1394 return n1;
1395 }
1396
1397 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1398 uint64_t bytes, QEMUIOVector *qiov,
1399 int flags)
1400 {
1401 BDRVQcow2State *s = bs->opaque;
1402 int offset_in_cluster, n1;
1403 int ret;
1404 unsigned int cur_bytes; /* number of bytes in current iteration */
1405 uint64_t cluster_offset = 0;
1406 uint64_t bytes_done = 0;
1407 QEMUIOVector hd_qiov;
1408 uint8_t *cluster_data = NULL;
1409
1410 qemu_iovec_init(&hd_qiov, qiov->niov);
1411
1412 qemu_co_mutex_lock(&s->lock);
1413
1414 while (bytes != 0) {
1415
1416 /* prepare next request */
1417 cur_bytes = MIN(bytes, INT_MAX);
1418 if (s->cipher) {
1419 cur_bytes = MIN(cur_bytes,
1420 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1421 }
1422
1423 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1424 if (ret < 0) {
1425 goto fail;
1426 }
1427
1428 offset_in_cluster = offset_into_cluster(s, offset);
1429
1430 qemu_iovec_reset(&hd_qiov);
1431 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1432
1433 switch (ret) {
1434 case QCOW2_CLUSTER_UNALLOCATED:
1435
1436 if (bs->backing) {
1437 /* read from the base image */
1438 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1439 offset, cur_bytes);
1440 if (n1 > 0) {
1441 QEMUIOVector local_qiov;
1442
1443 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1444 qemu_iovec_concat(&local_qiov, &hd_qiov, 0, n1);
1445
1446 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1447 qemu_co_mutex_unlock(&s->lock);
1448 ret = bdrv_co_preadv(bs->backing, offset, n1,
1449 &local_qiov, 0);
1450 qemu_co_mutex_lock(&s->lock);
1451
1452 qemu_iovec_destroy(&local_qiov);
1453
1454 if (ret < 0) {
1455 goto fail;
1456 }
1457 }
1458 } else {
1459 /* Note: in this case, no need to wait */
1460 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1461 }
1462 break;
1463
1464 case QCOW2_CLUSTER_ZERO:
1465 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1466 break;
1467
1468 case QCOW2_CLUSTER_COMPRESSED:
1469 /* add AIO support for compressed blocks ? */
1470 ret = qcow2_decompress_cluster(bs, cluster_offset);
1471 if (ret < 0) {
1472 goto fail;
1473 }
1474
1475 qemu_iovec_from_buf(&hd_qiov, 0,
1476 s->cluster_cache + offset_in_cluster,
1477 cur_bytes);
1478 break;
1479
1480 case QCOW2_CLUSTER_NORMAL:
1481 if ((cluster_offset & 511) != 0) {
1482 ret = -EIO;
1483 goto fail;
1484 }
1485
1486 if (bs->encrypted) {
1487 assert(s->cipher);
1488
1489 /*
1490 * For encrypted images, read everything into a temporary
1491 * contiguous buffer on which the AES functions can work.
1492 */
1493 if (!cluster_data) {
1494 cluster_data =
1495 qemu_try_blockalign(bs->file->bs,
1496 QCOW_MAX_CRYPT_CLUSTERS
1497 * s->cluster_size);
1498 if (cluster_data == NULL) {
1499 ret = -ENOMEM;
1500 goto fail;
1501 }
1502 }
1503
1504 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1505 qemu_iovec_reset(&hd_qiov);
1506 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1507 }
1508
1509 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1510 qemu_co_mutex_unlock(&s->lock);
1511 ret = bdrv_co_preadv(bs->file,
1512 cluster_offset + offset_in_cluster,
1513 cur_bytes, &hd_qiov, 0);
1514 qemu_co_mutex_lock(&s->lock);
1515 if (ret < 0) {
1516 goto fail;
1517 }
1518 if (bs->encrypted) {
1519 assert(s->cipher);
1520 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1521 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1522 Error *err = NULL;
1523 if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1524 cluster_data, cluster_data,
1525 cur_bytes >> BDRV_SECTOR_BITS,
1526 false, &err) < 0) {
1527 error_free(err);
1528 ret = -EIO;
1529 goto fail;
1530 }
1531 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1532 }
1533 break;
1534
1535 default:
1536 g_assert_not_reached();
1537 ret = -EIO;
1538 goto fail;
1539 }
1540
1541 bytes -= cur_bytes;
1542 offset += cur_bytes;
1543 bytes_done += cur_bytes;
1544 }
1545 ret = 0;
1546
1547 fail:
1548 qemu_co_mutex_unlock(&s->lock);
1549
1550 qemu_iovec_destroy(&hd_qiov);
1551 qemu_vfree(cluster_data);
1552
1553 return ret;
1554 }
1555
1556 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1557 uint64_t bytes, QEMUIOVector *qiov,
1558 int flags)
1559 {
1560 BDRVQcow2State *s = bs->opaque;
1561 int offset_in_cluster;
1562 int ret;
1563 unsigned int cur_bytes; /* number of sectors in current iteration */
1564 uint64_t cluster_offset;
1565 QEMUIOVector hd_qiov;
1566 uint64_t bytes_done = 0;
1567 uint8_t *cluster_data = NULL;
1568 QCowL2Meta *l2meta = NULL;
1569
1570 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1571
1572 qemu_iovec_init(&hd_qiov, qiov->niov);
1573
1574 s->cluster_cache_offset = -1; /* disable compressed cache */
1575
1576 qemu_co_mutex_lock(&s->lock);
1577
1578 while (bytes != 0) {
1579
1580 l2meta = NULL;
1581
1582 trace_qcow2_writev_start_part(qemu_coroutine_self());
1583 offset_in_cluster = offset_into_cluster(s, offset);
1584 cur_bytes = MIN(bytes, INT_MAX);
1585 if (bs->encrypted) {
1586 cur_bytes = MIN(cur_bytes,
1587 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1588 - offset_in_cluster);
1589 }
1590
1591 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1592 &cluster_offset, &l2meta);
1593 if (ret < 0) {
1594 goto fail;
1595 }
1596
1597 assert((cluster_offset & 511) == 0);
1598
1599 qemu_iovec_reset(&hd_qiov);
1600 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1601
1602 if (bs->encrypted) {
1603 Error *err = NULL;
1604 assert(s->cipher);
1605 if (!cluster_data) {
1606 cluster_data = qemu_try_blockalign(bs->file->bs,
1607 QCOW_MAX_CRYPT_CLUSTERS
1608 * s->cluster_size);
1609 if (cluster_data == NULL) {
1610 ret = -ENOMEM;
1611 goto fail;
1612 }
1613 }
1614
1615 assert(hd_qiov.size <=
1616 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1617 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1618
1619 if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1620 cluster_data, cluster_data,
1621 cur_bytes >>BDRV_SECTOR_BITS,
1622 true, &err) < 0) {
1623 error_free(err);
1624 ret = -EIO;
1625 goto fail;
1626 }
1627
1628 qemu_iovec_reset(&hd_qiov);
1629 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1630 }
1631
1632 ret = qcow2_pre_write_overlap_check(bs, 0,
1633 cluster_offset + offset_in_cluster, cur_bytes);
1634 if (ret < 0) {
1635 goto fail;
1636 }
1637
1638 qemu_co_mutex_unlock(&s->lock);
1639 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1640 trace_qcow2_writev_data(qemu_coroutine_self(),
1641 cluster_offset + offset_in_cluster);
1642 ret = bdrv_co_pwritev(bs->file,
1643 cluster_offset + offset_in_cluster,
1644 cur_bytes, &hd_qiov, 0);
1645 qemu_co_mutex_lock(&s->lock);
1646 if (ret < 0) {
1647 goto fail;
1648 }
1649
1650 while (l2meta != NULL) {
1651 QCowL2Meta *next;
1652
1653 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1654 if (ret < 0) {
1655 goto fail;
1656 }
1657
1658 /* Take the request off the list of running requests */
1659 if (l2meta->nb_clusters != 0) {
1660 QLIST_REMOVE(l2meta, next_in_flight);
1661 }
1662
1663 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1664
1665 next = l2meta->next;
1666 g_free(l2meta);
1667 l2meta = next;
1668 }
1669
1670 bytes -= cur_bytes;
1671 offset += cur_bytes;
1672 bytes_done += cur_bytes;
1673 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
1674 }
1675 ret = 0;
1676
1677 fail:
1678 qemu_co_mutex_unlock(&s->lock);
1679
1680 while (l2meta != NULL) {
1681 QCowL2Meta *next;
1682
1683 if (l2meta->nb_clusters != 0) {
1684 QLIST_REMOVE(l2meta, next_in_flight);
1685 }
1686 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1687
1688 next = l2meta->next;
1689 g_free(l2meta);
1690 l2meta = next;
1691 }
1692
1693 qemu_iovec_destroy(&hd_qiov);
1694 qemu_vfree(cluster_data);
1695 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1696
1697 return ret;
1698 }
1699
1700 static int qcow2_inactivate(BlockDriverState *bs)
1701 {
1702 BDRVQcow2State *s = bs->opaque;
1703 int ret, result = 0;
1704
1705 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1706 if (ret) {
1707 result = ret;
1708 error_report("Failed to flush the L2 table cache: %s",
1709 strerror(-ret));
1710 }
1711
1712 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1713 if (ret) {
1714 result = ret;
1715 error_report("Failed to flush the refcount block cache: %s",
1716 strerror(-ret));
1717 }
1718
1719 if (result == 0) {
1720 qcow2_mark_clean(bs);
1721 }
1722
1723 return result;
1724 }
1725
1726 static void qcow2_close(BlockDriverState *bs)
1727 {
1728 BDRVQcow2State *s = bs->opaque;
1729 qemu_vfree(s->l1_table);
1730 /* else pre-write overlap checks in cache_destroy may crash */
1731 s->l1_table = NULL;
1732
1733 if (!(s->flags & BDRV_O_INACTIVE)) {
1734 qcow2_inactivate(bs);
1735 }
1736
1737 cache_clean_timer_del(bs);
1738 qcow2_cache_destroy(bs, s->l2_table_cache);
1739 qcow2_cache_destroy(bs, s->refcount_block_cache);
1740
1741 qcrypto_cipher_free(s->cipher);
1742 s->cipher = NULL;
1743
1744 g_free(s->unknown_header_fields);
1745 cleanup_unknown_header_ext(bs);
1746
1747 g_free(s->image_backing_file);
1748 g_free(s->image_backing_format);
1749
1750 g_free(s->cluster_cache);
1751 qemu_vfree(s->cluster_data);
1752 qcow2_refcount_close(bs);
1753 qcow2_free_snapshots(bs);
1754 }
1755
1756 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1757 {
1758 BDRVQcow2State *s = bs->opaque;
1759 int flags = s->flags;
1760 QCryptoCipher *cipher = NULL;
1761 QDict *options;
1762 Error *local_err = NULL;
1763 int ret;
1764
1765 /*
1766 * Backing files are read-only which makes all of their metadata immutable,
1767 * that means we don't have to worry about reopening them here.
1768 */
1769
1770 cipher = s->cipher;
1771 s->cipher = NULL;
1772
1773 qcow2_close(bs);
1774
1775 memset(s, 0, sizeof(BDRVQcow2State));
1776 options = qdict_clone_shallow(bs->options);
1777
1778 flags &= ~BDRV_O_INACTIVE;
1779 ret = qcow2_open(bs, options, flags, &local_err);
1780 QDECREF(options);
1781 if (local_err) {
1782 error_propagate(errp, local_err);
1783 error_prepend(errp, "Could not reopen qcow2 layer: ");
1784 bs->drv = NULL;
1785 return;
1786 } else if (ret < 0) {
1787 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1788 bs->drv = NULL;
1789 return;
1790 }
1791
1792 s->cipher = cipher;
1793 }
1794
1795 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1796 size_t len, size_t buflen)
1797 {
1798 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1799 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1800
1801 if (buflen < ext_len) {
1802 return -ENOSPC;
1803 }
1804
1805 *ext_backing_fmt = (QCowExtension) {
1806 .magic = cpu_to_be32(magic),
1807 .len = cpu_to_be32(len),
1808 };
1809
1810 if (len) {
1811 memcpy(buf + sizeof(QCowExtension), s, len);
1812 }
1813
1814 return ext_len;
1815 }
1816
1817 /*
1818 * Updates the qcow2 header, including the variable length parts of it, i.e.
1819 * the backing file name and all extensions. qcow2 was not designed to allow
1820 * such changes, so if we run out of space (we can only use the first cluster)
1821 * this function may fail.
1822 *
1823 * Returns 0 on success, -errno in error cases.
1824 */
1825 int qcow2_update_header(BlockDriverState *bs)
1826 {
1827 BDRVQcow2State *s = bs->opaque;
1828 QCowHeader *header;
1829 char *buf;
1830 size_t buflen = s->cluster_size;
1831 int ret;
1832 uint64_t total_size;
1833 uint32_t refcount_table_clusters;
1834 size_t header_length;
1835 Qcow2UnknownHeaderExtension *uext;
1836
1837 buf = qemu_blockalign(bs, buflen);
1838
1839 /* Header structure */
1840 header = (QCowHeader*) buf;
1841
1842 if (buflen < sizeof(*header)) {
1843 ret = -ENOSPC;
1844 goto fail;
1845 }
1846
1847 header_length = sizeof(*header) + s->unknown_header_fields_size;
1848 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1849 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1850
1851 *header = (QCowHeader) {
1852 /* Version 2 fields */
1853 .magic = cpu_to_be32(QCOW_MAGIC),
1854 .version = cpu_to_be32(s->qcow_version),
1855 .backing_file_offset = 0,
1856 .backing_file_size = 0,
1857 .cluster_bits = cpu_to_be32(s->cluster_bits),
1858 .size = cpu_to_be64(total_size),
1859 .crypt_method = cpu_to_be32(s->crypt_method_header),
1860 .l1_size = cpu_to_be32(s->l1_size),
1861 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1862 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1863 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1864 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1865 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1866
1867 /* Version 3 fields */
1868 .incompatible_features = cpu_to_be64(s->incompatible_features),
1869 .compatible_features = cpu_to_be64(s->compatible_features),
1870 .autoclear_features = cpu_to_be64(s->autoclear_features),
1871 .refcount_order = cpu_to_be32(s->refcount_order),
1872 .header_length = cpu_to_be32(header_length),
1873 };
1874
1875 /* For older versions, write a shorter header */
1876 switch (s->qcow_version) {
1877 case 2:
1878 ret = offsetof(QCowHeader, incompatible_features);
1879 break;
1880 case 3:
1881 ret = sizeof(*header);
1882 break;
1883 default:
1884 ret = -EINVAL;
1885 goto fail;
1886 }
1887
1888 buf += ret;
1889 buflen -= ret;
1890 memset(buf, 0, buflen);
1891
1892 /* Preserve any unknown field in the header */
1893 if (s->unknown_header_fields_size) {
1894 if (buflen < s->unknown_header_fields_size) {
1895 ret = -ENOSPC;
1896 goto fail;
1897 }
1898
1899 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1900 buf += s->unknown_header_fields_size;
1901 buflen -= s->unknown_header_fields_size;
1902 }
1903
1904 /* Backing file format header extension */
1905 if (s->image_backing_format) {
1906 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1907 s->image_backing_format,
1908 strlen(s->image_backing_format),
1909 buflen);
1910 if (ret < 0) {
1911 goto fail;
1912 }
1913
1914 buf += ret;
1915 buflen -= ret;
1916 }
1917
1918 /* Feature table */
1919 if (s->qcow_version >= 3) {
1920 Qcow2Feature features[] = {
1921 {
1922 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1923 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1924 .name = "dirty bit",
1925 },
1926 {
1927 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1928 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1929 .name = "corrupt bit",
1930 },
1931 {
1932 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1933 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1934 .name = "lazy refcounts",
1935 },
1936 };
1937
1938 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1939 features, sizeof(features), buflen);
1940 if (ret < 0) {
1941 goto fail;
1942 }
1943 buf += ret;
1944 buflen -= ret;
1945 }
1946
1947 /* Keep unknown header extensions */
1948 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1949 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1950 if (ret < 0) {
1951 goto fail;
1952 }
1953
1954 buf += ret;
1955 buflen -= ret;
1956 }
1957
1958 /* End of header extensions */
1959 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1960 if (ret < 0) {
1961 goto fail;
1962 }
1963
1964 buf += ret;
1965 buflen -= ret;
1966
1967 /* Backing file name */
1968 if (s->image_backing_file) {
1969 size_t backing_file_len = strlen(s->image_backing_file);
1970
1971 if (buflen < backing_file_len) {
1972 ret = -ENOSPC;
1973 goto fail;
1974 }
1975
1976 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1977 strncpy(buf, s->image_backing_file, buflen);
1978
1979 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1980 header->backing_file_size = cpu_to_be32(backing_file_len);
1981 }
1982
1983 /* Write the new header */
1984 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1985 if (ret < 0) {
1986 goto fail;
1987 }
1988
1989 ret = 0;
1990 fail:
1991 qemu_vfree(header);
1992 return ret;
1993 }
1994
1995 static int qcow2_change_backing_file(BlockDriverState *bs,
1996 const char *backing_file, const char *backing_fmt)
1997 {
1998 BDRVQcow2State *s = bs->opaque;
1999
2000 if (backing_file && strlen(backing_file) > 1023) {
2001 return -EINVAL;
2002 }
2003
2004 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2005 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2006
2007 g_free(s->image_backing_file);
2008 g_free(s->image_backing_format);
2009
2010 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2011 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2012
2013 return qcow2_update_header(bs);
2014 }
2015
2016 static int preallocate(BlockDriverState *bs)
2017 {
2018 uint64_t bytes;
2019 uint64_t offset;
2020 uint64_t host_offset = 0;
2021 unsigned int cur_bytes;
2022 int ret;
2023 QCowL2Meta *meta;
2024
2025 bytes = bdrv_getlength(bs);
2026 offset = 0;
2027
2028 while (bytes) {
2029 cur_bytes = MIN(bytes, INT_MAX);
2030 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2031 &host_offset, &meta);
2032 if (ret < 0) {
2033 return ret;
2034 }
2035
2036 while (meta) {
2037 QCowL2Meta *next = meta->next;
2038
2039 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2040 if (ret < 0) {
2041 qcow2_free_any_clusters(bs, meta->alloc_offset,
2042 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2043 return ret;
2044 }
2045
2046 /* There are no dependent requests, but we need to remove our
2047 * request from the list of in-flight requests */
2048 QLIST_REMOVE(meta, next_in_flight);
2049
2050 g_free(meta);
2051 meta = next;
2052 }
2053
2054 /* TODO Preallocate data if requested */
2055
2056 bytes -= cur_bytes;
2057 offset += cur_bytes;
2058 }
2059
2060 /*
2061 * It is expected that the image file is large enough to actually contain
2062 * all of the allocated clusters (otherwise we get failing reads after
2063 * EOF). Extend the image to the last allocated sector.
2064 */
2065 if (host_offset != 0) {
2066 uint8_t data = 0;
2067 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2068 &data, 1);
2069 if (ret < 0) {
2070 return ret;
2071 }
2072 }
2073
2074 return 0;
2075 }
2076
2077 static int qcow2_create2(const char *filename, int64_t total_size,
2078 const char *backing_file, const char *backing_format,
2079 int flags, size_t cluster_size, PreallocMode prealloc,
2080 QemuOpts *opts, int version, int refcount_order,
2081 Error **errp)
2082 {
2083 int cluster_bits;
2084 QDict *options;
2085
2086 /* Calculate cluster_bits */
2087 cluster_bits = ctz32(cluster_size);
2088 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2089 (1 << cluster_bits) != cluster_size)
2090 {
2091 error_setg(errp, "Cluster size must be a power of two between %d and "
2092 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2093 return -EINVAL;
2094 }
2095
2096 /*
2097 * Open the image file and write a minimal qcow2 header.
2098 *
2099 * We keep things simple and start with a zero-sized image. We also
2100 * do without refcount blocks or a L1 table for now. We'll fix the
2101 * inconsistency later.
2102 *
2103 * We do need a refcount table because growing the refcount table means
2104 * allocating two new refcount blocks - the seconds of which would be at
2105 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2106 * size for any qcow2 image.
2107 */
2108 BlockBackend *blk;
2109 QCowHeader *header;
2110 uint64_t* refcount_table;
2111 Error *local_err = NULL;
2112 int ret;
2113
2114 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2115 /* Note: The following calculation does not need to be exact; if it is a
2116 * bit off, either some bytes will be "leaked" (which is fine) or we
2117 * will need to increase the file size by some bytes (which is fine,
2118 * too, as long as the bulk is allocated here). Therefore, using
2119 * floating point arithmetic is fine. */
2120 int64_t meta_size = 0;
2121 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
2122 int64_t aligned_total_size = align_offset(total_size, cluster_size);
2123 int refblock_bits, refblock_size;
2124 /* refcount entry size in bytes */
2125 double rces = (1 << refcount_order) / 8.;
2126
2127 /* see qcow2_open() */
2128 refblock_bits = cluster_bits - (refcount_order - 3);
2129 refblock_size = 1 << refblock_bits;
2130
2131 /* header: 1 cluster */
2132 meta_size += cluster_size;
2133
2134 /* total size of L2 tables */
2135 nl2e = aligned_total_size / cluster_size;
2136 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2137 meta_size += nl2e * sizeof(uint64_t);
2138
2139 /* total size of L1 tables */
2140 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2141 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2142 meta_size += nl1e * sizeof(uint64_t);
2143
2144 /* total size of refcount blocks
2145 *
2146 * note: every host cluster is reference-counted, including metadata
2147 * (even refcount blocks are recursively included).
2148 * Let:
2149 * a = total_size (this is the guest disk size)
2150 * m = meta size not including refcount blocks and refcount tables
2151 * c = cluster size
2152 * y1 = number of refcount blocks entries
2153 * y2 = meta size including everything
2154 * rces = refcount entry size in bytes
2155 * then,
2156 * y1 = (y2 + a)/c
2157 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2158 * we can get y1:
2159 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2160 */
2161 nrefblocke = (aligned_total_size + meta_size + cluster_size)
2162 / (cluster_size - rces - rces * sizeof(uint64_t)
2163 / cluster_size);
2164 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
2165
2166 /* total size of refcount tables */
2167 nreftablee = nrefblocke / refblock_size;
2168 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
2169 meta_size += nreftablee * sizeof(uint64_t);
2170
2171 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2172 aligned_total_size + meta_size, &error_abort);
2173 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2174 &error_abort);
2175 }
2176
2177 ret = bdrv_create_file(filename, opts, &local_err);
2178 if (ret < 0) {
2179 error_propagate(errp, local_err);
2180 return ret;
2181 }
2182
2183 blk = blk_new_open(filename, NULL, NULL,
2184 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
2185 if (blk == NULL) {
2186 error_propagate(errp, local_err);
2187 return -EIO;
2188 }
2189
2190 blk_set_allow_write_beyond_eof(blk, true);
2191
2192 /* Write the header */
2193 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2194 header = g_malloc0(cluster_size);
2195 *header = (QCowHeader) {
2196 .magic = cpu_to_be32(QCOW_MAGIC),
2197 .version = cpu_to_be32(version),
2198 .cluster_bits = cpu_to_be32(cluster_bits),
2199 .size = cpu_to_be64(0),
2200 .l1_table_offset = cpu_to_be64(0),
2201 .l1_size = cpu_to_be32(0),
2202 .refcount_table_offset = cpu_to_be64(cluster_size),
2203 .refcount_table_clusters = cpu_to_be32(1),
2204 .refcount_order = cpu_to_be32(refcount_order),
2205 .header_length = cpu_to_be32(sizeof(*header)),
2206 };
2207
2208 if (flags & BLOCK_FLAG_ENCRYPT) {
2209 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2210 } else {
2211 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2212 }
2213
2214 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2215 header->compatible_features |=
2216 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2217 }
2218
2219 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2220 g_free(header);
2221 if (ret < 0) {
2222 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2223 goto out;
2224 }
2225
2226 /* Write a refcount table with one refcount block */
2227 refcount_table = g_malloc0(2 * cluster_size);
2228 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2229 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2230 g_free(refcount_table);
2231
2232 if (ret < 0) {
2233 error_setg_errno(errp, -ret, "Could not write refcount table");
2234 goto out;
2235 }
2236
2237 blk_unref(blk);
2238 blk = NULL;
2239
2240 /*
2241 * And now open the image and make it consistent first (i.e. increase the
2242 * refcount of the cluster that is occupied by the header and the refcount
2243 * table)
2244 */
2245 options = qdict_new();
2246 qdict_put(options, "driver", qstring_from_str("qcow2"));
2247 blk = blk_new_open(filename, NULL, options,
2248 BDRV_O_RDWR | BDRV_O_NO_FLUSH, &local_err);
2249 if (blk == NULL) {
2250 error_propagate(errp, local_err);
2251 ret = -EIO;
2252 goto out;
2253 }
2254
2255 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2256 if (ret < 0) {
2257 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2258 "header and refcount table");
2259 goto out;
2260
2261 } else if (ret != 0) {
2262 error_report("Huh, first cluster in empty image is already in use?");
2263 abort();
2264 }
2265
2266 /* Create a full header (including things like feature table) */
2267 ret = qcow2_update_header(blk_bs(blk));
2268 if (ret < 0) {
2269 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2270 goto out;
2271 }
2272
2273 /* Okay, now that we have a valid image, let's give it the right size */
2274 ret = blk_truncate(blk, total_size);
2275 if (ret < 0) {
2276 error_setg_errno(errp, -ret, "Could not resize image");
2277 goto out;
2278 }
2279
2280 /* Want a backing file? There you go.*/
2281 if (backing_file) {
2282 ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2283 if (ret < 0) {
2284 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2285 "with format '%s'", backing_file, backing_format);
2286 goto out;
2287 }
2288 }
2289
2290 /* And if we're supposed to preallocate metadata, do that now */
2291 if (prealloc != PREALLOC_MODE_OFF) {
2292 BDRVQcow2State *s = blk_bs(blk)->opaque;
2293 qemu_co_mutex_lock(&s->lock);
2294 ret = preallocate(blk_bs(blk));
2295 qemu_co_mutex_unlock(&s->lock);
2296 if (ret < 0) {
2297 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2298 goto out;
2299 }
2300 }
2301
2302 blk_unref(blk);
2303 blk = NULL;
2304
2305 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2306 options = qdict_new();
2307 qdict_put(options, "driver", qstring_from_str("qcow2"));
2308 blk = blk_new_open(filename, NULL, options,
2309 BDRV_O_RDWR | BDRV_O_NO_BACKING, &local_err);
2310 if (blk == NULL) {
2311 error_propagate(errp, local_err);
2312 ret = -EIO;
2313 goto out;
2314 }
2315
2316 ret = 0;
2317 out:
2318 if (blk) {
2319 blk_unref(blk);
2320 }
2321 return ret;
2322 }
2323
2324 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2325 {
2326 char *backing_file = NULL;
2327 char *backing_fmt = NULL;
2328 char *buf = NULL;
2329 uint64_t size = 0;
2330 int flags = 0;
2331 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2332 PreallocMode prealloc;
2333 int version = 3;
2334 uint64_t refcount_bits = 16;
2335 int refcount_order;
2336 Error *local_err = NULL;
2337 int ret;
2338
2339 /* Read out options */
2340 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2341 BDRV_SECTOR_SIZE);
2342 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2343 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2344 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2345 flags |= BLOCK_FLAG_ENCRYPT;
2346 }
2347 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2348 DEFAULT_CLUSTER_SIZE);
2349 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2350 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2351 PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2352 &local_err);
2353 if (local_err) {
2354 error_propagate(errp, local_err);
2355 ret = -EINVAL;
2356 goto finish;
2357 }
2358 g_free(buf);
2359 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2360 if (!buf) {
2361 /* keep the default */
2362 } else if (!strcmp(buf, "0.10")) {
2363 version = 2;
2364 } else if (!strcmp(buf, "1.1")) {
2365 version = 3;
2366 } else {
2367 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2368 ret = -EINVAL;
2369 goto finish;
2370 }
2371
2372 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2373 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2374 }
2375
2376 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2377 error_setg(errp, "Backing file and preallocation cannot be used at "
2378 "the same time");
2379 ret = -EINVAL;
2380 goto finish;
2381 }
2382
2383 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2384 error_setg(errp, "Lazy refcounts only supported with compatibility "
2385 "level 1.1 and above (use compat=1.1 or greater)");
2386 ret = -EINVAL;
2387 goto finish;
2388 }
2389
2390 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2391 refcount_bits);
2392 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2393 error_setg(errp, "Refcount width must be a power of two and may not "
2394 "exceed 64 bits");
2395 ret = -EINVAL;
2396 goto finish;
2397 }
2398
2399 if (version < 3 && refcount_bits != 16) {
2400 error_setg(errp, "Different refcount widths than 16 bits require "
2401 "compatibility level 1.1 or above (use compat=1.1 or "
2402 "greater)");
2403 ret = -EINVAL;
2404 goto finish;
2405 }
2406
2407 refcount_order = ctz32(refcount_bits);
2408
2409 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2410 cluster_size, prealloc, opts, version, refcount_order,
2411 &local_err);
2412 error_propagate(errp, local_err);
2413
2414 finish:
2415 g_free(backing_file);
2416 g_free(backing_fmt);
2417 g_free(buf);
2418 return ret;
2419 }
2420
2421
2422 static bool is_zero_sectors(BlockDriverState *bs, int64_t start,
2423 uint32_t count)
2424 {
2425 int nr;
2426 BlockDriverState *file;
2427 int64_t res;
2428
2429 if (!count) {
2430 return true;
2431 }
2432 res = bdrv_get_block_status_above(bs, NULL, start, count,
2433 &nr, &file);
2434 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == count;
2435 }
2436
2437 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
2438 int64_t offset, int count, BdrvRequestFlags flags)
2439 {
2440 int ret;
2441 BDRVQcow2State *s = bs->opaque;
2442
2443 uint32_t head = offset % s->cluster_size;
2444 uint32_t tail = (offset + count) % s->cluster_size;
2445
2446 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, count);
2447
2448 if (head || tail) {
2449 int64_t cl_start = (offset - head) >> BDRV_SECTOR_BITS;
2450 uint64_t off;
2451 unsigned int nr;
2452
2453 assert(head + count <= s->cluster_size);
2454
2455 /* check whether remainder of cluster already reads as zero */
2456 if (!(is_zero_sectors(bs, cl_start,
2457 DIV_ROUND_UP(head, BDRV_SECTOR_SIZE)) &&
2458 is_zero_sectors(bs, (offset + count) >> BDRV_SECTOR_BITS,
2459 DIV_ROUND_UP(-tail & (s->cluster_size - 1),
2460 BDRV_SECTOR_SIZE)))) {
2461 return -ENOTSUP;
2462 }
2463
2464 qemu_co_mutex_lock(&s->lock);
2465 /* We can have new write after previous check */
2466 offset = cl_start << BDRV_SECTOR_BITS;
2467 count = s->cluster_size;
2468 nr = s->cluster_size;
2469 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
2470 if (ret != QCOW2_CLUSTER_UNALLOCATED && ret != QCOW2_CLUSTER_ZERO) {
2471 qemu_co_mutex_unlock(&s->lock);
2472 return -ENOTSUP;
2473 }
2474 } else {
2475 qemu_co_mutex_lock(&s->lock);
2476 }
2477
2478 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, count);
2479
2480 /* Whatever is left can use real zero clusters */
2481 ret = qcow2_zero_clusters(bs, offset, count >> BDRV_SECTOR_BITS, flags);
2482 qemu_co_mutex_unlock(&s->lock);
2483
2484 return ret;
2485 }
2486
2487 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
2488 int64_t offset, int count)
2489 {
2490 int ret;
2491 BDRVQcow2State *s = bs->opaque;
2492
2493 qemu_co_mutex_lock(&s->lock);
2494 ret = qcow2_discard_clusters(bs, offset, count >> BDRV_SECTOR_BITS,
2495 QCOW2_DISCARD_REQUEST, false);
2496 qemu_co_mutex_unlock(&s->lock);
2497 return ret;
2498 }
2499
2500 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2501 {
2502 BDRVQcow2State *s = bs->opaque;
2503 int64_t new_l1_size;
2504 int ret;
2505
2506 if (offset & 511) {
2507 error_report("The new size must be a multiple of 512");
2508 return -EINVAL;
2509 }
2510
2511 /* cannot proceed if image has snapshots */
2512 if (s->nb_snapshots) {
2513 error_report("Can't resize an image which has snapshots");
2514 return -ENOTSUP;
2515 }
2516
2517 /* shrinking is currently not supported */
2518 if (offset < bs->total_sectors * 512) {
2519 error_report("qcow2 doesn't support shrinking images yet");
2520 return -ENOTSUP;
2521 }
2522
2523 new_l1_size = size_to_l1(s, offset);
2524 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2525 if (ret < 0) {
2526 return ret;
2527 }
2528
2529 /* write updated header.size */
2530 offset = cpu_to_be64(offset);
2531 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2532 &offset, sizeof(uint64_t));
2533 if (ret < 0) {
2534 return ret;
2535 }
2536
2537 s->l1_vm_state_index = new_l1_size;
2538 return 0;
2539 }
2540
2541 /* XXX: put compressed sectors first, then all the cluster aligned
2542 tables to avoid losing bytes in alignment */
2543 static coroutine_fn int
2544 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
2545 uint64_t bytes, QEMUIOVector *qiov)
2546 {
2547 BDRVQcow2State *s = bs->opaque;
2548 QEMUIOVector hd_qiov;
2549 struct iovec iov;
2550 z_stream strm;
2551 int ret, out_len;
2552 uint8_t *buf, *out_buf;
2553 uint64_t cluster_offset;
2554
2555 if (bytes == 0) {
2556 /* align end of file to a sector boundary to ease reading with
2557 sector based I/Os */
2558 cluster_offset = bdrv_getlength(bs->file->bs);
2559 return bdrv_truncate(bs->file->bs, cluster_offset);
2560 }
2561
2562 buf = qemu_blockalign(bs, s->cluster_size);
2563 if (bytes != s->cluster_size) {
2564 if (bytes > s->cluster_size ||
2565 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
2566 {
2567 qemu_vfree(buf);
2568 return -EINVAL;
2569 }
2570 /* Zero-pad last write if image size is not cluster aligned */
2571 memset(buf + bytes, 0, s->cluster_size - bytes);
2572 }
2573 qemu_iovec_to_buf(qiov, 0, buf, bytes);
2574
2575 out_buf = g_malloc(s->cluster_size);
2576
2577 /* best compression, small window, no zlib header */
2578 memset(&strm, 0, sizeof(strm));
2579 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2580 Z_DEFLATED, -12,
2581 9, Z_DEFAULT_STRATEGY);
2582 if (ret != 0) {
2583 ret = -EINVAL;
2584 goto fail;
2585 }
2586
2587 strm.avail_in = s->cluster_size;
2588 strm.next_in = (uint8_t *)buf;
2589 strm.avail_out = s->cluster_size;
2590 strm.next_out = out_buf;
2591
2592 ret = deflate(&strm, Z_FINISH);
2593 if (ret != Z_STREAM_END && ret != Z_OK) {
2594 deflateEnd(&strm);
2595 ret = -EINVAL;
2596 goto fail;
2597 }
2598 out_len = strm.next_out - out_buf;
2599
2600 deflateEnd(&strm);
2601
2602 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2603 /* could not compress: write normal cluster */
2604 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
2605 if (ret < 0) {
2606 goto fail;
2607 }
2608 goto success;
2609 }
2610
2611 qemu_co_mutex_lock(&s->lock);
2612 cluster_offset =
2613 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
2614 if (!cluster_offset) {
2615 qemu_co_mutex_unlock(&s->lock);
2616 ret = -EIO;
2617 goto fail;
2618 }
2619 cluster_offset &= s->cluster_offset_mask;
2620
2621 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2622 qemu_co_mutex_unlock(&s->lock);
2623 if (ret < 0) {
2624 goto fail;
2625 }
2626
2627 iov = (struct iovec) {
2628 .iov_base = out_buf,
2629 .iov_len = out_len,
2630 };
2631 qemu_iovec_init_external(&hd_qiov, &iov, 1);
2632
2633 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2634 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
2635 if (ret < 0) {
2636 goto fail;
2637 }
2638 success:
2639 ret = 0;
2640 fail:
2641 qemu_vfree(buf);
2642 g_free(out_buf);
2643 return ret;
2644 }
2645
2646 static int make_completely_empty(BlockDriverState *bs)
2647 {
2648 BDRVQcow2State *s = bs->opaque;
2649 int ret, l1_clusters;
2650 int64_t offset;
2651 uint64_t *new_reftable = NULL;
2652 uint64_t rt_entry, l1_size2;
2653 struct {
2654 uint64_t l1_offset;
2655 uint64_t reftable_offset;
2656 uint32_t reftable_clusters;
2657 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2658
2659 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2660 if (ret < 0) {
2661 goto fail;
2662 }
2663
2664 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2665 if (ret < 0) {
2666 goto fail;
2667 }
2668
2669 /* Refcounts will be broken utterly */
2670 ret = qcow2_mark_dirty(bs);
2671 if (ret < 0) {
2672 goto fail;
2673 }
2674
2675 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2676
2677 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2678 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2679
2680 /* After this call, neither the in-memory nor the on-disk refcount
2681 * information accurately describe the actual references */
2682
2683 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
2684 l1_clusters * s->cluster_size, 0);
2685 if (ret < 0) {
2686 goto fail_broken_refcounts;
2687 }
2688 memset(s->l1_table, 0, l1_size2);
2689
2690 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2691
2692 /* Overwrite enough clusters at the beginning of the sectors to place
2693 * the refcount table, a refcount block and the L1 table in; this may
2694 * overwrite parts of the existing refcount and L1 table, which is not
2695 * an issue because the dirty flag is set, complete data loss is in fact
2696 * desired and partial data loss is consequently fine as well */
2697 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
2698 (2 + l1_clusters) * s->cluster_size, 0);
2699 /* This call (even if it failed overall) may have overwritten on-disk
2700 * refcount structures; in that case, the in-memory refcount information
2701 * will probably differ from the on-disk information which makes the BDS
2702 * unusable */
2703 if (ret < 0) {
2704 goto fail_broken_refcounts;
2705 }
2706
2707 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2708 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2709
2710 /* "Create" an empty reftable (one cluster) directly after the image
2711 * header and an empty L1 table three clusters after the image header;
2712 * the cluster between those two will be used as the first refblock */
2713 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
2714 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
2715 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
2716 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2717 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2718 if (ret < 0) {
2719 goto fail_broken_refcounts;
2720 }
2721
2722 s->l1_table_offset = 3 * s->cluster_size;
2723
2724 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2725 if (!new_reftable) {
2726 ret = -ENOMEM;
2727 goto fail_broken_refcounts;
2728 }
2729
2730 s->refcount_table_offset = s->cluster_size;
2731 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2732
2733 g_free(s->refcount_table);
2734 s->refcount_table = new_reftable;
2735 new_reftable = NULL;
2736
2737 /* Now the in-memory refcount information again corresponds to the on-disk
2738 * information (reftable is empty and no refblocks (the refblock cache is
2739 * empty)); however, this means some clusters (e.g. the image header) are
2740 * referenced, but not refcounted, but the normal qcow2 code assumes that
2741 * the in-memory information is always correct */
2742
2743 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2744
2745 /* Enter the first refblock into the reftable */
2746 rt_entry = cpu_to_be64(2 * s->cluster_size);
2747 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2748 &rt_entry, sizeof(rt_entry));
2749 if (ret < 0) {
2750 goto fail_broken_refcounts;
2751 }
2752 s->refcount_table[0] = 2 * s->cluster_size;
2753
2754 s->free_cluster_index = 0;
2755 assert(3 + l1_clusters <= s->refcount_block_size);
2756 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2757 if (offset < 0) {
2758 ret = offset;
2759 goto fail_broken_refcounts;
2760 } else if (offset > 0) {
2761 error_report("First cluster in emptied image is in use");
2762 abort();
2763 }
2764
2765 /* Now finally the in-memory information corresponds to the on-disk
2766 * structures and is correct */
2767 ret = qcow2_mark_clean(bs);
2768 if (ret < 0) {
2769 goto fail;
2770 }
2771
2772 ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
2773 if (ret < 0) {
2774 goto fail;
2775 }
2776
2777 return 0;
2778
2779 fail_broken_refcounts:
2780 /* The BDS is unusable at this point. If we wanted to make it usable, we
2781 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2782 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2783 * again. However, because the functions which could have caused this error
2784 * path to be taken are used by those functions as well, it's very likely
2785 * that that sequence will fail as well. Therefore, just eject the BDS. */
2786 bs->drv = NULL;
2787
2788 fail:
2789 g_free(new_reftable);
2790 return ret;
2791 }
2792
2793 static int qcow2_make_empty(BlockDriverState *bs)
2794 {
2795 BDRVQcow2State *s = bs->opaque;
2796 uint64_t start_sector;
2797 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2798 int l1_clusters, ret = 0;
2799
2800 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2801
2802 if (s->qcow_version >= 3 && !s->snapshots &&
2803 3 + l1_clusters <= s->refcount_block_size) {
2804 /* The following function only works for qcow2 v3 images (it requires
2805 * the dirty flag) and only as long as there are no snapshots (because
2806 * it completely empties the image). Furthermore, the L1 table and three
2807 * additional clusters (image header, refcount table, one refcount
2808 * block) have to fit inside one refcount block. */
2809 return make_completely_empty(bs);
2810 }
2811
2812 /* This fallback code simply discards every active cluster; this is slow,
2813 * but works in all cases */
2814 for (start_sector = 0; start_sector < bs->total_sectors;
2815 start_sector += sector_step)
2816 {
2817 /* As this function is generally used after committing an external
2818 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2819 * default action for this kind of discard is to pass the discard,
2820 * which will ideally result in an actually smaller image file, as
2821 * is probably desired. */
2822 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2823 MIN(sector_step,
2824 bs->total_sectors - start_sector),
2825 QCOW2_DISCARD_SNAPSHOT, true);
2826 if (ret < 0) {
2827 break;
2828 }
2829 }
2830
2831 return ret;
2832 }
2833
2834 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2835 {
2836 BDRVQcow2State *s = bs->opaque;
2837 int ret;
2838
2839 qemu_co_mutex_lock(&s->lock);
2840 ret = qcow2_cache_write(bs, s->l2_table_cache);
2841 if (ret < 0) {
2842 qemu_co_mutex_unlock(&s->lock);
2843 return ret;
2844 }
2845
2846 if (qcow2_need_accurate_refcounts(s)) {
2847 ret = qcow2_cache_write(bs, s->refcount_block_cache);
2848 if (ret < 0) {
2849 qemu_co_mutex_unlock(&s->lock);
2850 return ret;
2851 }
2852 }
2853 qemu_co_mutex_unlock(&s->lock);
2854
2855 return 0;
2856 }
2857
2858 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2859 {
2860 BDRVQcow2State *s = bs->opaque;
2861 bdi->unallocated_blocks_are_zero = true;
2862 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2863 bdi->cluster_size = s->cluster_size;
2864 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2865 return 0;
2866 }
2867
2868 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2869 {
2870 BDRVQcow2State *s = bs->opaque;
2871 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2872
2873 *spec_info = (ImageInfoSpecific){
2874 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2875 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
2876 };
2877 if (s->qcow_version == 2) {
2878 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
2879 .compat = g_strdup("0.10"),
2880 .refcount_bits = s->refcount_bits,
2881 };
2882 } else if (s->qcow_version == 3) {
2883 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
2884 .compat = g_strdup("1.1"),
2885 .lazy_refcounts = s->compatible_features &
2886 QCOW2_COMPAT_LAZY_REFCOUNTS,
2887 .has_lazy_refcounts = true,
2888 .corrupt = s->incompatible_features &
2889 QCOW2_INCOMPAT_CORRUPT,
2890 .has_corrupt = true,
2891 .refcount_bits = s->refcount_bits,
2892 };
2893 } else {
2894 /* if this assertion fails, this probably means a new version was
2895 * added without having it covered here */
2896 assert(false);
2897 }
2898
2899 return spec_info;
2900 }
2901
2902 #if 0
2903 static void dump_refcounts(BlockDriverState *bs)
2904 {
2905 BDRVQcow2State *s = bs->opaque;
2906 int64_t nb_clusters, k, k1, size;
2907 int refcount;
2908
2909 size = bdrv_getlength(bs->file->bs);
2910 nb_clusters = size_to_clusters(s, size);
2911 for(k = 0; k < nb_clusters;) {
2912 k1 = k;
2913 refcount = get_refcount(bs, k);
2914 k++;
2915 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2916 k++;
2917 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2918 k - k1);
2919 }
2920 }
2921 #endif
2922
2923 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2924 int64_t pos)
2925 {
2926 BDRVQcow2State *s = bs->opaque;
2927
2928 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2929 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
2930 qiov->size, qiov, 0);
2931 }
2932
2933 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2934 int64_t pos)
2935 {
2936 BDRVQcow2State *s = bs->opaque;
2937
2938 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2939 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
2940 qiov->size, qiov, 0);
2941 }
2942
2943 /*
2944 * Downgrades an image's version. To achieve this, any incompatible features
2945 * have to be removed.
2946 */
2947 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2948 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
2949 {
2950 BDRVQcow2State *s = bs->opaque;
2951 int current_version = s->qcow_version;
2952 int ret;
2953
2954 if (target_version == current_version) {
2955 return 0;
2956 } else if (target_version > current_version) {
2957 return -EINVAL;
2958 } else if (target_version != 2) {
2959 return -EINVAL;
2960 }
2961
2962 if (s->refcount_order != 4) {
2963 error_report("compat=0.10 requires refcount_bits=16");
2964 return -ENOTSUP;
2965 }
2966
2967 /* clear incompatible features */
2968 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2969 ret = qcow2_mark_clean(bs);
2970 if (ret < 0) {
2971 return ret;
2972 }
2973 }
2974
2975 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2976 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2977 * best thing to do anyway */
2978
2979 if (s->incompatible_features) {
2980 return -ENOTSUP;
2981 }
2982
2983 /* since we can ignore compatible features, we can set them to 0 as well */
2984 s->compatible_features = 0;
2985 /* if lazy refcounts have been used, they have already been fixed through
2986 * clearing the dirty flag */
2987
2988 /* clearing autoclear features is trivial */
2989 s->autoclear_features = 0;
2990
2991 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
2992 if (ret < 0) {
2993 return ret;
2994 }
2995
2996 s->qcow_version = target_version;
2997 ret = qcow2_update_header(bs);
2998 if (ret < 0) {
2999 s->qcow_version = current_version;
3000 return ret;
3001 }
3002 return 0;
3003 }
3004
3005 typedef enum Qcow2AmendOperation {
3006 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3007 * statically initialized to so that the helper CB can discern the first
3008 * invocation from an operation change */
3009 QCOW2_NO_OPERATION = 0,
3010
3011 QCOW2_CHANGING_REFCOUNT_ORDER,
3012 QCOW2_DOWNGRADING,
3013 } Qcow2AmendOperation;
3014
3015 typedef struct Qcow2AmendHelperCBInfo {
3016 /* The code coordinating the amend operations should only modify
3017 * these four fields; the rest will be managed by the CB */
3018 BlockDriverAmendStatusCB *original_status_cb;
3019 void *original_cb_opaque;
3020
3021 Qcow2AmendOperation current_operation;
3022
3023 /* Total number of operations to perform (only set once) */
3024 int total_operations;
3025
3026 /* The following fields are managed by the CB */
3027
3028 /* Number of operations completed */
3029 int operations_completed;
3030
3031 /* Cumulative offset of all completed operations */
3032 int64_t offset_completed;
3033
3034 Qcow2AmendOperation last_operation;
3035 int64_t last_work_size;
3036 } Qcow2AmendHelperCBInfo;
3037
3038 static void qcow2_amend_helper_cb(BlockDriverState *bs,
3039 int64_t operation_offset,
3040 int64_t operation_work_size, void *opaque)
3041 {
3042 Qcow2AmendHelperCBInfo *info = opaque;
3043 int64_t current_work_size;
3044 int64_t projected_work_size;
3045
3046 if (info->current_operation != info->last_operation) {
3047 if (info->last_operation != QCOW2_NO_OPERATION) {
3048 info->offset_completed += info->last_work_size;
3049 info->operations_completed++;
3050 }
3051
3052 info->last_operation = info->current_operation;
3053 }
3054
3055 assert(info->total_operations > 0);
3056 assert(info->operations_completed < info->total_operations);
3057
3058 info->last_work_size = operation_work_size;
3059
3060 current_work_size = info->offset_completed + operation_work_size;
3061
3062 /* current_work_size is the total work size for (operations_completed + 1)
3063 * operations (which includes this one), so multiply it by the number of
3064 * operations not covered and divide it by the number of operations
3065 * covered to get a projection for the operations not covered */
3066 projected_work_size = current_work_size * (info->total_operations -
3067 info->operations_completed - 1)
3068 / (info->operations_completed + 1);
3069
3070 info->original_status_cb(bs, info->offset_completed + operation_offset,
3071 current_work_size + projected_work_size,
3072 info->original_cb_opaque);
3073 }
3074
3075 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
3076 BlockDriverAmendStatusCB *status_cb,
3077 void *cb_opaque)
3078 {
3079 BDRVQcow2State *s = bs->opaque;
3080 int old_version = s->qcow_version, new_version = old_version;
3081 uint64_t new_size = 0;
3082 const char *backing_file = NULL, *backing_format = NULL;
3083 bool lazy_refcounts = s->use_lazy_refcounts;
3084 const char *compat = NULL;
3085 uint64_t cluster_size = s->cluster_size;
3086 bool encrypt;
3087 int refcount_bits = s->refcount_bits;
3088 int ret;
3089 QemuOptDesc *desc = opts->list->desc;
3090 Qcow2AmendHelperCBInfo helper_cb_info;
3091
3092 while (desc && desc->name) {
3093 if (!qemu_opt_find(opts, desc->name)) {
3094 /* only change explicitly defined options */
3095 desc++;
3096 continue;
3097 }
3098
3099 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
3100 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
3101 if (!compat) {
3102 /* preserve default */
3103 } else if (!strcmp(compat, "0.10")) {
3104 new_version = 2;
3105 } else if (!strcmp(compat, "1.1")) {
3106 new_version = 3;
3107 } else {
3108 error_report("Unknown compatibility level %s", compat);
3109 return -EINVAL;
3110 }
3111 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
3112 error_report("Cannot change preallocation mode");
3113 return -ENOTSUP;
3114 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
3115 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3116 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
3117 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3118 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
3119 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3120 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
3121 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3122 !!s->cipher);
3123
3124 if (encrypt != !!s->cipher) {
3125 error_report("Changing the encryption flag is not supported");
3126 return -ENOTSUP;
3127 }
3128 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
3129 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
3130 cluster_size);
3131 if (cluster_size != s->cluster_size) {
3132 error_report("Changing the cluster size is not supported");
3133 return -ENOTSUP;
3134 }
3135 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
3136 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
3137 lazy_refcounts);
3138 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
3139 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
3140 refcount_bits);
3141
3142 if (refcount_bits <= 0 || refcount_bits > 64 ||
3143 !is_power_of_2(refcount_bits))
3144 {
3145 error_report("Refcount width must be a power of two and may "
3146 "not exceed 64 bits");
3147 return -EINVAL;
3148 }
3149 } else {
3150 /* if this point is reached, this probably means a new option was
3151 * added without having it covered here */
3152 abort();
3153 }
3154
3155 desc++;
3156 }
3157
3158 helper_cb_info = (Qcow2AmendHelperCBInfo){
3159 .original_status_cb = status_cb,
3160 .original_cb_opaque = cb_opaque,
3161 .total_operations = (new_version < old_version)
3162 + (s->refcount_bits != refcount_bits)
3163 };
3164
3165 /* Upgrade first (some features may require compat=1.1) */
3166 if (new_version > old_version) {
3167 s->qcow_version = new_version;
3168 ret = qcow2_update_header(bs);
3169 if (ret < 0) {
3170 s->qcow_version = old_version;
3171 return ret;
3172 }
3173 }
3174
3175 if (s->refcount_bits != refcount_bits) {
3176 int refcount_order = ctz32(refcount_bits);
3177 Error *local_error = NULL;
3178
3179 if (new_version < 3 && refcount_bits != 16) {
3180 error_report("Different refcount widths than 16 bits require "
3181 "compatibility level 1.1 or above (use compat=1.1 or "
3182 "greater)");
3183 return -EINVAL;
3184 }
3185
3186 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
3187 ret = qcow2_change_refcount_order(bs, refcount_order,
3188 &qcow2_amend_helper_cb,
3189 &helper_cb_info, &local_error);
3190 if (ret < 0) {
3191 error_report_err(local_error);
3192 return ret;
3193 }
3194 }
3195
3196 if (backing_file || backing_format) {
3197 ret = qcow2_change_backing_file(bs,
3198 backing_file ?: s->image_backing_file,
3199 backing_format ?: s->image_backing_format);
3200 if (ret < 0) {
3201 return ret;
3202 }
3203 }
3204
3205 if (s->use_lazy_refcounts != lazy_refcounts) {
3206 if (lazy_refcounts) {
3207 if (new_version < 3) {
3208 error_report("Lazy refcounts only supported with compatibility "
3209 "level 1.1 and above (use compat=1.1 or greater)");
3210 return -EINVAL;
3211 }
3212 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3213 ret = qcow2_update_header(bs);
3214 if (ret < 0) {
3215 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3216 return ret;
3217 }
3218 s->use_lazy_refcounts = true;
3219 } else {
3220 /* make image clean first */
3221 ret = qcow2_mark_clean(bs);
3222 if (ret < 0) {
3223 return ret;
3224 }
3225 /* now disallow lazy refcounts */
3226 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3227 ret = qcow2_update_header(bs);
3228 if (ret < 0) {
3229 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3230 return ret;
3231 }
3232 s->use_lazy_refcounts = false;
3233 }
3234 }
3235
3236 if (new_size) {
3237 ret = bdrv_truncate(bs, new_size);
3238 if (ret < 0) {
3239 return ret;
3240 }
3241 }
3242
3243 /* Downgrade last (so unsupported features can be removed before) */
3244 if (new_version < old_version) {
3245 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3246 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3247 &helper_cb_info);
3248 if (ret < 0) {
3249 return ret;
3250 }
3251 }
3252
3253 return 0;
3254 }
3255
3256 /*
3257 * If offset or size are negative, respectively, they will not be included in
3258 * the BLOCK_IMAGE_CORRUPTED event emitted.
3259 * fatal will be ignored for read-only BDS; corruptions found there will always
3260 * be considered non-fatal.
3261 */
3262 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
3263 int64_t size, const char *message_format, ...)
3264 {
3265 BDRVQcow2State *s = bs->opaque;
3266 const char *node_name;
3267 char *message;
3268 va_list ap;
3269
3270 fatal = fatal && !bs->read_only;
3271
3272 if (s->signaled_corruption &&
3273 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
3274 {
3275 return;
3276 }
3277
3278 va_start(ap, message_format);
3279 message = g_strdup_vprintf(message_format, ap);
3280 va_end(ap);
3281
3282 if (fatal) {
3283 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
3284 "corruption events will be suppressed\n", message);
3285 } else {
3286 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
3287 "corruption events will be suppressed\n", message);
3288 }
3289
3290 node_name = bdrv_get_node_name(bs);
3291 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3292 *node_name != '\0', node_name,
3293 message, offset >= 0, offset,
3294 size >= 0, size,
3295 fatal, &error_abort);
3296 g_free(message);
3297
3298 if (fatal) {
3299 qcow2_mark_corrupt(bs);
3300 bs->drv = NULL; /* make BDS unusable */
3301 }
3302
3303 s->signaled_corruption = true;
3304 }
3305
3306 static QemuOptsList qcow2_create_opts = {
3307 .name = "qcow2-create-opts",
3308 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
3309 .desc = {
3310 {
3311 .name = BLOCK_OPT_SIZE,
3312 .type = QEMU_OPT_SIZE,
3313 .help = "Virtual disk size"
3314 },
3315 {
3316 .name = BLOCK_OPT_COMPAT_LEVEL,
3317 .type = QEMU_OPT_STRING,
3318 .help = "Compatibility level (0.10 or 1.1)"
3319 },
3320 {
3321 .name = BLOCK_OPT_BACKING_FILE,
3322 .type = QEMU_OPT_STRING,
3323 .help = "File name of a base image"
3324 },
3325 {
3326 .name = BLOCK_OPT_BACKING_FMT,
3327 .type = QEMU_OPT_STRING,
3328 .help = "Image format of the base image"
3329 },
3330 {
3331 .name = BLOCK_OPT_ENCRYPT,
3332 .type = QEMU_OPT_BOOL,
3333 .help = "Encrypt the image",
3334 .def_value_str = "off"
3335 },
3336 {
3337 .name = BLOCK_OPT_CLUSTER_SIZE,
3338 .type = QEMU_OPT_SIZE,
3339 .help = "qcow2 cluster size",
3340 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3341 },
3342 {
3343 .name = BLOCK_OPT_PREALLOC,
3344 .type = QEMU_OPT_STRING,
3345 .help = "Preallocation mode (allowed values: off, metadata, "
3346 "falloc, full)"
3347 },
3348 {
3349 .name = BLOCK_OPT_LAZY_REFCOUNTS,
3350 .type = QEMU_OPT_BOOL,
3351 .help = "Postpone refcount updates",
3352 .def_value_str = "off"
3353 },
3354 {
3355 .name = BLOCK_OPT_REFCOUNT_BITS,
3356 .type = QEMU_OPT_NUMBER,
3357 .help = "Width of a reference count entry in bits",
3358 .def_value_str = "16"
3359 },
3360 { /* end of list */ }
3361 }
3362 };
3363
3364 BlockDriver bdrv_qcow2 = {
3365 .format_name = "qcow2",
3366 .instance_size = sizeof(BDRVQcow2State),
3367 .bdrv_probe = qcow2_probe,
3368 .bdrv_open = qcow2_open,
3369 .bdrv_close = qcow2_close,
3370 .bdrv_reopen_prepare = qcow2_reopen_prepare,
3371 .bdrv_reopen_commit = qcow2_reopen_commit,
3372 .bdrv_reopen_abort = qcow2_reopen_abort,
3373 .bdrv_join_options = qcow2_join_options,
3374 .bdrv_create = qcow2_create,
3375 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3376 .bdrv_co_get_block_status = qcow2_co_get_block_status,
3377 .bdrv_set_key = qcow2_set_key,
3378
3379 .bdrv_co_preadv = qcow2_co_preadv,
3380 .bdrv_co_pwritev = qcow2_co_pwritev,
3381 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
3382
3383 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
3384 .bdrv_co_pdiscard = qcow2_co_pdiscard,
3385 .bdrv_truncate = qcow2_truncate,
3386 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
3387 .bdrv_make_empty = qcow2_make_empty,
3388
3389 .bdrv_snapshot_create = qcow2_snapshot_create,
3390 .bdrv_snapshot_goto = qcow2_snapshot_goto,
3391 .bdrv_snapshot_delete = qcow2_snapshot_delete,
3392 .bdrv_snapshot_list = qcow2_snapshot_list,
3393 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3394 .bdrv_get_info = qcow2_get_info,
3395 .bdrv_get_specific_info = qcow2_get_specific_info,
3396
3397 .bdrv_save_vmstate = qcow2_save_vmstate,
3398 .bdrv_load_vmstate = qcow2_load_vmstate,
3399
3400 .supports_backing = true,
3401 .bdrv_change_backing_file = qcow2_change_backing_file,
3402
3403 .bdrv_refresh_limits = qcow2_refresh_limits,
3404 .bdrv_invalidate_cache = qcow2_invalidate_cache,
3405 .bdrv_inactivate = qcow2_inactivate,
3406
3407 .create_opts = &qcow2_create_opts,
3408 .bdrv_check = qcow2_check,
3409 .bdrv_amend_options = qcow2_amend_options,
3410
3411 .bdrv_detach_aio_context = qcow2_detach_aio_context,
3412 .bdrv_attach_aio_context = qcow2_attach_aio_context,
3413 };
3414
3415 static void bdrv_qcow2_init(void)
3416 {
3417 bdrv_register(&bdrv_qcow2);
3418 }
3419
3420 block_init(bdrv_qcow2_init);