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