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