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