]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
block: acquire in bdrv_query_image_info
[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);
191fb11b 1767 bs->drv = NULL;
5a8a30db
KW
1768 return;
1769 }
3456a8d1 1770
ff99129a 1771 memset(s, 0, sizeof(BDRVQcow2State));
d475e5ac 1772 options = qdict_clone_shallow(bs->options);
5a8a30db 1773
140fd5a6 1774 flags &= ~BDRV_O_INACTIVE;
5a8a30db 1775 ret = qcow2_open(bs, options, flags, &local_err);
a1904e48 1776 QDECREF(options);
5a8a30db 1777 if (local_err) {
e43bfd9c
MA
1778 error_propagate(errp, local_err);
1779 error_prepend(errp, "Could not reopen qcow2 layer: ");
191fb11b 1780 bs->drv = NULL;
5a8a30db
KW
1781 return;
1782 } else if (ret < 0) {
1783 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
191fb11b 1784 bs->drv = NULL;
5a8a30db
KW
1785 return;
1786 }
acdfb480 1787
f6fa64f6 1788 s->cipher = cipher;
06d9260f
AL
1789}
1790
e24e49e6
KW
1791static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1792 size_t len, size_t buflen)
1793{
1794 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1795 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1796
1797 if (buflen < ext_len) {
1798 return -ENOSPC;
1799 }
1800
1801 *ext_backing_fmt = (QCowExtension) {
1802 .magic = cpu_to_be32(magic),
1803 .len = cpu_to_be32(len),
1804 };
1805 memcpy(buf + sizeof(QCowExtension), s, len);
1806
1807 return ext_len;
1808}
1809
756e6736 1810/*
e24e49e6
KW
1811 * Updates the qcow2 header, including the variable length parts of it, i.e.
1812 * the backing file name and all extensions. qcow2 was not designed to allow
1813 * such changes, so if we run out of space (we can only use the first cluster)
1814 * this function may fail.
756e6736
KW
1815 *
1816 * Returns 0 on success, -errno in error cases.
1817 */
e24e49e6 1818int qcow2_update_header(BlockDriverState *bs)
756e6736 1819{
ff99129a 1820 BDRVQcow2State *s = bs->opaque;
e24e49e6
KW
1821 QCowHeader *header;
1822 char *buf;
1823 size_t buflen = s->cluster_size;
756e6736 1824 int ret;
e24e49e6
KW
1825 uint64_t total_size;
1826 uint32_t refcount_table_clusters;
6744cbab 1827 size_t header_length;
75bab85c 1828 Qcow2UnknownHeaderExtension *uext;
756e6736 1829
e24e49e6 1830 buf = qemu_blockalign(bs, buflen);
756e6736 1831
e24e49e6
KW
1832 /* Header structure */
1833 header = (QCowHeader*) buf;
756e6736 1834
e24e49e6
KW
1835 if (buflen < sizeof(*header)) {
1836 ret = -ENOSPC;
1837 goto fail;
756e6736
KW
1838 }
1839
6744cbab 1840 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
1841 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1842 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1843
1844 *header = (QCowHeader) {
6744cbab 1845 /* Version 2 fields */
e24e49e6 1846 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 1847 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
1848 .backing_file_offset = 0,
1849 .backing_file_size = 0,
1850 .cluster_bits = cpu_to_be32(s->cluster_bits),
1851 .size = cpu_to_be64(total_size),
1852 .crypt_method = cpu_to_be32(s->crypt_method_header),
1853 .l1_size = cpu_to_be32(s->l1_size),
1854 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1855 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1856 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1857 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1858 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
1859
1860 /* Version 3 fields */
1861 .incompatible_features = cpu_to_be64(s->incompatible_features),
1862 .compatible_features = cpu_to_be64(s->compatible_features),
1863 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 1864 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 1865 .header_length = cpu_to_be32(header_length),
e24e49e6 1866 };
756e6736 1867
6744cbab
KW
1868 /* For older versions, write a shorter header */
1869 switch (s->qcow_version) {
1870 case 2:
1871 ret = offsetof(QCowHeader, incompatible_features);
1872 break;
1873 case 3:
1874 ret = sizeof(*header);
1875 break;
1876 default:
b6c14762
JM
1877 ret = -EINVAL;
1878 goto fail;
6744cbab
KW
1879 }
1880
1881 buf += ret;
1882 buflen -= ret;
1883 memset(buf, 0, buflen);
1884
1885 /* Preserve any unknown field in the header */
1886 if (s->unknown_header_fields_size) {
1887 if (buflen < s->unknown_header_fields_size) {
1888 ret = -ENOSPC;
1889 goto fail;
1890 }
1891
1892 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1893 buf += s->unknown_header_fields_size;
1894 buflen -= s->unknown_header_fields_size;
1895 }
756e6736 1896
e24e49e6 1897 /* Backing file format header extension */
e4603fe1 1898 if (s->image_backing_format) {
e24e49e6 1899 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
e4603fe1
KW
1900 s->image_backing_format,
1901 strlen(s->image_backing_format),
e24e49e6
KW
1902 buflen);
1903 if (ret < 0) {
1904 goto fail;
756e6736
KW
1905 }
1906
e24e49e6
KW
1907 buf += ret;
1908 buflen -= ret;
756e6736
KW
1909 }
1910
cfcc4c62 1911 /* Feature table */
1a4828c7
KW
1912 if (s->qcow_version >= 3) {
1913 Qcow2Feature features[] = {
1914 {
1915 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1916 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1917 .name = "dirty bit",
1918 },
1919 {
1920 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1921 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1922 .name = "corrupt bit",
1923 },
1924 {
1925 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1926 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1927 .name = "lazy refcounts",
1928 },
1929 };
1930
1931 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1932 features, sizeof(features), buflen);
1933 if (ret < 0) {
1934 goto fail;
1935 }
1936 buf += ret;
1937 buflen -= ret;
cfcc4c62 1938 }
cfcc4c62 1939
75bab85c
KW
1940 /* Keep unknown header extensions */
1941 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1942 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1943 if (ret < 0) {
1944 goto fail;
1945 }
1946
1947 buf += ret;
1948 buflen -= ret;
1949 }
1950
e24e49e6
KW
1951 /* End of header extensions */
1952 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
1953 if (ret < 0) {
1954 goto fail;
1955 }
1956
e24e49e6
KW
1957 buf += ret;
1958 buflen -= ret;
756e6736 1959
e24e49e6 1960 /* Backing file name */
e4603fe1
KW
1961 if (s->image_backing_file) {
1962 size_t backing_file_len = strlen(s->image_backing_file);
e24e49e6
KW
1963
1964 if (buflen < backing_file_len) {
1965 ret = -ENOSPC;
1966 goto fail;
1967 }
1968
00ea1881 1969 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e4603fe1 1970 strncpy(buf, s->image_backing_file, buflen);
e24e49e6
KW
1971
1972 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1973 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
1974 }
1975
e24e49e6 1976 /* Write the new header */
9a4f4c31 1977 ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
756e6736
KW
1978 if (ret < 0) {
1979 goto fail;
1980 }
1981
1982 ret = 0;
1983fail:
e24e49e6 1984 qemu_vfree(header);
756e6736
KW
1985 return ret;
1986}
1987
1988static int qcow2_change_backing_file(BlockDriverState *bs,
1989 const char *backing_file, const char *backing_fmt)
1990{
ff99129a 1991 BDRVQcow2State *s = bs->opaque;
e4603fe1 1992
e24e49e6
KW
1993 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1994 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1995
e4603fe1
KW
1996 g_free(s->image_backing_file);
1997 g_free(s->image_backing_format);
1998
1999 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2000 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2001
e24e49e6 2002 return qcow2_update_header(bs);
756e6736
KW
2003}
2004
a35e1c17
KW
2005static int preallocate(BlockDriverState *bs)
2006{
a35e1c17
KW
2007 uint64_t nb_sectors;
2008 uint64_t offset;
060bee89 2009 uint64_t host_offset = 0;
a35e1c17 2010 int num;
148da7ea 2011 int ret;
f50f88b9 2012 QCowL2Meta *meta;
a35e1c17 2013
57322b78 2014 nb_sectors = bdrv_nb_sectors(bs);
a35e1c17
KW
2015 offset = 0;
2016
2017 while (nb_sectors) {
7c2bbf4a 2018 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
16f0587e 2019 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
060bee89 2020 &host_offset, &meta);
148da7ea 2021 if (ret < 0) {
19dbcbf7 2022 return ret;
a35e1c17
KW
2023 }
2024
c792707f
SH
2025 while (meta) {
2026 QCowL2Meta *next = meta->next;
2027
7c2bbf4a
HT
2028 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2029 if (ret < 0) {
2030 qcow2_free_any_clusters(bs, meta->alloc_offset,
2031 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2032 return ret;
2033 }
2034
2035 /* There are no dependent requests, but we need to remove our
2036 * request from the list of in-flight requests */
4e95314e 2037 QLIST_REMOVE(meta, next_in_flight);
c792707f
SH
2038
2039 g_free(meta);
2040 meta = next;
f50f88b9 2041 }
f214978a 2042
a35e1c17
KW
2043 /* TODO Preallocate data if requested */
2044
2045 nb_sectors -= num;
7c2bbf4a 2046 offset += num << BDRV_SECTOR_BITS;
a35e1c17
KW
2047 }
2048
2049 /*
2050 * It is expected that the image file is large enough to actually contain
2051 * all of the allocated clusters (otherwise we get failing reads after
2052 * EOF). Extend the image to the last allocated sector.
2053 */
060bee89 2054 if (host_offset != 0) {
7c2bbf4a
HT
2055 uint8_t buf[BDRV_SECTOR_SIZE];
2056 memset(buf, 0, BDRV_SECTOR_SIZE);
9a4f4c31
KW
2057 ret = bdrv_write(bs->file->bs,
2058 (host_offset >> BDRV_SECTOR_BITS) + num - 1,
7c2bbf4a 2059 buf, 1);
19dbcbf7
KW
2060 if (ret < 0) {
2061 return ret;
2062 }
a35e1c17
KW
2063 }
2064
2065 return 0;
2066}
2067
7c80ab3f
JS
2068static int qcow2_create2(const char *filename, int64_t total_size,
2069 const char *backing_file, const char *backing_format,
ffeaac9b 2070 int flags, size_t cluster_size, PreallocMode prealloc,
bd4b167f 2071 QemuOpts *opts, int version, int refcount_order,
3ef6c40a 2072 Error **errp)
a9420734 2073{
a9420734 2074 int cluster_bits;
e6641719
HR
2075 QDict *options;
2076
2077 /* Calculate cluster_bits */
786a4ea8 2078 cluster_bits = ctz32(cluster_size);
a9420734
KW
2079 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2080 (1 << cluster_bits) != cluster_size)
2081 {
3ef6c40a
HR
2082 error_setg(errp, "Cluster size must be a power of two between %d and "
2083 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
a9420734
KW
2084 return -EINVAL;
2085 }
2086
2087 /*
2088 * Open the image file and write a minimal qcow2 header.
2089 *
2090 * We keep things simple and start with a zero-sized image. We also
2091 * do without refcount blocks or a L1 table for now. We'll fix the
2092 * inconsistency later.
2093 *
2094 * We do need a refcount table because growing the refcount table means
2095 * allocating two new refcount blocks - the seconds of which would be at
2096 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2097 * size for any qcow2 image.
2098 */
2099 BlockDriverState* bs;
f8413b3c 2100 QCowHeader *header;
b106ad91 2101 uint64_t* refcount_table;
3ef6c40a 2102 Error *local_err = NULL;
a9420734
KW
2103 int ret;
2104
0e4271b7 2105 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
bd4b167f
HR
2106 /* Note: The following calculation does not need to be exact; if it is a
2107 * bit off, either some bytes will be "leaked" (which is fine) or we
2108 * will need to increase the file size by some bytes (which is fine,
2109 * too, as long as the bulk is allocated here). Therefore, using
2110 * floating point arithmetic is fine. */
0e4271b7
HT
2111 int64_t meta_size = 0;
2112 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
2113 int64_t aligned_total_size = align_offset(total_size, cluster_size);
bd4b167f
HR
2114 int refblock_bits, refblock_size;
2115 /* refcount entry size in bytes */
2116 double rces = (1 << refcount_order) / 8.;
2117
2118 /* see qcow2_open() */
2119 refblock_bits = cluster_bits - (refcount_order - 3);
2120 refblock_size = 1 << refblock_bits;
0e4271b7
HT
2121
2122 /* header: 1 cluster */
2123 meta_size += cluster_size;
2124
2125 /* total size of L2 tables */
2126 nl2e = aligned_total_size / cluster_size;
2127 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2128 meta_size += nl2e * sizeof(uint64_t);
2129
2130 /* total size of L1 tables */
2131 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2132 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2133 meta_size += nl1e * sizeof(uint64_t);
2134
2135 /* total size of refcount blocks
2136 *
2137 * note: every host cluster is reference-counted, including metadata
2138 * (even refcount blocks are recursively included).
2139 * Let:
2140 * a = total_size (this is the guest disk size)
2141 * m = meta size not including refcount blocks and refcount tables
2142 * c = cluster size
2143 * y1 = number of refcount blocks entries
2144 * y2 = meta size including everything
bd4b167f 2145 * rces = refcount entry size in bytes
0e4271b7
HT
2146 * then,
2147 * y1 = (y2 + a)/c
bd4b167f 2148 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
0e4271b7 2149 * we can get y1:
bd4b167f 2150 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
0e4271b7 2151 */
bd4b167f
HR
2152 nrefblocke = (aligned_total_size + meta_size + cluster_size)
2153 / (cluster_size - rces - rces * sizeof(uint64_t)
2154 / cluster_size);
2155 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
0e4271b7
HT
2156
2157 /* total size of refcount tables */
bd4b167f 2158 nreftablee = nrefblocke / refblock_size;
0e4271b7
HT
2159 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
2160 meta_size += nreftablee * sizeof(uint64_t);
2161
2162 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
39101f25 2163 aligned_total_size + meta_size, &error_abort);
f43e47db
MA
2164 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2165 &error_abort);
0e4271b7
HT
2166 }
2167
c282e1fd 2168 ret = bdrv_create_file(filename, opts, &local_err);
a9420734 2169 if (ret < 0) {
3ef6c40a 2170 error_propagate(errp, local_err);
a9420734
KW
2171 return ret;
2172 }
2173
2e40134b
HR
2174 bs = NULL;
2175 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
6ebf9aa2 2176 &local_err);
a9420734 2177 if (ret < 0) {
3ef6c40a 2178 error_propagate(errp, local_err);
a9420734
KW
2179 return ret;
2180 }
2181
2182 /* Write the header */
f8413b3c
KW
2183 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2184 header = g_malloc0(cluster_size);
2185 *header = (QCowHeader) {
2186 .magic = cpu_to_be32(QCOW_MAGIC),
2187 .version = cpu_to_be32(version),
2188 .cluster_bits = cpu_to_be32(cluster_bits),
2189 .size = cpu_to_be64(0),
2190 .l1_table_offset = cpu_to_be64(0),
2191 .l1_size = cpu_to_be32(0),
2192 .refcount_table_offset = cpu_to_be64(cluster_size),
2193 .refcount_table_clusters = cpu_to_be32(1),
bd4b167f 2194 .refcount_order = cpu_to_be32(refcount_order),
f8413b3c
KW
2195 .header_length = cpu_to_be32(sizeof(*header)),
2196 };
a9420734
KW
2197
2198 if (flags & BLOCK_FLAG_ENCRYPT) {
f8413b3c 2199 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
a9420734 2200 } else {
f8413b3c 2201 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734
KW
2202 }
2203
bfe8043e 2204 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
f8413b3c 2205 header->compatible_features |=
bfe8043e
SH
2206 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2207 }
2208
f8413b3c
KW
2209 ret = bdrv_pwrite(bs, 0, header, cluster_size);
2210 g_free(header);
a9420734 2211 if (ret < 0) {
3ef6c40a 2212 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
2213 goto out;
2214 }
2215
b106ad91
KW
2216 /* Write a refcount table with one refcount block */
2217 refcount_table = g_malloc0(2 * cluster_size);
2218 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2219 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
7267c094 2220 g_free(refcount_table);
a9420734
KW
2221
2222 if (ret < 0) {
3ef6c40a 2223 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
2224 goto out;
2225 }
2226
f67503e5
HR
2227 bdrv_unref(bs);
2228 bs = NULL;
a9420734
KW
2229
2230 /*
2231 * And now open the image and make it consistent first (i.e. increase the
2232 * refcount of the cluster that is occupied by the header and the refcount
2233 * table)
2234 */
e6641719
HR
2235 options = qdict_new();
2236 qdict_put(options, "driver", qstring_from_str("qcow2"));
2237 ret = bdrv_open(&bs, filename, NULL, options,
ef810437 2238 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
6ebf9aa2 2239 &local_err);
a9420734 2240 if (ret < 0) {
3ef6c40a 2241 error_propagate(errp, local_err);
a9420734
KW
2242 goto out;
2243 }
2244
b106ad91 2245 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
a9420734 2246 if (ret < 0) {
3ef6c40a
HR
2247 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2248 "header and refcount table");
a9420734
KW
2249 goto out;
2250
2251 } else if (ret != 0) {
2252 error_report("Huh, first cluster in empty image is already in use?");
2253 abort();
2254 }
2255
b527c9b3
KW
2256 /* Create a full header (including things like feature table) */
2257 ret = qcow2_update_header(bs);
2258 if (ret < 0) {
2259 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2260 goto out;
2261 }
2262
a9420734 2263 /* Okay, now that we have a valid image, let's give it the right size */
180e9526 2264 ret = bdrv_truncate(bs, total_size);
a9420734 2265 if (ret < 0) {
3ef6c40a 2266 error_setg_errno(errp, -ret, "Could not resize image");
a9420734
KW
2267 goto out;
2268 }
2269
2270 /* Want a backing file? There you go.*/
2271 if (backing_file) {
2272 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
2273 if (ret < 0) {
3ef6c40a
HR
2274 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2275 "with format '%s'", backing_file, backing_format);
a9420734
KW
2276 goto out;
2277 }
2278 }
2279
2280 /* And if we're supposed to preallocate metadata, do that now */
0e4271b7 2281 if (prealloc != PREALLOC_MODE_OFF) {
ff99129a 2282 BDRVQcow2State *s = bs->opaque;
15552c4a 2283 qemu_co_mutex_lock(&s->lock);
a9420734 2284 ret = preallocate(bs);
15552c4a 2285 qemu_co_mutex_unlock(&s->lock);
a9420734 2286 if (ret < 0) {
3ef6c40a 2287 error_setg_errno(errp, -ret, "Could not preallocate metadata");
a9420734
KW
2288 goto out;
2289 }
2290 }
2291
f67503e5
HR
2292 bdrv_unref(bs);
2293 bs = NULL;
ba2ab2f2
HR
2294
2295 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
e6641719
HR
2296 options = qdict_new();
2297 qdict_put(options, "driver", qstring_from_str("qcow2"));
2298 ret = bdrv_open(&bs, filename, NULL, options,
c9fbb99d 2299 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
6ebf9aa2 2300 &local_err);
84d18f06 2301 if (local_err) {
ba2ab2f2
HR
2302 error_propagate(errp, local_err);
2303 goto out;
2304 }
2305
a9420734
KW
2306 ret = 0;
2307out:
f67503e5
HR
2308 if (bs) {
2309 bdrv_unref(bs);
2310 }
a9420734
KW
2311 return ret;
2312}
de5f3f40 2313
1bd0e2d1 2314static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
de5f3f40 2315{
1bd0e2d1
CL
2316 char *backing_file = NULL;
2317 char *backing_fmt = NULL;
2318 char *buf = NULL;
180e9526 2319 uint64_t size = 0;
de5f3f40 2320 int flags = 0;
99cce9fa 2321 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
ffeaac9b 2322 PreallocMode prealloc;
8ad1898c 2323 int version = 3;
bd4b167f
HR
2324 uint64_t refcount_bits = 16;
2325 int refcount_order;
3ef6c40a
HR
2326 Error *local_err = NULL;
2327 int ret;
de5f3f40
KW
2328
2329 /* Read out options */
180e9526
HT
2330 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2331 BDRV_SECTOR_SIZE);
1bd0e2d1
CL
2332 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2333 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2334 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2335 flags |= BLOCK_FLAG_ENCRYPT;
2336 }
2337 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2338 DEFAULT_CLUSTER_SIZE);
2339 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
ffeaac9b 2340 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
7fb1cf16 2341 PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
ffeaac9b
HT
2342 &local_err);
2343 if (local_err) {
2344 error_propagate(errp, local_err);
1bd0e2d1
CL
2345 ret = -EINVAL;
2346 goto finish;
2347 }
2348 g_free(buf);
2349 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2350 if (!buf) {
2351 /* keep the default */
2352 } else if (!strcmp(buf, "0.10")) {
2353 version = 2;
2354 } else if (!strcmp(buf, "1.1")) {
2355 version = 3;
2356 } else {
2357 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2358 ret = -EINVAL;
2359 goto finish;
2360 }
2361
2362 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2363 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
de5f3f40
KW
2364 }
2365
ffeaac9b 2366 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
3ef6c40a
HR
2367 error_setg(errp, "Backing file and preallocation cannot be used at "
2368 "the same time");
1bd0e2d1
CL
2369 ret = -EINVAL;
2370 goto finish;
de5f3f40
KW
2371 }
2372
bfe8043e 2373 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
3ef6c40a
HR
2374 error_setg(errp, "Lazy refcounts only supported with compatibility "
2375 "level 1.1 and above (use compat=1.1 or greater)");
1bd0e2d1
CL
2376 ret = -EINVAL;
2377 goto finish;
bfe8043e
SH
2378 }
2379
06d05fa7
HR
2380 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2381 refcount_bits);
2382 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2383 error_setg(errp, "Refcount width must be a power of two and may not "
2384 "exceed 64 bits");
2385 ret = -EINVAL;
2386 goto finish;
2387 }
2388
bd4b167f
HR
2389 if (version < 3 && refcount_bits != 16) {
2390 error_setg(errp, "Different refcount widths than 16 bits require "
2391 "compatibility level 1.1 or above (use compat=1.1 or "
2392 "greater)");
2393 ret = -EINVAL;
2394 goto finish;
2395 }
2396
786a4ea8 2397 refcount_order = ctz32(refcount_bits);
bd4b167f 2398
180e9526 2399 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
bd4b167f
HR
2400 cluster_size, prealloc, opts, version, refcount_order,
2401 &local_err);
84d18f06 2402 if (local_err) {
3ef6c40a
HR
2403 error_propagate(errp, local_err);
2404 }
1bd0e2d1
CL
2405
2406finish:
2407 g_free(backing_file);
2408 g_free(backing_fmt);
2409 g_free(buf);
3ef6c40a 2410 return ret;
de5f3f40
KW
2411}
2412
621f0589 2413static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
aa7bfbff 2414 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
621f0589
KW
2415{
2416 int ret;
ff99129a 2417 BDRVQcow2State *s = bs->opaque;
621f0589
KW
2418
2419 /* Emulate misaligned zero writes */
2420 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2421 return -ENOTSUP;
2422 }
2423
2424 /* Whatever is left can use real zero clusters */
2425 qemu_co_mutex_lock(&s->lock);
2426 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2427 nb_sectors);
2428 qemu_co_mutex_unlock(&s->lock);
2429
2430 return ret;
2431}
2432
6db39ae2
PB
2433static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2434 int64_t sector_num, int nb_sectors)
5ea929e3 2435{
6db39ae2 2436 int ret;
ff99129a 2437 BDRVQcow2State *s = bs->opaque;
6db39ae2
PB
2438
2439 qemu_co_mutex_lock(&s->lock);
2440 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
808c4b6f 2441 nb_sectors, QCOW2_DISCARD_REQUEST, false);
6db39ae2
PB
2442 qemu_co_mutex_unlock(&s->lock);
2443 return ret;
5ea929e3
KW
2444}
2445
419b19d9
SH
2446static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2447{
ff99129a 2448 BDRVQcow2State *s = bs->opaque;
2cf7cfa1
KW
2449 int64_t new_l1_size;
2450 int ret;
419b19d9
SH
2451
2452 if (offset & 511) {
259b2173 2453 error_report("The new size must be a multiple of 512");
419b19d9
SH
2454 return -EINVAL;
2455 }
2456
2457 /* cannot proceed if image has snapshots */
2458 if (s->nb_snapshots) {
259b2173 2459 error_report("Can't resize an image which has snapshots");
419b19d9
SH
2460 return -ENOTSUP;
2461 }
2462
2463 /* shrinking is currently not supported */
2464 if (offset < bs->total_sectors * 512) {
259b2173 2465 error_report("qcow2 doesn't support shrinking images yet");
419b19d9
SH
2466 return -ENOTSUP;
2467 }
2468
2469 new_l1_size = size_to_l1(s, offset);
72893756 2470 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
419b19d9
SH
2471 if (ret < 0) {
2472 return ret;
2473 }
2474
2475 /* write updated header.size */
2476 offset = cpu_to_be64(offset);
9a4f4c31 2477 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
8b3b7206 2478 &offset, sizeof(uint64_t));
419b19d9
SH
2479 if (ret < 0) {
2480 return ret;
2481 }
2482
2483 s->l1_vm_state_index = new_l1_size;
2484 return 0;
2485}
2486
20d97356
BS
2487/* XXX: put compressed sectors first, then all the cluster aligned
2488 tables to avoid losing bytes in alignment */
7c80ab3f
JS
2489static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2490 const uint8_t *buf, int nb_sectors)
20d97356 2491{
ff99129a 2492 BDRVQcow2State *s = bs->opaque;
20d97356
BS
2493 z_stream strm;
2494 int ret, out_len;
2495 uint8_t *out_buf;
2496 uint64_t cluster_offset;
2497
2498 if (nb_sectors == 0) {
2499 /* align end of file to a sector boundary to ease reading with
2500 sector based I/Os */
9a4f4c31
KW
2501 cluster_offset = bdrv_getlength(bs->file->bs);
2502 return bdrv_truncate(bs->file->bs, cluster_offset);
20d97356
BS
2503 }
2504
f4d38bef
SH
2505 if (nb_sectors != s->cluster_sectors) {
2506 ret = -EINVAL;
2507
2508 /* Zero-pad last write if image size is not cluster aligned */
2509 if (sector_num + nb_sectors == bs->total_sectors &&
2510 nb_sectors < s->cluster_sectors) {
2511 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2512 memset(pad_buf, 0, s->cluster_size);
2513 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2514 ret = qcow2_write_compressed(bs, sector_num,
2515 pad_buf, s->cluster_sectors);
2516 qemu_vfree(pad_buf);
2517 }
2518 return ret;
2519 }
20d97356 2520
7267c094 2521 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
20d97356
BS
2522
2523 /* best compression, small window, no zlib header */
2524 memset(&strm, 0, sizeof(strm));
2525 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2526 Z_DEFLATED, -12,
2527 9, Z_DEFAULT_STRATEGY);
2528 if (ret != 0) {
8f1efd00
KW
2529 ret = -EINVAL;
2530 goto fail;
20d97356
BS
2531 }
2532
2533 strm.avail_in = s->cluster_size;
2534 strm.next_in = (uint8_t *)buf;
2535 strm.avail_out = s->cluster_size;
2536 strm.next_out = out_buf;
2537
2538 ret = deflate(&strm, Z_FINISH);
2539 if (ret != Z_STREAM_END && ret != Z_OK) {
20d97356 2540 deflateEnd(&strm);
8f1efd00
KW
2541 ret = -EINVAL;
2542 goto fail;
20d97356
BS
2543 }
2544 out_len = strm.next_out - out_buf;
2545
2546 deflateEnd(&strm);
2547
2548 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2549 /* could not compress: write normal cluster */
8f1efd00
KW
2550 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2551 if (ret < 0) {
2552 goto fail;
2553 }
20d97356
BS
2554 } else {
2555 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2556 sector_num << 9, out_len);
8f1efd00
KW
2557 if (!cluster_offset) {
2558 ret = -EIO;
2559 goto fail;
2560 }
20d97356 2561 cluster_offset &= s->cluster_offset_mask;
cf93980e 2562
231bb267 2563 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
cf93980e
HR
2564 if (ret < 0) {
2565 goto fail;
2566 }
2567
66f82cee 2568 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
9a4f4c31 2569 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
8f1efd00
KW
2570 if (ret < 0) {
2571 goto fail;
20d97356
BS
2572 }
2573 }
2574
8f1efd00
KW
2575 ret = 0;
2576fail:
7267c094 2577 g_free(out_buf);
8f1efd00 2578 return ret;
20d97356
BS
2579}
2580
94054183
HR
2581static int make_completely_empty(BlockDriverState *bs)
2582{
ff99129a 2583 BDRVQcow2State *s = bs->opaque;
94054183
HR
2584 int ret, l1_clusters;
2585 int64_t offset;
2586 uint64_t *new_reftable = NULL;
2587 uint64_t rt_entry, l1_size2;
2588 struct {
2589 uint64_t l1_offset;
2590 uint64_t reftable_offset;
2591 uint32_t reftable_clusters;
2592 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2593
2594 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2595 if (ret < 0) {
2596 goto fail;
2597 }
2598
2599 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2600 if (ret < 0) {
2601 goto fail;
2602 }
2603
2604 /* Refcounts will be broken utterly */
2605 ret = qcow2_mark_dirty(bs);
2606 if (ret < 0) {
2607 goto fail;
2608 }
2609
2610 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2611
2612 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2613 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2614
2615 /* After this call, neither the in-memory nor the on-disk refcount
2616 * information accurately describe the actual references */
2617
9a4f4c31 2618 ret = bdrv_write_zeroes(bs->file->bs, s->l1_table_offset / BDRV_SECTOR_SIZE,
94054183
HR
2619 l1_clusters * s->cluster_sectors, 0);
2620 if (ret < 0) {
2621 goto fail_broken_refcounts;
2622 }
2623 memset(s->l1_table, 0, l1_size2);
2624
2625 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2626
2627 /* Overwrite enough clusters at the beginning of the sectors to place
2628 * the refcount table, a refcount block and the L1 table in; this may
2629 * overwrite parts of the existing refcount and L1 table, which is not
2630 * an issue because the dirty flag is set, complete data loss is in fact
2631 * desired and partial data loss is consequently fine as well */
9a4f4c31 2632 ret = bdrv_write_zeroes(bs->file->bs, s->cluster_size / BDRV_SECTOR_SIZE,
94054183
HR
2633 (2 + l1_clusters) * s->cluster_size /
2634 BDRV_SECTOR_SIZE, 0);
2635 /* This call (even if it failed overall) may have overwritten on-disk
2636 * refcount structures; in that case, the in-memory refcount information
2637 * will probably differ from the on-disk information which makes the BDS
2638 * unusable */
2639 if (ret < 0) {
2640 goto fail_broken_refcounts;
2641 }
2642
2643 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2644 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2645
2646 /* "Create" an empty reftable (one cluster) directly after the image
2647 * header and an empty L1 table three clusters after the image header;
2648 * the cluster between those two will be used as the first refblock */
2649 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2650 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2651 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
9a4f4c31 2652 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
94054183
HR
2653 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2654 if (ret < 0) {
2655 goto fail_broken_refcounts;
2656 }
2657
2658 s->l1_table_offset = 3 * s->cluster_size;
2659
2660 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2661 if (!new_reftable) {
2662 ret = -ENOMEM;
2663 goto fail_broken_refcounts;
2664 }
2665
2666 s->refcount_table_offset = s->cluster_size;
2667 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2668
2669 g_free(s->refcount_table);
2670 s->refcount_table = new_reftable;
2671 new_reftable = NULL;
2672
2673 /* Now the in-memory refcount information again corresponds to the on-disk
2674 * information (reftable is empty and no refblocks (the refblock cache is
2675 * empty)); however, this means some clusters (e.g. the image header) are
2676 * referenced, but not refcounted, but the normal qcow2 code assumes that
2677 * the in-memory information is always correct */
2678
2679 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2680
2681 /* Enter the first refblock into the reftable */
2682 rt_entry = cpu_to_be64(2 * s->cluster_size);
9a4f4c31 2683 ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
94054183
HR
2684 &rt_entry, sizeof(rt_entry));
2685 if (ret < 0) {
2686 goto fail_broken_refcounts;
2687 }
2688 s->refcount_table[0] = 2 * s->cluster_size;
2689
2690 s->free_cluster_index = 0;
2691 assert(3 + l1_clusters <= s->refcount_block_size);
2692 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2693 if (offset < 0) {
2694 ret = offset;
2695 goto fail_broken_refcounts;
2696 } else if (offset > 0) {
2697 error_report("First cluster in emptied image is in use");
2698 abort();
2699 }
2700
2701 /* Now finally the in-memory information corresponds to the on-disk
2702 * structures and is correct */
2703 ret = qcow2_mark_clean(bs);
2704 if (ret < 0) {
2705 goto fail;
2706 }
2707
9a4f4c31 2708 ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
94054183
HR
2709 if (ret < 0) {
2710 goto fail;
2711 }
2712
2713 return 0;
2714
2715fail_broken_refcounts:
2716 /* The BDS is unusable at this point. If we wanted to make it usable, we
2717 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2718 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2719 * again. However, because the functions which could have caused this error
2720 * path to be taken are used by those functions as well, it's very likely
2721 * that that sequence will fail as well. Therefore, just eject the BDS. */
2722 bs->drv = NULL;
2723
2724fail:
2725 g_free(new_reftable);
2726 return ret;
2727}
2728
491d27e2
HR
2729static int qcow2_make_empty(BlockDriverState *bs)
2730{
ff99129a 2731 BDRVQcow2State *s = bs->opaque;
491d27e2
HR
2732 uint64_t start_sector;
2733 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
94054183
HR
2734 int l1_clusters, ret = 0;
2735
2736 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2737
2738 if (s->qcow_version >= 3 && !s->snapshots &&
2739 3 + l1_clusters <= s->refcount_block_size) {
2740 /* The following function only works for qcow2 v3 images (it requires
2741 * the dirty flag) and only as long as there are no snapshots (because
2742 * it completely empties the image). Furthermore, the L1 table and three
2743 * additional clusters (image header, refcount table, one refcount
2744 * block) have to fit inside one refcount block. */
2745 return make_completely_empty(bs);
2746 }
491d27e2 2747
94054183
HR
2748 /* This fallback code simply discards every active cluster; this is slow,
2749 * but works in all cases */
491d27e2
HR
2750 for (start_sector = 0; start_sector < bs->total_sectors;
2751 start_sector += sector_step)
2752 {
2753 /* As this function is generally used after committing an external
2754 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2755 * default action for this kind of discard is to pass the discard,
2756 * which will ideally result in an actually smaller image file, as
2757 * is probably desired. */
2758 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2759 MIN(sector_step,
2760 bs->total_sectors - start_sector),
2761 QCOW2_DISCARD_SNAPSHOT, true);
2762 if (ret < 0) {
2763 break;
2764 }
2765 }
2766
2767 return ret;
2768}
2769
a968168c 2770static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 2771{
ff99129a 2772 BDRVQcow2State *s = bs->opaque;
29c1a730
KW
2773 int ret;
2774
8b94ff85 2775 qemu_co_mutex_lock(&s->lock);
29c1a730
KW
2776 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2777 if (ret < 0) {
c95de7e2 2778 qemu_co_mutex_unlock(&s->lock);
8b94ff85 2779 return ret;
29c1a730
KW
2780 }
2781
bfe8043e
SH
2782 if (qcow2_need_accurate_refcounts(s)) {
2783 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2784 if (ret < 0) {
2785 qemu_co_mutex_unlock(&s->lock);
2786 return ret;
2787 }
29c1a730 2788 }
8b94ff85 2789 qemu_co_mutex_unlock(&s->lock);
29c1a730 2790
eb489bb1
KW
2791 return 0;
2792}
2793
7c80ab3f 2794static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356 2795{
ff99129a 2796 BDRVQcow2State *s = bs->opaque;
95de6d70
PB
2797 bdi->unallocated_blocks_are_zero = true;
2798 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
20d97356 2799 bdi->cluster_size = s->cluster_size;
7c80ab3f 2800 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
2801 return 0;
2802}
2803
37764dfb
HR
2804static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2805{
ff99129a 2806 BDRVQcow2State *s = bs->opaque;
37764dfb
HR
2807 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2808
2809 *spec_info = (ImageInfoSpecific){
6a8f9661
EB
2810 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2811 .u.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
37764dfb
HR
2812 };
2813 if (s->qcow_version == 2) {
6a8f9661 2814 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
0709c5a1
HR
2815 .compat = g_strdup("0.10"),
2816 .refcount_bits = s->refcount_bits,
37764dfb
HR
2817 };
2818 } else if (s->qcow_version == 3) {
6a8f9661 2819 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
37764dfb
HR
2820 .compat = g_strdup("1.1"),
2821 .lazy_refcounts = s->compatible_features &
2822 QCOW2_COMPAT_LAZY_REFCOUNTS,
2823 .has_lazy_refcounts = true,
9009b196
HR
2824 .corrupt = s->incompatible_features &
2825 QCOW2_INCOMPAT_CORRUPT,
2826 .has_corrupt = true,
0709c5a1 2827 .refcount_bits = s->refcount_bits,
37764dfb 2828 };
b1fc8f93
DL
2829 } else {
2830 /* if this assertion fails, this probably means a new version was
2831 * added without having it covered here */
2832 assert(false);
37764dfb
HR
2833 }
2834
2835 return spec_info;
2836}
2837
20d97356
BS
2838#if 0
2839static void dump_refcounts(BlockDriverState *bs)
2840{
ff99129a 2841 BDRVQcow2State *s = bs->opaque;
20d97356
BS
2842 int64_t nb_clusters, k, k1, size;
2843 int refcount;
2844
9a4f4c31 2845 size = bdrv_getlength(bs->file->bs);
20d97356
BS
2846 nb_clusters = size_to_clusters(s, size);
2847 for(k = 0; k < nb_clusters;) {
2848 k1 = k;
2849 refcount = get_refcount(bs, k);
2850 k++;
2851 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2852 k++;
0bfcd599
BS
2853 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2854 k - k1);
20d97356
BS
2855 }
2856}
2857#endif
2858
cf8074b3
KW
2859static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2860 int64_t pos)
20d97356 2861{
ff99129a 2862 BDRVQcow2State *s = bs->opaque;
eedff66f 2863 int64_t total_sectors = bs->total_sectors;
6e13610a 2864 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2865 int ret;
2866
66f82cee 2867 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
6e13610a 2868 bs->zero_beyond_eof = false;
8d3b1a2d 2869 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
6e13610a 2870 bs->zero_beyond_eof = zero_beyond_eof;
20d97356 2871
eedff66f
HR
2872 /* bdrv_co_do_writev will have increased the total_sectors value to include
2873 * the VM state - the VM state is however not an actual part of the block
2874 * device, therefore, we need to restore the old value. */
2875 bs->total_sectors = total_sectors;
2876
20d97356
BS
2877 return ret;
2878}
2879
7c80ab3f
JS
2880static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2881 int64_t pos, int size)
20d97356 2882{
ff99129a 2883 BDRVQcow2State *s = bs->opaque;
0d51b4de 2884 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2885 int ret;
2886
66f82cee 2887 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
0d51b4de 2888 bs->zero_beyond_eof = false;
7c80ab3f 2889 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
0d51b4de 2890 bs->zero_beyond_eof = zero_beyond_eof;
20d97356
BS
2891
2892 return ret;
2893}
2894
9296b3ed
HR
2895/*
2896 * Downgrades an image's version. To achieve this, any incompatible features
2897 * have to be removed.
2898 */
4057a2b2 2899static int qcow2_downgrade(BlockDriverState *bs, int target_version,
8b13976d 2900 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
9296b3ed 2901{
ff99129a 2902 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
2903 int current_version = s->qcow_version;
2904 int ret;
2905
2906 if (target_version == current_version) {
2907 return 0;
2908 } else if (target_version > current_version) {
2909 return -EINVAL;
2910 } else if (target_version != 2) {
2911 return -EINVAL;
2912 }
2913
2914 if (s->refcount_order != 4) {
61ce55fc 2915 error_report("compat=0.10 requires refcount_bits=16");
9296b3ed
HR
2916 return -ENOTSUP;
2917 }
2918
2919 /* clear incompatible features */
2920 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2921 ret = qcow2_mark_clean(bs);
2922 if (ret < 0) {
2923 return ret;
2924 }
2925 }
2926
2927 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2928 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2929 * best thing to do anyway */
2930
2931 if (s->incompatible_features) {
2932 return -ENOTSUP;
2933 }
2934
2935 /* since we can ignore compatible features, we can set them to 0 as well */
2936 s->compatible_features = 0;
2937 /* if lazy refcounts have been used, they have already been fixed through
2938 * clearing the dirty flag */
2939
2940 /* clearing autoclear features is trivial */
2941 s->autoclear_features = 0;
2942
8b13976d 2943 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
9296b3ed
HR
2944 if (ret < 0) {
2945 return ret;
2946 }
2947
2948 s->qcow_version = target_version;
2949 ret = qcow2_update_header(bs);
2950 if (ret < 0) {
2951 s->qcow_version = current_version;
2952 return ret;
2953 }
2954 return 0;
2955}
2956
c293a809
HR
2957typedef enum Qcow2AmendOperation {
2958 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
2959 * statically initialized to so that the helper CB can discern the first
2960 * invocation from an operation change */
2961 QCOW2_NO_OPERATION = 0,
2962
61ce55fc 2963 QCOW2_CHANGING_REFCOUNT_ORDER,
c293a809
HR
2964 QCOW2_DOWNGRADING,
2965} Qcow2AmendOperation;
2966
2967typedef struct Qcow2AmendHelperCBInfo {
2968 /* The code coordinating the amend operations should only modify
2969 * these four fields; the rest will be managed by the CB */
2970 BlockDriverAmendStatusCB *original_status_cb;
2971 void *original_cb_opaque;
2972
2973 Qcow2AmendOperation current_operation;
2974
2975 /* Total number of operations to perform (only set once) */
2976 int total_operations;
2977
2978 /* The following fields are managed by the CB */
2979
2980 /* Number of operations completed */
2981 int operations_completed;
2982
2983 /* Cumulative offset of all completed operations */
2984 int64_t offset_completed;
2985
2986 Qcow2AmendOperation last_operation;
2987 int64_t last_work_size;
2988} Qcow2AmendHelperCBInfo;
2989
2990static void qcow2_amend_helper_cb(BlockDriverState *bs,
2991 int64_t operation_offset,
2992 int64_t operation_work_size, void *opaque)
2993{
2994 Qcow2AmendHelperCBInfo *info = opaque;
2995 int64_t current_work_size;
2996 int64_t projected_work_size;
2997
2998 if (info->current_operation != info->last_operation) {
2999 if (info->last_operation != QCOW2_NO_OPERATION) {
3000 info->offset_completed += info->last_work_size;
3001 info->operations_completed++;
3002 }
3003
3004 info->last_operation = info->current_operation;
3005 }
3006
3007 assert(info->total_operations > 0);
3008 assert(info->operations_completed < info->total_operations);
3009
3010 info->last_work_size = operation_work_size;
3011
3012 current_work_size = info->offset_completed + operation_work_size;
3013
3014 /* current_work_size is the total work size for (operations_completed + 1)
3015 * operations (which includes this one), so multiply it by the number of
3016 * operations not covered and divide it by the number of operations
3017 * covered to get a projection for the operations not covered */
3018 projected_work_size = current_work_size * (info->total_operations -
3019 info->operations_completed - 1)
3020 / (info->operations_completed + 1);
3021
3022 info->original_status_cb(bs, info->offset_completed + operation_offset,
3023 current_work_size + projected_work_size,
3024 info->original_cb_opaque);
3025}
3026
77485434 3027static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
8b13976d
HR
3028 BlockDriverAmendStatusCB *status_cb,
3029 void *cb_opaque)
9296b3ed 3030{
ff99129a 3031 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
3032 int old_version = s->qcow_version, new_version = old_version;
3033 uint64_t new_size = 0;
3034 const char *backing_file = NULL, *backing_format = NULL;
3035 bool lazy_refcounts = s->use_lazy_refcounts;
1bd0e2d1
CL
3036 const char *compat = NULL;
3037 uint64_t cluster_size = s->cluster_size;
3038 bool encrypt;
61ce55fc 3039 int refcount_bits = s->refcount_bits;
9296b3ed 3040 int ret;
1bd0e2d1 3041 QemuOptDesc *desc = opts->list->desc;
c293a809 3042 Qcow2AmendHelperCBInfo helper_cb_info;
9296b3ed 3043
1bd0e2d1
CL
3044 while (desc && desc->name) {
3045 if (!qemu_opt_find(opts, desc->name)) {
9296b3ed 3046 /* only change explicitly defined options */
1bd0e2d1 3047 desc++;
9296b3ed
HR
3048 continue;
3049 }
3050
8a17b83c
HR
3051 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
3052 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
1bd0e2d1 3053 if (!compat) {
9296b3ed 3054 /* preserve default */
1bd0e2d1 3055 } else if (!strcmp(compat, "0.10")) {
9296b3ed 3056 new_version = 2;
1bd0e2d1 3057 } else if (!strcmp(compat, "1.1")) {
9296b3ed
HR
3058 new_version = 3;
3059 } else {
29d72431 3060 error_report("Unknown compatibility level %s", compat);
9296b3ed
HR
3061 return -EINVAL;
3062 }
8a17b83c 3063 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
29d72431 3064 error_report("Cannot change preallocation mode");
9296b3ed 3065 return -ENOTSUP;
8a17b83c
HR
3066 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
3067 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3068 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
3069 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3070 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
3071 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3072 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
3073 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
f6fa64f6
DB
3074 !!s->cipher);
3075
3076 if (encrypt != !!s->cipher) {
29d72431 3077 error_report("Changing the encryption flag is not supported");
9296b3ed
HR
3078 return -ENOTSUP;
3079 }
8a17b83c
HR
3080 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
3081 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
1bd0e2d1
CL
3082 cluster_size);
3083 if (cluster_size != s->cluster_size) {
29d72431 3084 error_report("Changing the cluster size is not supported");
9296b3ed
HR
3085 return -ENOTSUP;
3086 }
8a17b83c
HR
3087 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
3088 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
1bd0e2d1 3089 lazy_refcounts);
06d05fa7 3090 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
61ce55fc
HR
3091 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
3092 refcount_bits);
3093
3094 if (refcount_bits <= 0 || refcount_bits > 64 ||
3095 !is_power_of_2(refcount_bits))
3096 {
3097 error_report("Refcount width must be a power of two and may "
3098 "not exceed 64 bits");
3099 return -EINVAL;
3100 }
9296b3ed 3101 } else {
164e0f89 3102 /* if this point is reached, this probably means a new option was
9296b3ed 3103 * added without having it covered here */
164e0f89 3104 abort();
9296b3ed 3105 }
1bd0e2d1
CL
3106
3107 desc++;
9296b3ed
HR
3108 }
3109
c293a809
HR
3110 helper_cb_info = (Qcow2AmendHelperCBInfo){
3111 .original_status_cb = status_cb,
3112 .original_cb_opaque = cb_opaque,
3113 .total_operations = (new_version < old_version)
61ce55fc 3114 + (s->refcount_bits != refcount_bits)
c293a809
HR
3115 };
3116
1038bbb8
HR
3117 /* Upgrade first (some features may require compat=1.1) */
3118 if (new_version > old_version) {
3119 s->qcow_version = new_version;
3120 ret = qcow2_update_header(bs);
3121 if (ret < 0) {
3122 s->qcow_version = old_version;
3123 return ret;
9296b3ed
HR
3124 }
3125 }
3126
61ce55fc
HR
3127 if (s->refcount_bits != refcount_bits) {
3128 int refcount_order = ctz32(refcount_bits);
3129 Error *local_error = NULL;
3130
3131 if (new_version < 3 && refcount_bits != 16) {
3132 error_report("Different refcount widths than 16 bits require "
3133 "compatibility level 1.1 or above (use compat=1.1 or "
3134 "greater)");
3135 return -EINVAL;
3136 }
3137
3138 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
3139 ret = qcow2_change_refcount_order(bs, refcount_order,
3140 &qcow2_amend_helper_cb,
3141 &helper_cb_info, &local_error);
3142 if (ret < 0) {
3143 error_report_err(local_error);
3144 return ret;
3145 }
3146 }
3147
9296b3ed 3148 if (backing_file || backing_format) {
e4603fe1
KW
3149 ret = qcow2_change_backing_file(bs,
3150 backing_file ?: s->image_backing_file,
3151 backing_format ?: s->image_backing_format);
9296b3ed
HR
3152 if (ret < 0) {
3153 return ret;
3154 }
3155 }
3156
3157 if (s->use_lazy_refcounts != lazy_refcounts) {
3158 if (lazy_refcounts) {
1038bbb8 3159 if (new_version < 3) {
29d72431
HR
3160 error_report("Lazy refcounts only supported with compatibility "
3161 "level 1.1 and above (use compat=1.1 or greater)");
9296b3ed
HR
3162 return -EINVAL;
3163 }
3164 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3165 ret = qcow2_update_header(bs);
3166 if (ret < 0) {
3167 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3168 return ret;
3169 }
3170 s->use_lazy_refcounts = true;
3171 } else {
3172 /* make image clean first */
3173 ret = qcow2_mark_clean(bs);
3174 if (ret < 0) {
3175 return ret;
3176 }
3177 /* now disallow lazy refcounts */
3178 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3179 ret = qcow2_update_header(bs);
3180 if (ret < 0) {
3181 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3182 return ret;
3183 }
3184 s->use_lazy_refcounts = false;
3185 }
3186 }
3187
3188 if (new_size) {
3189 ret = bdrv_truncate(bs, new_size);
3190 if (ret < 0) {
3191 return ret;
3192 }
3193 }
3194
1038bbb8
HR
3195 /* Downgrade last (so unsupported features can be removed before) */
3196 if (new_version < old_version) {
c293a809
HR
3197 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3198 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3199 &helper_cb_info);
1038bbb8
HR
3200 if (ret < 0) {
3201 return ret;
3202 }
3203 }
3204
9296b3ed
HR
3205 return 0;
3206}
3207
85186ebd
HR
3208/*
3209 * If offset or size are negative, respectively, they will not be included in
3210 * the BLOCK_IMAGE_CORRUPTED event emitted.
3211 * fatal will be ignored for read-only BDS; corruptions found there will always
3212 * be considered non-fatal.
3213 */
3214void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
3215 int64_t size, const char *message_format, ...)
3216{
ff99129a 3217 BDRVQcow2State *s = bs->opaque;
dc881b44 3218 const char *node_name;
85186ebd
HR
3219 char *message;
3220 va_list ap;
3221
3222 fatal = fatal && !bs->read_only;
3223
3224 if (s->signaled_corruption &&
3225 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
3226 {
3227 return;
3228 }
3229
3230 va_start(ap, message_format);
3231 message = g_strdup_vprintf(message_format, ap);
3232 va_end(ap);
3233
3234 if (fatal) {
3235 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
3236 "corruption events will be suppressed\n", message);
3237 } else {
3238 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
3239 "corruption events will be suppressed\n", message);
3240 }
3241
dc881b44
AG
3242 node_name = bdrv_get_node_name(bs);
3243 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3244 *node_name != '\0', node_name,
3245 message, offset >= 0, offset,
3246 size >= 0, size,
85186ebd
HR
3247 fatal, &error_abort);
3248 g_free(message);
3249
3250 if (fatal) {
3251 qcow2_mark_corrupt(bs);
3252 bs->drv = NULL; /* make BDS unusable */
3253 }
3254
3255 s->signaled_corruption = true;
3256}
3257
1bd0e2d1
CL
3258static QemuOptsList qcow2_create_opts = {
3259 .name = "qcow2-create-opts",
3260 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
3261 .desc = {
3262 {
3263 .name = BLOCK_OPT_SIZE,
3264 .type = QEMU_OPT_SIZE,
3265 .help = "Virtual disk size"
3266 },
3267 {
3268 .name = BLOCK_OPT_COMPAT_LEVEL,
3269 .type = QEMU_OPT_STRING,
3270 .help = "Compatibility level (0.10 or 1.1)"
3271 },
3272 {
3273 .name = BLOCK_OPT_BACKING_FILE,
3274 .type = QEMU_OPT_STRING,
3275 .help = "File name of a base image"
3276 },
3277 {
3278 .name = BLOCK_OPT_BACKING_FMT,
3279 .type = QEMU_OPT_STRING,
3280 .help = "Image format of the base image"
3281 },
3282 {
3283 .name = BLOCK_OPT_ENCRYPT,
3284 .type = QEMU_OPT_BOOL,
3285 .help = "Encrypt the image",
3286 .def_value_str = "off"
3287 },
3288 {
3289 .name = BLOCK_OPT_CLUSTER_SIZE,
3290 .type = QEMU_OPT_SIZE,
3291 .help = "qcow2 cluster size",
3292 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3293 },
3294 {
3295 .name = BLOCK_OPT_PREALLOC,
3296 .type = QEMU_OPT_STRING,
0e4271b7
HT
3297 .help = "Preallocation mode (allowed values: off, metadata, "
3298 "falloc, full)"
1bd0e2d1
CL
3299 },
3300 {
3301 .name = BLOCK_OPT_LAZY_REFCOUNTS,
3302 .type = QEMU_OPT_BOOL,
3303 .help = "Postpone refcount updates",
3304 .def_value_str = "off"
3305 },
06d05fa7
HR
3306 {
3307 .name = BLOCK_OPT_REFCOUNT_BITS,
3308 .type = QEMU_OPT_NUMBER,
3309 .help = "Width of a reference count entry in bits",
3310 .def_value_str = "16"
3311 },
1bd0e2d1
CL
3312 { /* end of list */ }
3313 }
20d97356
BS
3314};
3315
5f535a94 3316BlockDriver bdrv_qcow2 = {
7c80ab3f 3317 .format_name = "qcow2",
ff99129a 3318 .instance_size = sizeof(BDRVQcow2State),
7c80ab3f
JS
3319 .bdrv_probe = qcow2_probe,
3320 .bdrv_open = qcow2_open,
3321 .bdrv_close = qcow2_close,
21d82ac9 3322 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5b0959a7
KW
3323 .bdrv_reopen_commit = qcow2_reopen_commit,
3324 .bdrv_reopen_abort = qcow2_reopen_abort,
5365f44d 3325 .bdrv_join_options = qcow2_join_options,
c282e1fd 3326 .bdrv_create = qcow2_create,
3ac21627 3327 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 3328 .bdrv_co_get_block_status = qcow2_co_get_block_status,
7c80ab3f 3329 .bdrv_set_key = qcow2_set_key,
7c80ab3f 3330
c68b89ac
KW
3331 .bdrv_co_readv = qcow2_co_readv,
3332 .bdrv_co_writev = qcow2_co_writev,
eb489bb1 3333 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 3334
621f0589 3335 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
6db39ae2 3336 .bdrv_co_discard = qcow2_co_discard,
419b19d9 3337 .bdrv_truncate = qcow2_truncate,
7c80ab3f 3338 .bdrv_write_compressed = qcow2_write_compressed,
491d27e2 3339 .bdrv_make_empty = qcow2_make_empty,
20d97356
BS
3340
3341 .bdrv_snapshot_create = qcow2_snapshot_create,
3342 .bdrv_snapshot_goto = qcow2_snapshot_goto,
3343 .bdrv_snapshot_delete = qcow2_snapshot_delete,
3344 .bdrv_snapshot_list = qcow2_snapshot_list,
1bd0e2d1
CL
3345 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3346 .bdrv_get_info = qcow2_get_info,
37764dfb 3347 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 3348
7c80ab3f
JS
3349 .bdrv_save_vmstate = qcow2_save_vmstate,
3350 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356 3351
8ee79e70 3352 .supports_backing = true,
20d97356
BS
3353 .bdrv_change_backing_file = qcow2_change_backing_file,
3354
d34682cd 3355 .bdrv_refresh_limits = qcow2_refresh_limits,
06d9260f 3356 .bdrv_invalidate_cache = qcow2_invalidate_cache,
ec6d8912 3357 .bdrv_inactivate = qcow2_inactivate,
06d9260f 3358
1bd0e2d1
CL
3359 .create_opts = &qcow2_create_opts,
3360 .bdrv_check = qcow2_check,
c282e1fd 3361 .bdrv_amend_options = qcow2_amend_options,
279621c0
AG
3362
3363 .bdrv_detach_aio_context = qcow2_detach_aio_context,
3364 .bdrv_attach_aio_context = qcow2_attach_aio_context,
20d97356
BS
3365};
3366
5efa9d5a
AL
3367static void bdrv_qcow2_init(void)
3368{
3369 bdrv_register(&bdrv_qcow2);
3370}
3371
3372block_init(bdrv_qcow2_init);