]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
qemu-iotests: Make debugging python tests easier
[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 */
faf07963 24#include "qemu-common.h"
737e150e 25#include "block/block_int.h"
1de7afc9 26#include "qemu/module.h"
585f8587 27#include <zlib.h>
753d9b82 28#include "qemu/aes.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{
75bab85c 89 BDRVQcowState *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
3ef6c40a
HR
108 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
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 }
3ef6c40a
HR
136 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
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));
152 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
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
173 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
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{
191 BDRVQcowState *s = bs->opaque;
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
bfb197e0 210 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
81e5f78a 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
SH
252{
253 BDRVQcowState *s = bs->opaque;
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);
264 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
265 &val, sizeof(val));
266 if (ret < 0) {
267 return ret;
268 }
269 ret = bdrv_flush(bs->file);
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{
286 BDRVQcowState *s = bs->opaque;
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{
308 BDRVQcowState *s = bs->opaque;
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{
320 BDRVQcowState *s = bs->opaque;
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{
355 BDRVQcowState *s = bs->opaque;
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 },
74c4510a
KW
471 { /* end of list */ }
472 },
473};
474
4092e99d
HR
475static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
476 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
477 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
478 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
479 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
480 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
481 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
482 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
483 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
484};
485
6c1c8d5d
HR
486static void read_cache_sizes(QemuOpts *opts, uint64_t *l2_cache_size,
487 uint64_t *refcount_cache_size, Error **errp)
488{
489 uint64_t combined_cache_size;
490 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
491
492 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
493 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
494 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
495
496 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
497 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
498 *refcount_cache_size = qemu_opt_get_size(opts,
499 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
500
501 if (combined_cache_size_set) {
502 if (l2_cache_size_set && refcount_cache_size_set) {
503 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
504 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
505 "the same time");
506 return;
507 } else if (*l2_cache_size > combined_cache_size) {
508 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
509 QCOW2_OPT_CACHE_SIZE);
510 return;
511 } else if (*refcount_cache_size > combined_cache_size) {
512 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
513 QCOW2_OPT_CACHE_SIZE);
514 return;
515 }
516
517 if (l2_cache_size_set) {
518 *refcount_cache_size = combined_cache_size - *l2_cache_size;
519 } else if (refcount_cache_size_set) {
520 *l2_cache_size = combined_cache_size - *refcount_cache_size;
521 } else {
522 *refcount_cache_size = combined_cache_size
523 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
524 *l2_cache_size = combined_cache_size - *refcount_cache_size;
525 }
526 } else {
527 if (!l2_cache_size_set && !refcount_cache_size_set) {
528 *l2_cache_size = DEFAULT_L2_CACHE_BYTE_SIZE;
529 *refcount_cache_size = *l2_cache_size
530 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
531 } else if (!l2_cache_size_set) {
532 *l2_cache_size = *refcount_cache_size
533 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
534 } else if (!refcount_cache_size_set) {
535 *refcount_cache_size = *l2_cache_size
536 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
537 }
538 }
539}
540
015a1036
HR
541static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
542 Error **errp)
585f8587
FB
543{
544 BDRVQcowState *s = bs->opaque;
6d33e8e7
KW
545 unsigned int len, i;
546 int ret = 0;
585f8587 547 QCowHeader header;
7b17ce60 548 QemuOpts *opts = NULL;
74c4510a 549 Error *local_err = NULL;
9b80ddf3 550 uint64_t ext_end;
2cf7cfa1 551 uint64_t l1_vm_state_index;
ee42b5ce 552 const char *opt_overlap_check, *opt_overlap_check_template;
1fa5cc83 553 int overlap_check_template = 0;
440ba08a 554 uint64_t l2_cache_size, refcount_cache_size;
585f8587 555
6d85a57e
JS
556 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
557 if (ret < 0) {
3ef6c40a 558 error_setg_errno(errp, -ret, "Could not read qcow2 header");
585f8587 559 goto fail;
6d85a57e 560 }
585f8587
FB
561 be32_to_cpus(&header.magic);
562 be32_to_cpus(&header.version);
563 be64_to_cpus(&header.backing_file_offset);
564 be32_to_cpus(&header.backing_file_size);
565 be64_to_cpus(&header.size);
566 be32_to_cpus(&header.cluster_bits);
567 be32_to_cpus(&header.crypt_method);
568 be64_to_cpus(&header.l1_table_offset);
569 be32_to_cpus(&header.l1_size);
570 be64_to_cpus(&header.refcount_table_offset);
571 be32_to_cpus(&header.refcount_table_clusters);
572 be64_to_cpus(&header.snapshots_offset);
573 be32_to_cpus(&header.nb_snapshots);
3b46e624 574
e8cdcec1 575 if (header.magic != QCOW_MAGIC) {
3ef6c40a 576 error_setg(errp, "Image is not in qcow2 format");
76abe407 577 ret = -EINVAL;
585f8587 578 goto fail;
6d85a57e 579 }
6744cbab 580 if (header.version < 2 || header.version > 3) {
521b2b5d 581 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
6744cbab
KW
582 ret = -ENOTSUP;
583 goto fail;
584 }
585
586 s->qcow_version = header.version;
587
24342f2c
KW
588 /* Initialise cluster size */
589 if (header.cluster_bits < MIN_CLUSTER_BITS ||
590 header.cluster_bits > MAX_CLUSTER_BITS) {
521b2b5d
HR
591 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
592 header.cluster_bits);
24342f2c
KW
593 ret = -EINVAL;
594 goto fail;
595 }
596
597 s->cluster_bits = header.cluster_bits;
598 s->cluster_size = 1 << s->cluster_bits;
599 s->cluster_sectors = 1 << (s->cluster_bits - 9);
600
6744cbab
KW
601 /* Initialise version 3 header fields */
602 if (header.version == 2) {
603 header.incompatible_features = 0;
604 header.compatible_features = 0;
605 header.autoclear_features = 0;
606 header.refcount_order = 4;
607 header.header_length = 72;
608 } else {
609 be64_to_cpus(&header.incompatible_features);
610 be64_to_cpus(&header.compatible_features);
611 be64_to_cpus(&header.autoclear_features);
612 be32_to_cpus(&header.refcount_order);
613 be32_to_cpus(&header.header_length);
24342f2c
KW
614
615 if (header.header_length < 104) {
616 error_setg(errp, "qcow2 header too short");
617 ret = -EINVAL;
618 goto fail;
619 }
620 }
621
622 if (header.header_length > s->cluster_size) {
623 error_setg(errp, "qcow2 header exceeds cluster size");
624 ret = -EINVAL;
625 goto fail;
6744cbab
KW
626 }
627
628 if (header.header_length > sizeof(header)) {
629 s->unknown_header_fields_size = header.header_length - sizeof(header);
630 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
631 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
632 s->unknown_header_fields_size);
633 if (ret < 0) {
3ef6c40a
HR
634 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
635 "fields");
6744cbab
KW
636 goto fail;
637 }
638 }
639
a1b3955c
KW
640 if (header.backing_file_offset > s->cluster_size) {
641 error_setg(errp, "Invalid backing file offset");
642 ret = -EINVAL;
643 goto fail;
644 }
645
cfcc4c62
KW
646 if (header.backing_file_offset) {
647 ext_end = header.backing_file_offset;
648 } else {
649 ext_end = 1 << header.cluster_bits;
650 }
651
6744cbab
KW
652 /* Handle feature bits */
653 s->incompatible_features = header.incompatible_features;
654 s->compatible_features = header.compatible_features;
655 s->autoclear_features = header.autoclear_features;
656
c61d0004 657 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
cfcc4c62
KW
658 void *feature_table = NULL;
659 qcow2_read_extensions(bs, header.header_length, ext_end,
3ef6c40a
HR
660 &feature_table, NULL);
661 report_unsupported_feature(bs, errp, feature_table,
c61d0004
SH
662 s->incompatible_features &
663 ~QCOW2_INCOMPAT_MASK);
6744cbab 664 ret = -ENOTSUP;
c5a33ee9 665 g_free(feature_table);
6744cbab
KW
666 goto fail;
667 }
668
69c98726
HR
669 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
670 /* Corrupt images may not be written to unless they are being repaired
671 */
672 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
3ef6c40a
HR
673 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
674 "read/write");
69c98726
HR
675 ret = -EACCES;
676 goto fail;
677 }
678 }
679
6744cbab 680 /* Check support for various header values */
b72faf9f
HR
681 if (header.refcount_order > 6) {
682 error_setg(errp, "Reference count entry width too large; may not "
683 "exceed 64 bits");
684 ret = -EINVAL;
e8cdcec1
KW
685 goto fail;
686 }
b6481f37 687 s->refcount_order = header.refcount_order;
346a53df
HR
688 s->refcount_bits = 1 << s->refcount_order;
689 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
690 s->refcount_max += s->refcount_max - 1;
6744cbab 691
6d85a57e 692 if (header.crypt_method > QCOW_CRYPT_AES) {
521b2b5d 693 error_setg(errp, "Unsupported encryption method: %" PRIu32,
3ef6c40a 694 header.crypt_method);
6d85a57e 695 ret = -EINVAL;
585f8587 696 goto fail;
6d85a57e 697 }
585f8587 698 s->crypt_method_header = header.crypt_method;
6d85a57e 699 if (s->crypt_method_header) {
585f8587 700 bs->encrypted = 1;
6d85a57e 701 }
24342f2c 702
585f8587
FB
703 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
704 s->l2_size = 1 << s->l2_bits;
1d13d654
HR
705 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
706 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
707 s->refcount_block_size = 1 << s->refcount_block_bits;
585f8587
FB
708 bs->total_sectors = header.size / 512;
709 s->csize_shift = (62 - (s->cluster_bits - 8));
710 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
711 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
5dab2fad 712
585f8587 713 s->refcount_table_offset = header.refcount_table_offset;
5fafdf24 714 s->refcount_table_size =
585f8587
FB
715 header.refcount_table_clusters << (s->cluster_bits - 3);
716
2b5d5953 717 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
5dab2fad
KW
718 error_setg(errp, "Reference count table too large");
719 ret = -EINVAL;
720 goto fail;
721 }
722
8c7de283
KW
723 ret = validate_table_offset(bs, s->refcount_table_offset,
724 s->refcount_table_size, sizeof(uint64_t));
725 if (ret < 0) {
726 error_setg(errp, "Invalid reference count table offset");
727 goto fail;
728 }
729
ce48f2f4
KW
730 /* Snapshot table offset/length */
731 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
732 error_setg(errp, "Too many snapshots");
733 ret = -EINVAL;
734 goto fail;
735 }
736
737 ret = validate_table_offset(bs, header.snapshots_offset,
738 header.nb_snapshots,
739 sizeof(QCowSnapshotHeader));
740 if (ret < 0) {
741 error_setg(errp, "Invalid snapshot table offset");
742 goto fail;
743 }
744
585f8587 745 /* read the level 1 table */
87b86e7e 746 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
2d51c32c
KW
747 error_setg(errp, "Active L1 table too large");
748 ret = -EFBIG;
749 goto fail;
750 }
585f8587 751 s->l1_size = header.l1_size;
2cf7cfa1
KW
752
753 l1_vm_state_index = size_to_l1(s, header.size);
754 if (l1_vm_state_index > INT_MAX) {
3ef6c40a 755 error_setg(errp, "Image is too big");
2cf7cfa1
KW
756 ret = -EFBIG;
757 goto fail;
758 }
759 s->l1_vm_state_index = l1_vm_state_index;
760
585f8587
FB
761 /* the L1 table must contain at least enough entries to put
762 header.size bytes */
6d85a57e 763 if (s->l1_size < s->l1_vm_state_index) {
3ef6c40a 764 error_setg(errp, "L1 table is too small");
6d85a57e 765 ret = -EINVAL;
585f8587 766 goto fail;
6d85a57e 767 }
2d51c32c
KW
768
769 ret = validate_table_offset(bs, header.l1_table_offset,
770 header.l1_size, sizeof(uint64_t));
771 if (ret < 0) {
772 error_setg(errp, "Invalid L1 table offset");
773 goto fail;
774 }
585f8587 775 s->l1_table_offset = header.l1_table_offset;
2d51c32c
KW
776
777
d191d12d 778 if (s->l1_size > 0) {
de82815d 779 s->l1_table = qemu_try_blockalign(bs->file,
d191d12d 780 align_offset(s->l1_size * sizeof(uint64_t), 512));
de82815d
KW
781 if (s->l1_table == NULL) {
782 error_setg(errp, "Could not allocate L1 table");
783 ret = -ENOMEM;
784 goto fail;
785 }
6d85a57e
JS
786 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
787 s->l1_size * sizeof(uint64_t));
788 if (ret < 0) {
3ef6c40a 789 error_setg_errno(errp, -ret, "Could not read L1 table");
d191d12d 790 goto fail;
6d85a57e 791 }
d191d12d
SW
792 for(i = 0;i < s->l1_size; i++) {
793 be64_to_cpus(&s->l1_table[i]);
794 }
585f8587 795 }
29c1a730 796
6c1c8d5d
HR
797 /* get L2 table/refcount block cache size from command line options */
798 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
799 qemu_opts_absorb_qdict(opts, options, &local_err);
800 if (local_err) {
801 error_propagate(errp, local_err);
802 ret = -EINVAL;
803 goto fail;
804 }
805
806 read_cache_sizes(opts, &l2_cache_size, &refcount_cache_size, &local_err);
807 if (local_err) {
808 error_propagate(errp, local_err);
809 ret = -EINVAL;
810 goto fail;
811 }
812
813 l2_cache_size /= s->cluster_size;
440ba08a
HR
814 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
815 l2_cache_size = MIN_L2_CACHE_SIZE;
816 }
6c1c8d5d
HR
817 if (l2_cache_size > INT_MAX) {
818 error_setg(errp, "L2 cache size too big");
819 ret = -EINVAL;
820 goto fail;
821 }
440ba08a 822
6c1c8d5d 823 refcount_cache_size /= s->cluster_size;
440ba08a
HR
824 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
825 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
826 }
6c1c8d5d
HR
827 if (refcount_cache_size > INT_MAX) {
828 error_setg(errp, "Refcount cache size too big");
829 ret = -EINVAL;
830 goto fail;
831 }
440ba08a 832
6c1c8d5d 833 /* alloc L2 table/refcount block cache */
440ba08a
HR
834 s->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
835 s->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
de82815d
KW
836 if (s->l2_table_cache == NULL || s->refcount_block_cache == NULL) {
837 error_setg(errp, "Could not allocate metadata caches");
838 ret = -ENOMEM;
839 goto fail;
840 }
29c1a730 841
7267c094 842 s->cluster_cache = g_malloc(s->cluster_size);
585f8587 843 /* one more sector for decompressed data alignment */
de82815d
KW
844 s->cluster_data = qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
845 * s->cluster_size + 512);
846 if (s->cluster_data == NULL) {
847 error_setg(errp, "Could not allocate temporary cluster buffer");
848 ret = -ENOMEM;
849 goto fail;
850 }
851
585f8587 852 s->cluster_cache_offset = -1;
06d9260f 853 s->flags = flags;
3b46e624 854
6d85a57e
JS
855 ret = qcow2_refcount_init(bs);
856 if (ret != 0) {
3ef6c40a 857 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
585f8587 858 goto fail;
6d85a57e 859 }
585f8587 860
72cf2d4f 861 QLIST_INIT(&s->cluster_allocs);
0b919fae 862 QTAILQ_INIT(&s->discards);
f214978a 863
9b80ddf3 864 /* read qcow2 extensions */
3ef6c40a
HR
865 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
866 &local_err)) {
867 error_propagate(errp, local_err);
6d85a57e 868 ret = -EINVAL;
9b80ddf3 869 goto fail;
6d85a57e 870 }
9b80ddf3 871
585f8587
FB
872 /* read the backing file name */
873 if (header.backing_file_offset != 0) {
874 len = header.backing_file_size;
9a29e18f 875 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
e729fa6a 876 len >= sizeof(bs->backing_file)) {
6d33e8e7
KW
877 error_setg(errp, "Backing file name too long");
878 ret = -EINVAL;
879 goto fail;
6d85a57e
JS
880 }
881 ret = bdrv_pread(bs->file, header.backing_file_offset,
882 bs->backing_file, len);
883 if (ret < 0) {
3ef6c40a 884 error_setg_errno(errp, -ret, "Could not read backing file name");
585f8587 885 goto fail;
6d85a57e 886 }
585f8587 887 bs->backing_file[len] = '\0';
e4603fe1 888 s->image_backing_file = g_strdup(bs->backing_file);
585f8587 889 }
42deb29f 890
11b128f4
KW
891 /* Internal snapshots */
892 s->snapshots_offset = header.snapshots_offset;
893 s->nb_snapshots = header.nb_snapshots;
894
42deb29f
KW
895 ret = qcow2_read_snapshots(bs);
896 if (ret < 0) {
3ef6c40a 897 error_setg_errno(errp, -ret, "Could not read snapshots");
585f8587 898 goto fail;
6d85a57e 899 }
585f8587 900
af7b708d 901 /* Clear unknown autoclear feature bits */
27eb6c09 902 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
af7b708d
SH
903 s->autoclear_features = 0;
904 ret = qcow2_update_header(bs);
905 if (ret < 0) {
3ef6c40a 906 error_setg_errno(errp, -ret, "Could not update qcow2 header");
af7b708d
SH
907 goto fail;
908 }
909 }
910
68d100e9
KW
911 /* Initialise locks */
912 qemu_co_mutex_init(&s->lock);
913
c61d0004 914 /* Repair image if dirty */
27eb6c09 915 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
058f8f16 916 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
c61d0004
SH
917 BdrvCheckResult result = {0};
918
5b84106b 919 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
c61d0004 920 if (ret < 0) {
3ef6c40a 921 error_setg_errno(errp, -ret, "Could not repair dirty image");
c61d0004
SH
922 goto fail;
923 }
924 }
925
74c4510a 926 /* Enable lazy_refcounts according to image and command line options */
acdfb480 927 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
74c4510a
KW
928 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
929
67af674e
KW
930 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
931 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
932 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
933 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
934 flags & BDRV_O_UNMAP);
935 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
936 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
937 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
938 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
939
ee42b5ce
HR
940 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
941 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
942 if (opt_overlap_check_template && opt_overlap_check &&
943 strcmp(opt_overlap_check_template, opt_overlap_check))
944 {
945 error_setg(errp, "Conflicting values for qcow2 options '"
946 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
947 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
948 ret = -EINVAL;
949 goto fail;
950 }
951 if (!opt_overlap_check) {
952 opt_overlap_check = opt_overlap_check_template ?: "cached";
953 }
954
1fa5cc83
HR
955 if (!strcmp(opt_overlap_check, "none")) {
956 overlap_check_template = 0;
957 } else if (!strcmp(opt_overlap_check, "constant")) {
958 overlap_check_template = QCOW2_OL_CONSTANT;
959 } else if (!strcmp(opt_overlap_check, "cached")) {
960 overlap_check_template = QCOW2_OL_CACHED;
961 } else if (!strcmp(opt_overlap_check, "all")) {
962 overlap_check_template = QCOW2_OL_ALL;
963 } else {
964 error_setg(errp, "Unsupported value '%s' for qcow2 option "
965 "'overlap-check'. Allowed are either of the following: "
966 "none, constant, cached, all", opt_overlap_check);
1fa5cc83
HR
967 ret = -EINVAL;
968 goto fail;
969 }
970
971 s->overlap_check = 0;
972 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
973 /* overlap-check defines a template bitmask, but every flag may be
974 * overwritten through the associated boolean option */
975 s->overlap_check |=
976 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
977 overlap_check_template & (1 << i)) << i;
978 }
3e355390 979
74c4510a 980 qemu_opts_del(opts);
7b17ce60 981 opts = NULL;
74c4510a
KW
982
983 if (s->use_lazy_refcounts && s->qcow_version < 3) {
3ef6c40a
HR
984 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
985 "qemu 1.1 compatibility level");
74c4510a
KW
986 ret = -EINVAL;
987 goto fail;
988 }
989
585f8587 990#ifdef DEBUG_ALLOC
6cbc3031
PH
991 {
992 BdrvCheckResult result = {0};
b35278f7 993 qcow2_check_refcounts(bs, &result, 0);
6cbc3031 994 }
585f8587 995#endif
6d85a57e 996 return ret;
585f8587
FB
997
998 fail:
7b17ce60 999 qemu_opts_del(opts);
6744cbab 1000 g_free(s->unknown_header_fields);
75bab85c 1001 cleanup_unknown_header_ext(bs);
ed6ccf0f
KW
1002 qcow2_free_snapshots(bs);
1003 qcow2_refcount_close(bs);
de82815d 1004 qemu_vfree(s->l1_table);
cf93980e
HR
1005 /* else pre-write overlap checks in cache_destroy may crash */
1006 s->l1_table = NULL;
29c1a730
KW
1007 if (s->l2_table_cache) {
1008 qcow2_cache_destroy(bs, s->l2_table_cache);
1009 }
c5a33ee9
PJ
1010 if (s->refcount_block_cache) {
1011 qcow2_cache_destroy(bs, s->refcount_block_cache);
1012 }
7267c094 1013 g_free(s->cluster_cache);
dea43a65 1014 qemu_vfree(s->cluster_data);
6d85a57e 1015 return ret;
585f8587
FB
1016}
1017
3baca891 1018static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
d34682cd
KW
1019{
1020 BDRVQcowState *s = bs->opaque;
1021
1022 bs->bl.write_zeroes_alignment = s->cluster_sectors;
d34682cd
KW
1023}
1024
7c80ab3f 1025static int qcow2_set_key(BlockDriverState *bs, const char *key)
585f8587
FB
1026{
1027 BDRVQcowState *s = bs->opaque;
1028 uint8_t keybuf[16];
1029 int len, i;
3b46e624 1030
585f8587
FB
1031 memset(keybuf, 0, 16);
1032 len = strlen(key);
1033 if (len > 16)
1034 len = 16;
1035 /* XXX: we could compress the chars to 7 bits to increase
1036 entropy */
1037 for(i = 0;i < len;i++) {
1038 keybuf[i] = key[i];
1039 }
1040 s->crypt_method = s->crypt_method_header;
1041
1042 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
1043 return -1;
1044 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
1045 return -1;
1046#if 0
1047 /* test */
1048 {
1049 uint8_t in[16];
1050 uint8_t out[16];
1051 uint8_t tmp[16];
1052 for(i=0;i<16;i++)
1053 in[i] = i;
1054 AES_encrypt(in, tmp, &s->aes_encrypt_key);
1055 AES_decrypt(tmp, out, &s->aes_decrypt_key);
1056 for(i = 0; i < 16; i++)
1057 printf(" %02x", tmp[i]);
1058 printf("\n");
1059 for(i = 0; i < 16; i++)
1060 printf(" %02x", out[i]);
1061 printf("\n");
1062 }
1063#endif
1064 return 0;
1065}
1066
4c2e5f8f
KW
1067/* We have no actual commit/abort logic for qcow2, but we need to write out any
1068 * unwritten data if we reopen read-only. */
21d82ac9
JC
1069static int qcow2_reopen_prepare(BDRVReopenState *state,
1070 BlockReopenQueue *queue, Error **errp)
1071{
4c2e5f8f
KW
1072 int ret;
1073
1074 if ((state->flags & BDRV_O_RDWR) == 0) {
1075 ret = bdrv_flush(state->bs);
1076 if (ret < 0) {
1077 return ret;
1078 }
1079
1080 ret = qcow2_mark_clean(state->bs);
1081 if (ret < 0) {
1082 return ret;
1083 }
1084 }
1085
21d82ac9
JC
1086 return 0;
1087}
1088
b6b8a333 1089static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
f8a2e5e3 1090 int64_t sector_num, int nb_sectors, int *pnum)
585f8587 1091{
f8a2e5e3 1092 BDRVQcowState *s = bs->opaque;
585f8587 1093 uint64_t cluster_offset;
4bc74be9
PB
1094 int index_in_cluster, ret;
1095 int64_t status = 0;
585f8587 1096
095a9c58 1097 *pnum = nb_sectors;
f8a2e5e3 1098 qemu_co_mutex_lock(&s->lock);
1c46efaa 1099 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
f8a2e5e3 1100 qemu_co_mutex_unlock(&s->lock);
1c46efaa 1101 if (ret < 0) {
d663640c 1102 return ret;
1c46efaa 1103 }
095a9c58 1104
4bc74be9
PB
1105 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1106 !s->crypt_method) {
1107 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1108 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1109 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1110 }
1111 if (ret == QCOW2_CLUSTER_ZERO) {
1112 status |= BDRV_BLOCK_ZERO;
1113 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1114 status |= BDRV_BLOCK_DATA;
1115 }
1116 return status;
585f8587
FB
1117}
1118
a9465922 1119/* handle reading after the end of the backing file */
bd28f835
KW
1120int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1121 int64_t sector_num, int nb_sectors)
a9465922
FB
1122{
1123 int n1;
1124 if ((sector_num + nb_sectors) <= bs->total_sectors)
1125 return nb_sectors;
1126 if (sector_num >= bs->total_sectors)
1127 n1 = 0;
1128 else
1129 n1 = bs->total_sectors - sector_num;
bd28f835 1130
3d9b4925 1131 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
bd28f835 1132
a9465922
FB
1133 return n1;
1134}
1135
a968168c 1136static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
3fc48d09 1137 int remaining_sectors, QEMUIOVector *qiov)
585f8587 1138{
585f8587 1139 BDRVQcowState *s = bs->opaque;
a9465922 1140 int index_in_cluster, n1;
68d100e9 1141 int ret;
faf575c1 1142 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 1143 uint64_t cluster_offset = 0;
3fc48d09
FZ
1144 uint64_t bytes_done = 0;
1145 QEMUIOVector hd_qiov;
1146 uint8_t *cluster_data = NULL;
585f8587 1147
3fc48d09
FZ
1148 qemu_iovec_init(&hd_qiov, qiov->niov);
1149
1150 qemu_co_mutex_lock(&s->lock);
1151
1152 while (remaining_sectors != 0) {
bd28f835 1153
5ebaa27e 1154 /* prepare next request */
3fc48d09 1155 cur_nr_sectors = remaining_sectors;
5ebaa27e
FZ
1156 if (s->crypt_method) {
1157 cur_nr_sectors = MIN(cur_nr_sectors,
1158 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
585f8587 1159 }
5ebaa27e 1160
3fc48d09 1161 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
5ebaa27e 1162 &cur_nr_sectors, &cluster_offset);
8af36488 1163 if (ret < 0) {
3fc48d09 1164 goto fail;
8af36488 1165 }
bd28f835 1166
3fc48d09 1167 index_in_cluster = sector_num & (s->cluster_sectors - 1);
c87c0672 1168
3fc48d09 1169 qemu_iovec_reset(&hd_qiov);
1b093c48 1170 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e
FZ
1171 cur_nr_sectors * 512);
1172
68d000a3
KW
1173 switch (ret) {
1174 case QCOW2_CLUSTER_UNALLOCATED:
5ebaa27e
FZ
1175
1176 if (bs->backing_hd) {
1177 /* read from the base image */
3fc48d09
FZ
1178 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1179 sector_num, cur_nr_sectors);
5ebaa27e 1180 if (n1 > 0) {
44deba5a
KW
1181 QEMUIOVector local_qiov;
1182
1183 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1184 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1185 n1 * BDRV_SECTOR_SIZE);
1186
5ebaa27e
FZ
1187 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1188 qemu_co_mutex_unlock(&s->lock);
3fc48d09 1189 ret = bdrv_co_readv(bs->backing_hd, sector_num,
44deba5a 1190 n1, &local_qiov);
5ebaa27e 1191 qemu_co_mutex_lock(&s->lock);
44deba5a
KW
1192
1193 qemu_iovec_destroy(&local_qiov);
1194
5ebaa27e 1195 if (ret < 0) {
3fc48d09 1196 goto fail;
5ebaa27e
FZ
1197 }
1198 }
1199 } else {
1200 /* Note: in this case, no need to wait */
3d9b4925 1201 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
5ebaa27e 1202 }
68d000a3
KW
1203 break;
1204
6377af48 1205 case QCOW2_CLUSTER_ZERO:
3d9b4925 1206 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
6377af48
KW
1207 break;
1208
68d000a3 1209 case QCOW2_CLUSTER_COMPRESSED:
5ebaa27e
FZ
1210 /* add AIO support for compressed blocks ? */
1211 ret = qcow2_decompress_cluster(bs, cluster_offset);
1212 if (ret < 0) {
3fc48d09 1213 goto fail;
bd28f835
KW
1214 }
1215
03396148 1216 qemu_iovec_from_buf(&hd_qiov, 0,
5ebaa27e 1217 s->cluster_cache + index_in_cluster * 512,
faf575c1 1218 512 * cur_nr_sectors);
68d000a3
KW
1219 break;
1220
1221 case QCOW2_CLUSTER_NORMAL:
5ebaa27e 1222 if ((cluster_offset & 511) != 0) {
3fc48d09
FZ
1223 ret = -EIO;
1224 goto fail;
5ebaa27e 1225 }
bd28f835 1226
5ebaa27e
FZ
1227 if (s->crypt_method) {
1228 /*
1229 * For encrypted images, read everything into a temporary
1230 * contiguous buffer on which the AES functions can work.
1231 */
3fc48d09
FZ
1232 if (!cluster_data) {
1233 cluster_data =
de82815d
KW
1234 qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1235 * s->cluster_size);
1236 if (cluster_data == NULL) {
1237 ret = -ENOMEM;
1238 goto fail;
1239 }
5ebaa27e
FZ
1240 }
1241
1242 assert(cur_nr_sectors <=
1243 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
3fc48d09
FZ
1244 qemu_iovec_reset(&hd_qiov);
1245 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1246 512 * cur_nr_sectors);
1247 }
1248
1249 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1250 qemu_co_mutex_unlock(&s->lock);
1251 ret = bdrv_co_readv(bs->file,
1252 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1253 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1254 qemu_co_mutex_lock(&s->lock);
1255 if (ret < 0) {
3fc48d09 1256 goto fail;
5ebaa27e
FZ
1257 }
1258 if (s->crypt_method) {
3fc48d09
FZ
1259 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1260 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
03396148
MT
1261 qemu_iovec_from_buf(qiov, bytes_done,
1262 cluster_data, 512 * cur_nr_sectors);
5ebaa27e 1263 }
68d000a3
KW
1264 break;
1265
1266 default:
1267 g_assert_not_reached();
1268 ret = -EIO;
1269 goto fail;
faf575c1 1270 }
f141eafe 1271
3fc48d09
FZ
1272 remaining_sectors -= cur_nr_sectors;
1273 sector_num += cur_nr_sectors;
1274 bytes_done += cur_nr_sectors * 512;
5ebaa27e 1275 }
3fc48d09 1276 ret = 0;
faf575c1 1277
3fc48d09 1278fail:
68d100e9 1279 qemu_co_mutex_unlock(&s->lock);
42496d62 1280
3fc48d09 1281 qemu_iovec_destroy(&hd_qiov);
dea43a65 1282 qemu_vfree(cluster_data);
68d100e9
KW
1283
1284 return ret;
585f8587
FB
1285}
1286
a968168c 1287static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
3fc48d09
FZ
1288 int64_t sector_num,
1289 int remaining_sectors,
1290 QEMUIOVector *qiov)
585f8587 1291{
585f8587 1292 BDRVQcowState *s = bs->opaque;
585f8587 1293 int index_in_cluster;
68d100e9 1294 int ret;
faf575c1 1295 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 1296 uint64_t cluster_offset;
3fc48d09
FZ
1297 QEMUIOVector hd_qiov;
1298 uint64_t bytes_done = 0;
1299 uint8_t *cluster_data = NULL;
8d2497c3 1300 QCowL2Meta *l2meta = NULL;
c2271403 1301
3cce16f4
KW
1302 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1303 remaining_sectors);
1304
3fc48d09
FZ
1305 qemu_iovec_init(&hd_qiov, qiov->niov);
1306
1307 s->cluster_cache_offset = -1; /* disable compressed cache */
3b46e624 1308
3fc48d09
FZ
1309 qemu_co_mutex_lock(&s->lock);
1310
1311 while (remaining_sectors != 0) {
1312
f50f88b9 1313 l2meta = NULL;
cf5c1a23 1314
3cce16f4 1315 trace_qcow2_writev_start_part(qemu_coroutine_self());
3fc48d09 1316 index_in_cluster = sector_num & (s->cluster_sectors - 1);
16f0587e 1317 cur_nr_sectors = remaining_sectors;
5ebaa27e 1318 if (s->crypt_method &&
16f0587e
HT
1319 cur_nr_sectors >
1320 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1321 cur_nr_sectors =
1322 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
5ebaa27e 1323 }
095a9c58 1324
3fc48d09 1325 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
16f0587e 1326 &cur_nr_sectors, &cluster_offset, &l2meta);
5ebaa27e 1327 if (ret < 0) {
3fc48d09 1328 goto fail;
5ebaa27e 1329 }
148da7ea 1330
5ebaa27e 1331 assert((cluster_offset & 511) == 0);
148da7ea 1332
3fc48d09 1333 qemu_iovec_reset(&hd_qiov);
1b093c48 1334 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e 1335 cur_nr_sectors * 512);
6f5f060b 1336
5ebaa27e 1337 if (s->crypt_method) {
3fc48d09 1338 if (!cluster_data) {
de82815d
KW
1339 cluster_data = qemu_try_blockalign(bs->file,
1340 QCOW_MAX_CRYPT_CLUSTERS
1341 * s->cluster_size);
1342 if (cluster_data == NULL) {
1343 ret = -ENOMEM;
1344 goto fail;
1345 }
5ebaa27e 1346 }
6f5f060b 1347
3fc48d09 1348 assert(hd_qiov.size <=
5ebaa27e 1349 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
d5e6b161 1350 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
6f5f060b 1351
3fc48d09
FZ
1352 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1353 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
6f5f060b 1354
3fc48d09
FZ
1355 qemu_iovec_reset(&hd_qiov);
1356 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1357 cur_nr_sectors * 512);
1358 }
6f5f060b 1359
231bb267 1360 ret = qcow2_pre_write_overlap_check(bs, 0,
cf93980e
HR
1361 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1362 cur_nr_sectors * BDRV_SECTOR_SIZE);
1363 if (ret < 0) {
1364 goto fail;
1365 }
1366
5ebaa27e 1367 qemu_co_mutex_unlock(&s->lock);
67a7a0eb 1368 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
3cce16f4
KW
1369 trace_qcow2_writev_data(qemu_coroutine_self(),
1370 (cluster_offset >> 9) + index_in_cluster);
5ebaa27e
FZ
1371 ret = bdrv_co_writev(bs->file,
1372 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1373 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1374 qemu_co_mutex_lock(&s->lock);
1375 if (ret < 0) {
3fc48d09 1376 goto fail;
5ebaa27e 1377 }
f141eafe 1378
88c6588c
KW
1379 while (l2meta != NULL) {
1380 QCowL2Meta *next;
1381
f50f88b9
KW
1382 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1383 if (ret < 0) {
1384 goto fail;
1385 }
faf575c1 1386
4e95314e
KW
1387 /* Take the request off the list of running requests */
1388 if (l2meta->nb_clusters != 0) {
1389 QLIST_REMOVE(l2meta, next_in_flight);
1390 }
1391
4e95314e 1392 qemu_co_queue_restart_all(&l2meta->dependent_requests);
4e95314e 1393
88c6588c 1394 next = l2meta->next;
f50f88b9 1395 g_free(l2meta);
88c6588c 1396 l2meta = next;
f50f88b9 1397 }
0fa9131a 1398
3fc48d09
FZ
1399 remaining_sectors -= cur_nr_sectors;
1400 sector_num += cur_nr_sectors;
1401 bytes_done += cur_nr_sectors * 512;
3cce16f4 1402 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
5ebaa27e 1403 }
3fc48d09 1404 ret = 0;
faf575c1 1405
3fc48d09 1406fail:
4e95314e
KW
1407 qemu_co_mutex_unlock(&s->lock);
1408
88c6588c
KW
1409 while (l2meta != NULL) {
1410 QCowL2Meta *next;
1411
4e95314e
KW
1412 if (l2meta->nb_clusters != 0) {
1413 QLIST_REMOVE(l2meta, next_in_flight);
1414 }
1415 qemu_co_queue_restart_all(&l2meta->dependent_requests);
88c6588c
KW
1416
1417 next = l2meta->next;
cf5c1a23 1418 g_free(l2meta);
88c6588c 1419 l2meta = next;
cf5c1a23 1420 }
0fa9131a 1421
3fc48d09 1422 qemu_iovec_destroy(&hd_qiov);
dea43a65 1423 qemu_vfree(cluster_data);
3cce16f4 1424 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 1425
68d100e9 1426 return ret;
585f8587
FB
1427}
1428
7c80ab3f 1429static void qcow2_close(BlockDriverState *bs)
585f8587
FB
1430{
1431 BDRVQcowState *s = bs->opaque;
de82815d 1432 qemu_vfree(s->l1_table);
cf93980e
HR
1433 /* else pre-write overlap checks in cache_destroy may crash */
1434 s->l1_table = NULL;
29c1a730 1435
27eb6c09 1436 if (!(bs->open_flags & BDRV_O_INCOMING)) {
3b5e14c7 1437 int ret1, ret2;
29c1a730 1438
3b5e14c7
HR
1439 ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1440 ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1441
1442 if (ret1) {
1443 error_report("Failed to flush the L2 table cache: %s",
1444 strerror(-ret1));
1445 }
1446 if (ret2) {
1447 error_report("Failed to flush the refcount block cache: %s",
1448 strerror(-ret2));
1449 }
1450
1451 if (!ret1 && !ret2) {
1452 qcow2_mark_clean(bs);
1453 }
27eb6c09 1454 }
c61d0004 1455
29c1a730
KW
1456 qcow2_cache_destroy(bs, s->l2_table_cache);
1457 qcow2_cache_destroy(bs, s->refcount_block_cache);
1458
6744cbab 1459 g_free(s->unknown_header_fields);
75bab85c 1460 cleanup_unknown_header_ext(bs);
6744cbab 1461
e4603fe1
KW
1462 g_free(s->image_backing_file);
1463 g_free(s->image_backing_format);
1464
7267c094 1465 g_free(s->cluster_cache);
dea43a65 1466 qemu_vfree(s->cluster_data);
ed6ccf0f 1467 qcow2_refcount_close(bs);
28c1202b 1468 qcow2_free_snapshots(bs);
585f8587
FB
1469}
1470
5a8a30db 1471static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
06d9260f
AL
1472{
1473 BDRVQcowState *s = bs->opaque;
1474 int flags = s->flags;
1475 AES_KEY aes_encrypt_key;
1476 AES_KEY aes_decrypt_key;
1477 uint32_t crypt_method = 0;
acdfb480 1478 QDict *options;
5a8a30db
KW
1479 Error *local_err = NULL;
1480 int ret;
06d9260f
AL
1481
1482 /*
1483 * Backing files are read-only which makes all of their metadata immutable,
1484 * that means we don't have to worry about reopening them here.
1485 */
1486
1487 if (s->crypt_method) {
1488 crypt_method = s->crypt_method;
1489 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1490 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1491 }
1492
1493 qcow2_close(bs);
1494
5a8a30db
KW
1495 bdrv_invalidate_cache(bs->file, &local_err);
1496 if (local_err) {
1497 error_propagate(errp, local_err);
1498 return;
1499 }
3456a8d1 1500
06d9260f 1501 memset(s, 0, sizeof(BDRVQcowState));
d475e5ac 1502 options = qdict_clone_shallow(bs->options);
5a8a30db
KW
1503
1504 ret = qcow2_open(bs, options, flags, &local_err);
a1904e48 1505 QDECREF(options);
5a8a30db
KW
1506 if (local_err) {
1507 error_setg(errp, "Could not reopen qcow2 layer: %s",
1508 error_get_pretty(local_err));
1509 error_free(local_err);
1510 return;
1511 } else if (ret < 0) {
1512 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1513 return;
1514 }
acdfb480 1515
06d9260f
AL
1516 if (crypt_method) {
1517 s->crypt_method = crypt_method;
1518 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1519 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1520 }
1521}
1522
e24e49e6
KW
1523static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1524 size_t len, size_t buflen)
1525{
1526 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1527 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1528
1529 if (buflen < ext_len) {
1530 return -ENOSPC;
1531 }
1532
1533 *ext_backing_fmt = (QCowExtension) {
1534 .magic = cpu_to_be32(magic),
1535 .len = cpu_to_be32(len),
1536 };
1537 memcpy(buf + sizeof(QCowExtension), s, len);
1538
1539 return ext_len;
1540}
1541
756e6736 1542/*
e24e49e6
KW
1543 * Updates the qcow2 header, including the variable length parts of it, i.e.
1544 * the backing file name and all extensions. qcow2 was not designed to allow
1545 * such changes, so if we run out of space (we can only use the first cluster)
1546 * this function may fail.
756e6736
KW
1547 *
1548 * Returns 0 on success, -errno in error cases.
1549 */
e24e49e6 1550int qcow2_update_header(BlockDriverState *bs)
756e6736 1551{
756e6736 1552 BDRVQcowState *s = bs->opaque;
e24e49e6
KW
1553 QCowHeader *header;
1554 char *buf;
1555 size_t buflen = s->cluster_size;
756e6736 1556 int ret;
e24e49e6
KW
1557 uint64_t total_size;
1558 uint32_t refcount_table_clusters;
6744cbab 1559 size_t header_length;
75bab85c 1560 Qcow2UnknownHeaderExtension *uext;
756e6736 1561
e24e49e6 1562 buf = qemu_blockalign(bs, buflen);
756e6736 1563
e24e49e6
KW
1564 /* Header structure */
1565 header = (QCowHeader*) buf;
756e6736 1566
e24e49e6
KW
1567 if (buflen < sizeof(*header)) {
1568 ret = -ENOSPC;
1569 goto fail;
756e6736
KW
1570 }
1571
6744cbab 1572 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
1573 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1574 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1575
1576 *header = (QCowHeader) {
6744cbab 1577 /* Version 2 fields */
e24e49e6 1578 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 1579 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
1580 .backing_file_offset = 0,
1581 .backing_file_size = 0,
1582 .cluster_bits = cpu_to_be32(s->cluster_bits),
1583 .size = cpu_to_be64(total_size),
1584 .crypt_method = cpu_to_be32(s->crypt_method_header),
1585 .l1_size = cpu_to_be32(s->l1_size),
1586 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1587 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1588 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1589 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1590 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
1591
1592 /* Version 3 fields */
1593 .incompatible_features = cpu_to_be64(s->incompatible_features),
1594 .compatible_features = cpu_to_be64(s->compatible_features),
1595 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 1596 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 1597 .header_length = cpu_to_be32(header_length),
e24e49e6 1598 };
756e6736 1599
6744cbab
KW
1600 /* For older versions, write a shorter header */
1601 switch (s->qcow_version) {
1602 case 2:
1603 ret = offsetof(QCowHeader, incompatible_features);
1604 break;
1605 case 3:
1606 ret = sizeof(*header);
1607 break;
1608 default:
b6c14762
JM
1609 ret = -EINVAL;
1610 goto fail;
6744cbab
KW
1611 }
1612
1613 buf += ret;
1614 buflen -= ret;
1615 memset(buf, 0, buflen);
1616
1617 /* Preserve any unknown field in the header */
1618 if (s->unknown_header_fields_size) {
1619 if (buflen < s->unknown_header_fields_size) {
1620 ret = -ENOSPC;
1621 goto fail;
1622 }
1623
1624 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1625 buf += s->unknown_header_fields_size;
1626 buflen -= s->unknown_header_fields_size;
1627 }
756e6736 1628
e24e49e6 1629 /* Backing file format header extension */
e4603fe1 1630 if (s->image_backing_format) {
e24e49e6 1631 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
e4603fe1
KW
1632 s->image_backing_format,
1633 strlen(s->image_backing_format),
e24e49e6
KW
1634 buflen);
1635 if (ret < 0) {
1636 goto fail;
756e6736
KW
1637 }
1638
e24e49e6
KW
1639 buf += ret;
1640 buflen -= ret;
756e6736
KW
1641 }
1642
cfcc4c62
KW
1643 /* Feature table */
1644 Qcow2Feature features[] = {
c61d0004
SH
1645 {
1646 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1647 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1648 .name = "dirty bit",
1649 },
69c98726
HR
1650 {
1651 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1652 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1653 .name = "corrupt bit",
1654 },
bfe8043e
SH
1655 {
1656 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1657 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1658 .name = "lazy refcounts",
1659 },
cfcc4c62
KW
1660 };
1661
1662 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1663 features, sizeof(features), buflen);
1664 if (ret < 0) {
1665 goto fail;
1666 }
1667 buf += ret;
1668 buflen -= ret;
1669
75bab85c
KW
1670 /* Keep unknown header extensions */
1671 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1672 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1673 if (ret < 0) {
1674 goto fail;
1675 }
1676
1677 buf += ret;
1678 buflen -= ret;
1679 }
1680
e24e49e6
KW
1681 /* End of header extensions */
1682 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
1683 if (ret < 0) {
1684 goto fail;
1685 }
1686
e24e49e6
KW
1687 buf += ret;
1688 buflen -= ret;
756e6736 1689
e24e49e6 1690 /* Backing file name */
e4603fe1
KW
1691 if (s->image_backing_file) {
1692 size_t backing_file_len = strlen(s->image_backing_file);
e24e49e6
KW
1693
1694 if (buflen < backing_file_len) {
1695 ret = -ENOSPC;
1696 goto fail;
1697 }
1698
00ea1881 1699 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e4603fe1 1700 strncpy(buf, s->image_backing_file, buflen);
e24e49e6
KW
1701
1702 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1703 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
1704 }
1705
e24e49e6
KW
1706 /* Write the new header */
1707 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
1708 if (ret < 0) {
1709 goto fail;
1710 }
1711
1712 ret = 0;
1713fail:
e24e49e6 1714 qemu_vfree(header);
756e6736
KW
1715 return ret;
1716}
1717
1718static int qcow2_change_backing_file(BlockDriverState *bs,
1719 const char *backing_file, const char *backing_fmt)
1720{
e4603fe1
KW
1721 BDRVQcowState *s = bs->opaque;
1722
e24e49e6
KW
1723 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1724 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1725
e4603fe1
KW
1726 g_free(s->image_backing_file);
1727 g_free(s->image_backing_format);
1728
1729 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1730 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1731
e24e49e6 1732 return qcow2_update_header(bs);
756e6736
KW
1733}
1734
a35e1c17
KW
1735static int preallocate(BlockDriverState *bs)
1736{
a35e1c17
KW
1737 uint64_t nb_sectors;
1738 uint64_t offset;
060bee89 1739 uint64_t host_offset = 0;
a35e1c17 1740 int num;
148da7ea 1741 int ret;
f50f88b9 1742 QCowL2Meta *meta;
a35e1c17 1743
57322b78 1744 nb_sectors = bdrv_nb_sectors(bs);
a35e1c17
KW
1745 offset = 0;
1746
1747 while (nb_sectors) {
7c2bbf4a 1748 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
16f0587e 1749 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
060bee89 1750 &host_offset, &meta);
148da7ea 1751 if (ret < 0) {
19dbcbf7 1752 return ret;
a35e1c17
KW
1753 }
1754
c792707f
SH
1755 while (meta) {
1756 QCowL2Meta *next = meta->next;
1757
7c2bbf4a
HT
1758 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1759 if (ret < 0) {
1760 qcow2_free_any_clusters(bs, meta->alloc_offset,
1761 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1762 return ret;
1763 }
1764
1765 /* There are no dependent requests, but we need to remove our
1766 * request from the list of in-flight requests */
4e95314e 1767 QLIST_REMOVE(meta, next_in_flight);
c792707f
SH
1768
1769 g_free(meta);
1770 meta = next;
f50f88b9 1771 }
f214978a 1772
a35e1c17
KW
1773 /* TODO Preallocate data if requested */
1774
1775 nb_sectors -= num;
7c2bbf4a 1776 offset += num << BDRV_SECTOR_BITS;
a35e1c17
KW
1777 }
1778
1779 /*
1780 * It is expected that the image file is large enough to actually contain
1781 * all of the allocated clusters (otherwise we get failing reads after
1782 * EOF). Extend the image to the last allocated sector.
1783 */
060bee89 1784 if (host_offset != 0) {
7c2bbf4a
HT
1785 uint8_t buf[BDRV_SECTOR_SIZE];
1786 memset(buf, 0, BDRV_SECTOR_SIZE);
1787 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1788 buf, 1);
19dbcbf7
KW
1789 if (ret < 0) {
1790 return ret;
1791 }
a35e1c17
KW
1792 }
1793
1794 return 0;
1795}
1796
7c80ab3f
JS
1797static int qcow2_create2(const char *filename, int64_t total_size,
1798 const char *backing_file, const char *backing_format,
ffeaac9b 1799 int flags, size_t cluster_size, PreallocMode prealloc,
bd4b167f 1800 QemuOpts *opts, int version, int refcount_order,
3ef6c40a 1801 Error **errp)
a9420734 1802{
9b2260cb 1803 /* Calculate cluster_bits */
a9420734 1804 int cluster_bits;
786a4ea8 1805 cluster_bits = ctz32(cluster_size);
a9420734
KW
1806 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1807 (1 << cluster_bits) != cluster_size)
1808 {
3ef6c40a
HR
1809 error_setg(errp, "Cluster size must be a power of two between %d and "
1810 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
a9420734
KW
1811 return -EINVAL;
1812 }
1813
1814 /*
1815 * Open the image file and write a minimal qcow2 header.
1816 *
1817 * We keep things simple and start with a zero-sized image. We also
1818 * do without refcount blocks or a L1 table for now. We'll fix the
1819 * inconsistency later.
1820 *
1821 * We do need a refcount table because growing the refcount table means
1822 * allocating two new refcount blocks - the seconds of which would be at
1823 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1824 * size for any qcow2 image.
1825 */
1826 BlockDriverState* bs;
f8413b3c 1827 QCowHeader *header;
b106ad91 1828 uint64_t* refcount_table;
3ef6c40a 1829 Error *local_err = NULL;
a9420734
KW
1830 int ret;
1831
0e4271b7 1832 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
bd4b167f
HR
1833 /* Note: The following calculation does not need to be exact; if it is a
1834 * bit off, either some bytes will be "leaked" (which is fine) or we
1835 * will need to increase the file size by some bytes (which is fine,
1836 * too, as long as the bulk is allocated here). Therefore, using
1837 * floating point arithmetic is fine. */
0e4271b7
HT
1838 int64_t meta_size = 0;
1839 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
1840 int64_t aligned_total_size = align_offset(total_size, cluster_size);
bd4b167f
HR
1841 int refblock_bits, refblock_size;
1842 /* refcount entry size in bytes */
1843 double rces = (1 << refcount_order) / 8.;
1844
1845 /* see qcow2_open() */
1846 refblock_bits = cluster_bits - (refcount_order - 3);
1847 refblock_size = 1 << refblock_bits;
0e4271b7
HT
1848
1849 /* header: 1 cluster */
1850 meta_size += cluster_size;
1851
1852 /* total size of L2 tables */
1853 nl2e = aligned_total_size / cluster_size;
1854 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
1855 meta_size += nl2e * sizeof(uint64_t);
1856
1857 /* total size of L1 tables */
1858 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
1859 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
1860 meta_size += nl1e * sizeof(uint64_t);
1861
1862 /* total size of refcount blocks
1863 *
1864 * note: every host cluster is reference-counted, including metadata
1865 * (even refcount blocks are recursively included).
1866 * Let:
1867 * a = total_size (this is the guest disk size)
1868 * m = meta size not including refcount blocks and refcount tables
1869 * c = cluster size
1870 * y1 = number of refcount blocks entries
1871 * y2 = meta size including everything
bd4b167f 1872 * rces = refcount entry size in bytes
0e4271b7
HT
1873 * then,
1874 * y1 = (y2 + a)/c
bd4b167f 1875 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
0e4271b7 1876 * we can get y1:
bd4b167f 1877 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
0e4271b7 1878 */
bd4b167f
HR
1879 nrefblocke = (aligned_total_size + meta_size + cluster_size)
1880 / (cluster_size - rces - rces * sizeof(uint64_t)
1881 / cluster_size);
1882 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
0e4271b7
HT
1883
1884 /* total size of refcount tables */
bd4b167f 1885 nreftablee = nrefblocke / refblock_size;
0e4271b7
HT
1886 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
1887 meta_size += nreftablee * sizeof(uint64_t);
1888
1889 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
39101f25 1890 aligned_total_size + meta_size, &error_abort);
f43e47db
MA
1891 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
1892 &error_abort);
0e4271b7
HT
1893 }
1894
c282e1fd 1895 ret = bdrv_create_file(filename, opts, &local_err);
a9420734 1896 if (ret < 0) {
3ef6c40a 1897 error_propagate(errp, local_err);
a9420734
KW
1898 return ret;
1899 }
1900
2e40134b
HR
1901 bs = NULL;
1902 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1903 NULL, &local_err);
a9420734 1904 if (ret < 0) {
3ef6c40a 1905 error_propagate(errp, local_err);
a9420734
KW
1906 return ret;
1907 }
1908
1909 /* Write the header */
f8413b3c
KW
1910 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1911 header = g_malloc0(cluster_size);
1912 *header = (QCowHeader) {
1913 .magic = cpu_to_be32(QCOW_MAGIC),
1914 .version = cpu_to_be32(version),
1915 .cluster_bits = cpu_to_be32(cluster_bits),
1916 .size = cpu_to_be64(0),
1917 .l1_table_offset = cpu_to_be64(0),
1918 .l1_size = cpu_to_be32(0),
1919 .refcount_table_offset = cpu_to_be64(cluster_size),
1920 .refcount_table_clusters = cpu_to_be32(1),
bd4b167f 1921 .refcount_order = cpu_to_be32(refcount_order),
f8413b3c
KW
1922 .header_length = cpu_to_be32(sizeof(*header)),
1923 };
a9420734
KW
1924
1925 if (flags & BLOCK_FLAG_ENCRYPT) {
f8413b3c 1926 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
a9420734 1927 } else {
f8413b3c 1928 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734
KW
1929 }
1930
bfe8043e 1931 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
f8413b3c 1932 header->compatible_features |=
bfe8043e
SH
1933 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1934 }
1935
f8413b3c
KW
1936 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1937 g_free(header);
a9420734 1938 if (ret < 0) {
3ef6c40a 1939 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
1940 goto out;
1941 }
1942
b106ad91
KW
1943 /* Write a refcount table with one refcount block */
1944 refcount_table = g_malloc0(2 * cluster_size);
1945 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1946 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
7267c094 1947 g_free(refcount_table);
a9420734
KW
1948
1949 if (ret < 0) {
3ef6c40a 1950 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
1951 goto out;
1952 }
1953
f67503e5
HR
1954 bdrv_unref(bs);
1955 bs = NULL;
a9420734
KW
1956
1957 /*
1958 * And now open the image and make it consistent first (i.e. increase the
1959 * refcount of the cluster that is occupied by the header and the refcount
1960 * table)
1961 */
ddf5636d 1962 ret = bdrv_open(&bs, filename, NULL, NULL,
ef810437
HR
1963 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
1964 &bdrv_qcow2, &local_err);
a9420734 1965 if (ret < 0) {
3ef6c40a 1966 error_propagate(errp, local_err);
a9420734
KW
1967 goto out;
1968 }
1969
b106ad91 1970 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
a9420734 1971 if (ret < 0) {
3ef6c40a
HR
1972 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1973 "header and refcount table");
a9420734
KW
1974 goto out;
1975
1976 } else if (ret != 0) {
1977 error_report("Huh, first cluster in empty image is already in use?");
1978 abort();
1979 }
1980
1981 /* Okay, now that we have a valid image, let's give it the right size */
180e9526 1982 ret = bdrv_truncate(bs, total_size);
a9420734 1983 if (ret < 0) {
3ef6c40a 1984 error_setg_errno(errp, -ret, "Could not resize image");
a9420734
KW
1985 goto out;
1986 }
1987
1988 /* Want a backing file? There you go.*/
1989 if (backing_file) {
1990 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1991 if (ret < 0) {
3ef6c40a
HR
1992 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1993 "with format '%s'", backing_file, backing_format);
a9420734
KW
1994 goto out;
1995 }
1996 }
1997
1998 /* And if we're supposed to preallocate metadata, do that now */
0e4271b7 1999 if (prealloc != PREALLOC_MODE_OFF) {
15552c4a
ZYW
2000 BDRVQcowState *s = bs->opaque;
2001 qemu_co_mutex_lock(&s->lock);
a9420734 2002 ret = preallocate(bs);
15552c4a 2003 qemu_co_mutex_unlock(&s->lock);
a9420734 2004 if (ret < 0) {
3ef6c40a 2005 error_setg_errno(errp, -ret, "Could not preallocate metadata");
a9420734
KW
2006 goto out;
2007 }
2008 }
2009
f67503e5
HR
2010 bdrv_unref(bs);
2011 bs = NULL;
ba2ab2f2
HR
2012
2013 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
ddf5636d 2014 ret = bdrv_open(&bs, filename, NULL, NULL,
c9fbb99d 2015 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
ef810437 2016 &bdrv_qcow2, &local_err);
84d18f06 2017 if (local_err) {
ba2ab2f2
HR
2018 error_propagate(errp, local_err);
2019 goto out;
2020 }
2021
a9420734
KW
2022 ret = 0;
2023out:
f67503e5
HR
2024 if (bs) {
2025 bdrv_unref(bs);
2026 }
a9420734
KW
2027 return ret;
2028}
de5f3f40 2029
1bd0e2d1 2030static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
de5f3f40 2031{
1bd0e2d1
CL
2032 char *backing_file = NULL;
2033 char *backing_fmt = NULL;
2034 char *buf = NULL;
180e9526 2035 uint64_t size = 0;
de5f3f40 2036 int flags = 0;
99cce9fa 2037 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
ffeaac9b 2038 PreallocMode prealloc;
8ad1898c 2039 int version = 3;
bd4b167f
HR
2040 uint64_t refcount_bits = 16;
2041 int refcount_order;
3ef6c40a
HR
2042 Error *local_err = NULL;
2043 int ret;
de5f3f40
KW
2044
2045 /* Read out options */
180e9526
HT
2046 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2047 BDRV_SECTOR_SIZE);
1bd0e2d1
CL
2048 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2049 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2050 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2051 flags |= BLOCK_FLAG_ENCRYPT;
2052 }
2053 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2054 DEFAULT_CLUSTER_SIZE);
2055 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
ffeaac9b
HT
2056 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2057 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
2058 &local_err);
2059 if (local_err) {
2060 error_propagate(errp, local_err);
1bd0e2d1
CL
2061 ret = -EINVAL;
2062 goto finish;
2063 }
2064 g_free(buf);
2065 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2066 if (!buf) {
2067 /* keep the default */
2068 } else if (!strcmp(buf, "0.10")) {
2069 version = 2;
2070 } else if (!strcmp(buf, "1.1")) {
2071 version = 3;
2072 } else {
2073 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2074 ret = -EINVAL;
2075 goto finish;
2076 }
2077
2078 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2079 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
de5f3f40
KW
2080 }
2081
ffeaac9b 2082 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
3ef6c40a
HR
2083 error_setg(errp, "Backing file and preallocation cannot be used at "
2084 "the same time");
1bd0e2d1
CL
2085 ret = -EINVAL;
2086 goto finish;
de5f3f40
KW
2087 }
2088
bfe8043e 2089 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
3ef6c40a
HR
2090 error_setg(errp, "Lazy refcounts only supported with compatibility "
2091 "level 1.1 and above (use compat=1.1 or greater)");
1bd0e2d1
CL
2092 ret = -EINVAL;
2093 goto finish;
bfe8043e
SH
2094 }
2095
06d05fa7
HR
2096 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2097 refcount_bits);
2098 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2099 error_setg(errp, "Refcount width must be a power of two and may not "
2100 "exceed 64 bits");
2101 ret = -EINVAL;
2102 goto finish;
2103 }
2104
bd4b167f
HR
2105 if (version < 3 && refcount_bits != 16) {
2106 error_setg(errp, "Different refcount widths than 16 bits require "
2107 "compatibility level 1.1 or above (use compat=1.1 or "
2108 "greater)");
2109 ret = -EINVAL;
2110 goto finish;
2111 }
2112
786a4ea8 2113 refcount_order = ctz32(refcount_bits);
bd4b167f 2114
180e9526 2115 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
bd4b167f
HR
2116 cluster_size, prealloc, opts, version, refcount_order,
2117 &local_err);
84d18f06 2118 if (local_err) {
3ef6c40a
HR
2119 error_propagate(errp, local_err);
2120 }
1bd0e2d1
CL
2121
2122finish:
2123 g_free(backing_file);
2124 g_free(backing_fmt);
2125 g_free(buf);
3ef6c40a 2126 return ret;
de5f3f40
KW
2127}
2128
621f0589 2129static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
aa7bfbff 2130 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
621f0589
KW
2131{
2132 int ret;
2133 BDRVQcowState *s = bs->opaque;
2134
2135 /* Emulate misaligned zero writes */
2136 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2137 return -ENOTSUP;
2138 }
2139
2140 /* Whatever is left can use real zero clusters */
2141 qemu_co_mutex_lock(&s->lock);
2142 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2143 nb_sectors);
2144 qemu_co_mutex_unlock(&s->lock);
2145
2146 return ret;
2147}
2148
6db39ae2
PB
2149static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2150 int64_t sector_num, int nb_sectors)
5ea929e3 2151{
6db39ae2
PB
2152 int ret;
2153 BDRVQcowState *s = bs->opaque;
2154
2155 qemu_co_mutex_lock(&s->lock);
2156 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
808c4b6f 2157 nb_sectors, QCOW2_DISCARD_REQUEST, false);
6db39ae2
PB
2158 qemu_co_mutex_unlock(&s->lock);
2159 return ret;
5ea929e3
KW
2160}
2161
419b19d9
SH
2162static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2163{
2164 BDRVQcowState *s = bs->opaque;
2cf7cfa1
KW
2165 int64_t new_l1_size;
2166 int ret;
419b19d9
SH
2167
2168 if (offset & 511) {
259b2173 2169 error_report("The new size must be a multiple of 512");
419b19d9
SH
2170 return -EINVAL;
2171 }
2172
2173 /* cannot proceed if image has snapshots */
2174 if (s->nb_snapshots) {
259b2173 2175 error_report("Can't resize an image which has snapshots");
419b19d9
SH
2176 return -ENOTSUP;
2177 }
2178
2179 /* shrinking is currently not supported */
2180 if (offset < bs->total_sectors * 512) {
259b2173 2181 error_report("qcow2 doesn't support shrinking images yet");
419b19d9
SH
2182 return -ENOTSUP;
2183 }
2184
2185 new_l1_size = size_to_l1(s, offset);
72893756 2186 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
419b19d9
SH
2187 if (ret < 0) {
2188 return ret;
2189 }
2190
2191 /* write updated header.size */
2192 offset = cpu_to_be64(offset);
8b3b7206
KW
2193 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2194 &offset, sizeof(uint64_t));
419b19d9
SH
2195 if (ret < 0) {
2196 return ret;
2197 }
2198
2199 s->l1_vm_state_index = new_l1_size;
2200 return 0;
2201}
2202
20d97356
BS
2203/* XXX: put compressed sectors first, then all the cluster aligned
2204 tables to avoid losing bytes in alignment */
7c80ab3f
JS
2205static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2206 const uint8_t *buf, int nb_sectors)
20d97356
BS
2207{
2208 BDRVQcowState *s = bs->opaque;
2209 z_stream strm;
2210 int ret, out_len;
2211 uint8_t *out_buf;
2212 uint64_t cluster_offset;
2213
2214 if (nb_sectors == 0) {
2215 /* align end of file to a sector boundary to ease reading with
2216 sector based I/Os */
66f82cee 2217 cluster_offset = bdrv_getlength(bs->file);
6a69b962 2218 return bdrv_truncate(bs->file, cluster_offset);
20d97356
BS
2219 }
2220
f4d38bef
SH
2221 if (nb_sectors != s->cluster_sectors) {
2222 ret = -EINVAL;
2223
2224 /* Zero-pad last write if image size is not cluster aligned */
2225 if (sector_num + nb_sectors == bs->total_sectors &&
2226 nb_sectors < s->cluster_sectors) {
2227 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2228 memset(pad_buf, 0, s->cluster_size);
2229 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2230 ret = qcow2_write_compressed(bs, sector_num,
2231 pad_buf, s->cluster_sectors);
2232 qemu_vfree(pad_buf);
2233 }
2234 return ret;
2235 }
20d97356 2236
7267c094 2237 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
20d97356
BS
2238
2239 /* best compression, small window, no zlib header */
2240 memset(&strm, 0, sizeof(strm));
2241 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2242 Z_DEFLATED, -12,
2243 9, Z_DEFAULT_STRATEGY);
2244 if (ret != 0) {
8f1efd00
KW
2245 ret = -EINVAL;
2246 goto fail;
20d97356
BS
2247 }
2248
2249 strm.avail_in = s->cluster_size;
2250 strm.next_in = (uint8_t *)buf;
2251 strm.avail_out = s->cluster_size;
2252 strm.next_out = out_buf;
2253
2254 ret = deflate(&strm, Z_FINISH);
2255 if (ret != Z_STREAM_END && ret != Z_OK) {
20d97356 2256 deflateEnd(&strm);
8f1efd00
KW
2257 ret = -EINVAL;
2258 goto fail;
20d97356
BS
2259 }
2260 out_len = strm.next_out - out_buf;
2261
2262 deflateEnd(&strm);
2263
2264 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2265 /* could not compress: write normal cluster */
8f1efd00
KW
2266 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2267 if (ret < 0) {
2268 goto fail;
2269 }
20d97356
BS
2270 } else {
2271 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2272 sector_num << 9, out_len);
8f1efd00
KW
2273 if (!cluster_offset) {
2274 ret = -EIO;
2275 goto fail;
2276 }
20d97356 2277 cluster_offset &= s->cluster_offset_mask;
cf93980e 2278
231bb267 2279 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
cf93980e
HR
2280 if (ret < 0) {
2281 goto fail;
2282 }
2283
66f82cee 2284 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
8f1efd00
KW
2285 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2286 if (ret < 0) {
2287 goto fail;
20d97356
BS
2288 }
2289 }
2290
8f1efd00
KW
2291 ret = 0;
2292fail:
7267c094 2293 g_free(out_buf);
8f1efd00 2294 return ret;
20d97356
BS
2295}
2296
94054183
HR
2297static int make_completely_empty(BlockDriverState *bs)
2298{
2299 BDRVQcowState *s = bs->opaque;
2300 int ret, l1_clusters;
2301 int64_t offset;
2302 uint64_t *new_reftable = NULL;
2303 uint64_t rt_entry, l1_size2;
2304 struct {
2305 uint64_t l1_offset;
2306 uint64_t reftable_offset;
2307 uint32_t reftable_clusters;
2308 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2309
2310 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2311 if (ret < 0) {
2312 goto fail;
2313 }
2314
2315 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2316 if (ret < 0) {
2317 goto fail;
2318 }
2319
2320 /* Refcounts will be broken utterly */
2321 ret = qcow2_mark_dirty(bs);
2322 if (ret < 0) {
2323 goto fail;
2324 }
2325
2326 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2327
2328 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2329 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2330
2331 /* After this call, neither the in-memory nor the on-disk refcount
2332 * information accurately describe the actual references */
2333
2334 ret = bdrv_write_zeroes(bs->file, s->l1_table_offset / BDRV_SECTOR_SIZE,
2335 l1_clusters * s->cluster_sectors, 0);
2336 if (ret < 0) {
2337 goto fail_broken_refcounts;
2338 }
2339 memset(s->l1_table, 0, l1_size2);
2340
2341 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2342
2343 /* Overwrite enough clusters at the beginning of the sectors to place
2344 * the refcount table, a refcount block and the L1 table in; this may
2345 * overwrite parts of the existing refcount and L1 table, which is not
2346 * an issue because the dirty flag is set, complete data loss is in fact
2347 * desired and partial data loss is consequently fine as well */
2348 ret = bdrv_write_zeroes(bs->file, s->cluster_size / BDRV_SECTOR_SIZE,
2349 (2 + l1_clusters) * s->cluster_size /
2350 BDRV_SECTOR_SIZE, 0);
2351 /* This call (even if it failed overall) may have overwritten on-disk
2352 * refcount structures; in that case, the in-memory refcount information
2353 * will probably differ from the on-disk information which makes the BDS
2354 * unusable */
2355 if (ret < 0) {
2356 goto fail_broken_refcounts;
2357 }
2358
2359 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2360 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2361
2362 /* "Create" an empty reftable (one cluster) directly after the image
2363 * header and an empty L1 table three clusters after the image header;
2364 * the cluster between those two will be used as the first refblock */
2365 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2366 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2367 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2368 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2369 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2370 if (ret < 0) {
2371 goto fail_broken_refcounts;
2372 }
2373
2374 s->l1_table_offset = 3 * s->cluster_size;
2375
2376 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2377 if (!new_reftable) {
2378 ret = -ENOMEM;
2379 goto fail_broken_refcounts;
2380 }
2381
2382 s->refcount_table_offset = s->cluster_size;
2383 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2384
2385 g_free(s->refcount_table);
2386 s->refcount_table = new_reftable;
2387 new_reftable = NULL;
2388
2389 /* Now the in-memory refcount information again corresponds to the on-disk
2390 * information (reftable is empty and no refblocks (the refblock cache is
2391 * empty)); however, this means some clusters (e.g. the image header) are
2392 * referenced, but not refcounted, but the normal qcow2 code assumes that
2393 * the in-memory information is always correct */
2394
2395 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2396
2397 /* Enter the first refblock into the reftable */
2398 rt_entry = cpu_to_be64(2 * s->cluster_size);
2399 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2400 &rt_entry, sizeof(rt_entry));
2401 if (ret < 0) {
2402 goto fail_broken_refcounts;
2403 }
2404 s->refcount_table[0] = 2 * s->cluster_size;
2405
2406 s->free_cluster_index = 0;
2407 assert(3 + l1_clusters <= s->refcount_block_size);
2408 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2409 if (offset < 0) {
2410 ret = offset;
2411 goto fail_broken_refcounts;
2412 } else if (offset > 0) {
2413 error_report("First cluster in emptied image is in use");
2414 abort();
2415 }
2416
2417 /* Now finally the in-memory information corresponds to the on-disk
2418 * structures and is correct */
2419 ret = qcow2_mark_clean(bs);
2420 if (ret < 0) {
2421 goto fail;
2422 }
2423
2424 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size);
2425 if (ret < 0) {
2426 goto fail;
2427 }
2428
2429 return 0;
2430
2431fail_broken_refcounts:
2432 /* The BDS is unusable at this point. If we wanted to make it usable, we
2433 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2434 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2435 * again. However, because the functions which could have caused this error
2436 * path to be taken are used by those functions as well, it's very likely
2437 * that that sequence will fail as well. Therefore, just eject the BDS. */
2438 bs->drv = NULL;
2439
2440fail:
2441 g_free(new_reftable);
2442 return ret;
2443}
2444
491d27e2
HR
2445static int qcow2_make_empty(BlockDriverState *bs)
2446{
94054183 2447 BDRVQcowState *s = bs->opaque;
491d27e2
HR
2448 uint64_t start_sector;
2449 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
94054183
HR
2450 int l1_clusters, ret = 0;
2451
2452 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2453
2454 if (s->qcow_version >= 3 && !s->snapshots &&
2455 3 + l1_clusters <= s->refcount_block_size) {
2456 /* The following function only works for qcow2 v3 images (it requires
2457 * the dirty flag) and only as long as there are no snapshots (because
2458 * it completely empties the image). Furthermore, the L1 table and three
2459 * additional clusters (image header, refcount table, one refcount
2460 * block) have to fit inside one refcount block. */
2461 return make_completely_empty(bs);
2462 }
491d27e2 2463
94054183
HR
2464 /* This fallback code simply discards every active cluster; this is slow,
2465 * but works in all cases */
491d27e2
HR
2466 for (start_sector = 0; start_sector < bs->total_sectors;
2467 start_sector += sector_step)
2468 {
2469 /* As this function is generally used after committing an external
2470 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2471 * default action for this kind of discard is to pass the discard,
2472 * which will ideally result in an actually smaller image file, as
2473 * is probably desired. */
2474 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2475 MIN(sector_step,
2476 bs->total_sectors - start_sector),
2477 QCOW2_DISCARD_SNAPSHOT, true);
2478 if (ret < 0) {
2479 break;
2480 }
2481 }
2482
2483 return ret;
2484}
2485
a968168c 2486static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 2487{
29c1a730
KW
2488 BDRVQcowState *s = bs->opaque;
2489 int ret;
2490
8b94ff85 2491 qemu_co_mutex_lock(&s->lock);
29c1a730
KW
2492 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2493 if (ret < 0) {
c95de7e2 2494 qemu_co_mutex_unlock(&s->lock);
8b94ff85 2495 return ret;
29c1a730
KW
2496 }
2497
bfe8043e
SH
2498 if (qcow2_need_accurate_refcounts(s)) {
2499 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2500 if (ret < 0) {
2501 qemu_co_mutex_unlock(&s->lock);
2502 return ret;
2503 }
29c1a730 2504 }
8b94ff85 2505 qemu_co_mutex_unlock(&s->lock);
29c1a730 2506
eb489bb1
KW
2507 return 0;
2508}
2509
7c80ab3f 2510static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356
BS
2511{
2512 BDRVQcowState *s = bs->opaque;
95de6d70
PB
2513 bdi->unallocated_blocks_are_zero = true;
2514 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
20d97356 2515 bdi->cluster_size = s->cluster_size;
7c80ab3f 2516 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
2517 return 0;
2518}
2519
37764dfb
HR
2520static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2521{
2522 BDRVQcowState *s = bs->opaque;
2523 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2524
2525 *spec_info = (ImageInfoSpecific){
2526 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2527 {
2528 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2529 },
2530 };
2531 if (s->qcow_version == 2) {
2532 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
0709c5a1
HR
2533 .compat = g_strdup("0.10"),
2534 .refcount_bits = s->refcount_bits,
37764dfb
HR
2535 };
2536 } else if (s->qcow_version == 3) {
2537 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2538 .compat = g_strdup("1.1"),
2539 .lazy_refcounts = s->compatible_features &
2540 QCOW2_COMPAT_LAZY_REFCOUNTS,
2541 .has_lazy_refcounts = true,
9009b196
HR
2542 .corrupt = s->incompatible_features &
2543 QCOW2_INCOMPAT_CORRUPT,
2544 .has_corrupt = true,
0709c5a1 2545 .refcount_bits = s->refcount_bits,
37764dfb
HR
2546 };
2547 }
2548
2549 return spec_info;
2550}
2551
20d97356
BS
2552#if 0
2553static void dump_refcounts(BlockDriverState *bs)
2554{
2555 BDRVQcowState *s = bs->opaque;
2556 int64_t nb_clusters, k, k1, size;
2557 int refcount;
2558
66f82cee 2559 size = bdrv_getlength(bs->file);
20d97356
BS
2560 nb_clusters = size_to_clusters(s, size);
2561 for(k = 0; k < nb_clusters;) {
2562 k1 = k;
2563 refcount = get_refcount(bs, k);
2564 k++;
2565 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2566 k++;
0bfcd599
BS
2567 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2568 k - k1);
20d97356
BS
2569 }
2570}
2571#endif
2572
cf8074b3
KW
2573static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2574 int64_t pos)
20d97356
BS
2575{
2576 BDRVQcowState *s = bs->opaque;
eedff66f 2577 int64_t total_sectors = bs->total_sectors;
6e13610a 2578 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2579 int ret;
2580
66f82cee 2581 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
6e13610a 2582 bs->zero_beyond_eof = false;
8d3b1a2d 2583 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
6e13610a 2584 bs->zero_beyond_eof = zero_beyond_eof;
20d97356 2585
eedff66f
HR
2586 /* bdrv_co_do_writev will have increased the total_sectors value to include
2587 * the VM state - the VM state is however not an actual part of the block
2588 * device, therefore, we need to restore the old value. */
2589 bs->total_sectors = total_sectors;
2590
20d97356
BS
2591 return ret;
2592}
2593
7c80ab3f
JS
2594static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2595 int64_t pos, int size)
20d97356
BS
2596{
2597 BDRVQcowState *s = bs->opaque;
0d51b4de 2598 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2599 int ret;
2600
66f82cee 2601 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
0d51b4de 2602 bs->zero_beyond_eof = false;
7c80ab3f 2603 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
0d51b4de 2604 bs->zero_beyond_eof = zero_beyond_eof;
20d97356
BS
2605
2606 return ret;
2607}
2608
9296b3ed
HR
2609/*
2610 * Downgrades an image's version. To achieve this, any incompatible features
2611 * have to be removed.
2612 */
4057a2b2
HR
2613static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2614 BlockDriverAmendStatusCB *status_cb)
9296b3ed
HR
2615{
2616 BDRVQcowState *s = bs->opaque;
2617 int current_version = s->qcow_version;
2618 int ret;
2619
2620 if (target_version == current_version) {
2621 return 0;
2622 } else if (target_version > current_version) {
2623 return -EINVAL;
2624 } else if (target_version != 2) {
2625 return -EINVAL;
2626 }
2627
2628 if (s->refcount_order != 4) {
2629 /* we would have to convert the image to a refcount_order == 4 image
2630 * here; however, since qemu (at the time of writing this) does not
2631 * support anything different than 4 anyway, there is no point in doing
2632 * so right now; however, we should error out (if qemu supports this in
2633 * the future and this code has not been adapted) */
9e3f0892 2634 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
9296b3ed
HR
2635 "currently not supported.");
2636 return -ENOTSUP;
2637 }
2638
2639 /* clear incompatible features */
2640 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2641 ret = qcow2_mark_clean(bs);
2642 if (ret < 0) {
2643 return ret;
2644 }
2645 }
2646
2647 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2648 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2649 * best thing to do anyway */
2650
2651 if (s->incompatible_features) {
2652 return -ENOTSUP;
2653 }
2654
2655 /* since we can ignore compatible features, we can set them to 0 as well */
2656 s->compatible_features = 0;
2657 /* if lazy refcounts have been used, they have already been fixed through
2658 * clearing the dirty flag */
2659
2660 /* clearing autoclear features is trivial */
2661 s->autoclear_features = 0;
2662
4057a2b2 2663 ret = qcow2_expand_zero_clusters(bs, status_cb);
9296b3ed
HR
2664 if (ret < 0) {
2665 return ret;
2666 }
2667
2668 s->qcow_version = target_version;
2669 ret = qcow2_update_header(bs);
2670 if (ret < 0) {
2671 s->qcow_version = current_version;
2672 return ret;
2673 }
2674 return 0;
2675}
2676
77485434
HR
2677static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
2678 BlockDriverAmendStatusCB *status_cb)
9296b3ed
HR
2679{
2680 BDRVQcowState *s = bs->opaque;
2681 int old_version = s->qcow_version, new_version = old_version;
2682 uint64_t new_size = 0;
2683 const char *backing_file = NULL, *backing_format = NULL;
2684 bool lazy_refcounts = s->use_lazy_refcounts;
1bd0e2d1
CL
2685 const char *compat = NULL;
2686 uint64_t cluster_size = s->cluster_size;
2687 bool encrypt;
9296b3ed 2688 int ret;
1bd0e2d1 2689 QemuOptDesc *desc = opts->list->desc;
9296b3ed 2690
1bd0e2d1
CL
2691 while (desc && desc->name) {
2692 if (!qemu_opt_find(opts, desc->name)) {
9296b3ed 2693 /* only change explicitly defined options */
1bd0e2d1 2694 desc++;
9296b3ed
HR
2695 continue;
2696 }
2697
8a17b83c
HR
2698 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
2699 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
1bd0e2d1 2700 if (!compat) {
9296b3ed 2701 /* preserve default */
1bd0e2d1 2702 } else if (!strcmp(compat, "0.10")) {
9296b3ed 2703 new_version = 2;
1bd0e2d1 2704 } else if (!strcmp(compat, "1.1")) {
9296b3ed
HR
2705 new_version = 3;
2706 } else {
1bd0e2d1 2707 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
9296b3ed
HR
2708 return -EINVAL;
2709 }
8a17b83c 2710 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
9296b3ed
HR
2711 fprintf(stderr, "Cannot change preallocation mode.\n");
2712 return -ENOTSUP;
8a17b83c
HR
2713 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
2714 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
2715 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
2716 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2717 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
2718 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
2719 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
2720 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
2721 s->crypt_method);
1bd0e2d1 2722 if (encrypt != !!s->crypt_method) {
9296b3ed
HR
2723 fprintf(stderr, "Changing the encryption flag is not "
2724 "supported.\n");
2725 return -ENOTSUP;
2726 }
8a17b83c
HR
2727 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
2728 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
1bd0e2d1
CL
2729 cluster_size);
2730 if (cluster_size != s->cluster_size) {
9296b3ed
HR
2731 fprintf(stderr, "Changing the cluster size is not "
2732 "supported.\n");
2733 return -ENOTSUP;
2734 }
8a17b83c
HR
2735 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
2736 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
1bd0e2d1 2737 lazy_refcounts);
06d05fa7
HR
2738 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
2739 error_report("Cannot change refcount entry width");
2740 return -ENOTSUP;
9296b3ed
HR
2741 } else {
2742 /* if this assertion fails, this probably means a new option was
2743 * added without having it covered here */
2744 assert(false);
2745 }
1bd0e2d1
CL
2746
2747 desc++;
9296b3ed
HR
2748 }
2749
2750 if (new_version != old_version) {
2751 if (new_version > old_version) {
2752 /* Upgrade */
2753 s->qcow_version = new_version;
2754 ret = qcow2_update_header(bs);
2755 if (ret < 0) {
2756 s->qcow_version = old_version;
2757 return ret;
2758 }
2759 } else {
4057a2b2 2760 ret = qcow2_downgrade(bs, new_version, status_cb);
9296b3ed
HR
2761 if (ret < 0) {
2762 return ret;
2763 }
2764 }
2765 }
2766
2767 if (backing_file || backing_format) {
e4603fe1
KW
2768 ret = qcow2_change_backing_file(bs,
2769 backing_file ?: s->image_backing_file,
2770 backing_format ?: s->image_backing_format);
9296b3ed
HR
2771 if (ret < 0) {
2772 return ret;
2773 }
2774 }
2775
2776 if (s->use_lazy_refcounts != lazy_refcounts) {
2777 if (lazy_refcounts) {
2778 if (s->qcow_version < 3) {
2779 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2780 "level 1.1 and above (use compat=1.1 or greater)\n");
2781 return -EINVAL;
2782 }
2783 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2784 ret = qcow2_update_header(bs);
2785 if (ret < 0) {
2786 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2787 return ret;
2788 }
2789 s->use_lazy_refcounts = true;
2790 } else {
2791 /* make image clean first */
2792 ret = qcow2_mark_clean(bs);
2793 if (ret < 0) {
2794 return ret;
2795 }
2796 /* now disallow lazy refcounts */
2797 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2798 ret = qcow2_update_header(bs);
2799 if (ret < 0) {
2800 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2801 return ret;
2802 }
2803 s->use_lazy_refcounts = false;
2804 }
2805 }
2806
2807 if (new_size) {
2808 ret = bdrv_truncate(bs, new_size);
2809 if (ret < 0) {
2810 return ret;
2811 }
2812 }
2813
2814 return 0;
2815}
2816
85186ebd
HR
2817/*
2818 * If offset or size are negative, respectively, they will not be included in
2819 * the BLOCK_IMAGE_CORRUPTED event emitted.
2820 * fatal will be ignored for read-only BDS; corruptions found there will always
2821 * be considered non-fatal.
2822 */
2823void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
2824 int64_t size, const char *message_format, ...)
2825{
2826 BDRVQcowState *s = bs->opaque;
dc881b44 2827 const char *node_name;
85186ebd
HR
2828 char *message;
2829 va_list ap;
2830
2831 fatal = fatal && !bs->read_only;
2832
2833 if (s->signaled_corruption &&
2834 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
2835 {
2836 return;
2837 }
2838
2839 va_start(ap, message_format);
2840 message = g_strdup_vprintf(message_format, ap);
2841 va_end(ap);
2842
2843 if (fatal) {
2844 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
2845 "corruption events will be suppressed\n", message);
2846 } else {
2847 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
2848 "corruption events will be suppressed\n", message);
2849 }
2850
dc881b44
AG
2851 node_name = bdrv_get_node_name(bs);
2852 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
2853 *node_name != '\0', node_name,
2854 message, offset >= 0, offset,
2855 size >= 0, size,
85186ebd
HR
2856 fatal, &error_abort);
2857 g_free(message);
2858
2859 if (fatal) {
2860 qcow2_mark_corrupt(bs);
2861 bs->drv = NULL; /* make BDS unusable */
2862 }
2863
2864 s->signaled_corruption = true;
2865}
2866
1bd0e2d1
CL
2867static QemuOptsList qcow2_create_opts = {
2868 .name = "qcow2-create-opts",
2869 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2870 .desc = {
2871 {
2872 .name = BLOCK_OPT_SIZE,
2873 .type = QEMU_OPT_SIZE,
2874 .help = "Virtual disk size"
2875 },
2876 {
2877 .name = BLOCK_OPT_COMPAT_LEVEL,
2878 .type = QEMU_OPT_STRING,
2879 .help = "Compatibility level (0.10 or 1.1)"
2880 },
2881 {
2882 .name = BLOCK_OPT_BACKING_FILE,
2883 .type = QEMU_OPT_STRING,
2884 .help = "File name of a base image"
2885 },
2886 {
2887 .name = BLOCK_OPT_BACKING_FMT,
2888 .type = QEMU_OPT_STRING,
2889 .help = "Image format of the base image"
2890 },
2891 {
2892 .name = BLOCK_OPT_ENCRYPT,
2893 .type = QEMU_OPT_BOOL,
2894 .help = "Encrypt the image",
2895 .def_value_str = "off"
2896 },
2897 {
2898 .name = BLOCK_OPT_CLUSTER_SIZE,
2899 .type = QEMU_OPT_SIZE,
2900 .help = "qcow2 cluster size",
2901 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
2902 },
2903 {
2904 .name = BLOCK_OPT_PREALLOC,
2905 .type = QEMU_OPT_STRING,
0e4271b7
HT
2906 .help = "Preallocation mode (allowed values: off, metadata, "
2907 "falloc, full)"
1bd0e2d1
CL
2908 },
2909 {
2910 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2911 .type = QEMU_OPT_BOOL,
2912 .help = "Postpone refcount updates",
2913 .def_value_str = "off"
2914 },
06d05fa7
HR
2915 {
2916 .name = BLOCK_OPT_REFCOUNT_BITS,
2917 .type = QEMU_OPT_NUMBER,
2918 .help = "Width of a reference count entry in bits",
2919 .def_value_str = "16"
2920 },
1bd0e2d1
CL
2921 { /* end of list */ }
2922 }
20d97356
BS
2923};
2924
5f535a94 2925BlockDriver bdrv_qcow2 = {
7c80ab3f
JS
2926 .format_name = "qcow2",
2927 .instance_size = sizeof(BDRVQcowState),
2928 .bdrv_probe = qcow2_probe,
2929 .bdrv_open = qcow2_open,
2930 .bdrv_close = qcow2_close,
21d82ac9 2931 .bdrv_reopen_prepare = qcow2_reopen_prepare,
c282e1fd 2932 .bdrv_create = qcow2_create,
3ac21627 2933 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 2934 .bdrv_co_get_block_status = qcow2_co_get_block_status,
7c80ab3f 2935 .bdrv_set_key = qcow2_set_key,
7c80ab3f 2936
c68b89ac
KW
2937 .bdrv_co_readv = qcow2_co_readv,
2938 .bdrv_co_writev = qcow2_co_writev,
eb489bb1 2939 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 2940
621f0589 2941 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
6db39ae2 2942 .bdrv_co_discard = qcow2_co_discard,
419b19d9 2943 .bdrv_truncate = qcow2_truncate,
7c80ab3f 2944 .bdrv_write_compressed = qcow2_write_compressed,
491d27e2 2945 .bdrv_make_empty = qcow2_make_empty,
20d97356
BS
2946
2947 .bdrv_snapshot_create = qcow2_snapshot_create,
2948 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2949 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2950 .bdrv_snapshot_list = qcow2_snapshot_list,
1bd0e2d1
CL
2951 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2952 .bdrv_get_info = qcow2_get_info,
37764dfb 2953 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 2954
7c80ab3f
JS
2955 .bdrv_save_vmstate = qcow2_save_vmstate,
2956 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356 2957
8ee79e70 2958 .supports_backing = true,
20d97356
BS
2959 .bdrv_change_backing_file = qcow2_change_backing_file,
2960
d34682cd 2961 .bdrv_refresh_limits = qcow2_refresh_limits,
06d9260f
AL
2962 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2963
1bd0e2d1
CL
2964 .create_opts = &qcow2_create_opts,
2965 .bdrv_check = qcow2_check,
c282e1fd 2966 .bdrv_amend_options = qcow2_amend_options,
20d97356
BS
2967};
2968
5efa9d5a
AL
2969static void bdrv_qcow2_init(void)
2970{
2971 bdrv_register(&bdrv_qcow2);
2972}
2973
2974block_init(bdrv_qcow2_init);