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