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