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