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