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