]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
iotests: qcow2 COW with minimal L2 cache size
[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 }
8336aafa 1040 assert(bs->encrypted);
585f8587
FB
1041 s->crypt_method = s->crypt_method_header;
1042
1043 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
1044 return -1;
1045 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
1046 return -1;
1047#if 0
1048 /* test */
1049 {
1050 uint8_t in[16];
1051 uint8_t out[16];
1052 uint8_t tmp[16];
1053 for(i=0;i<16;i++)
1054 in[i] = i;
1055 AES_encrypt(in, tmp, &s->aes_encrypt_key);
1056 AES_decrypt(tmp, out, &s->aes_decrypt_key);
1057 for(i = 0; i < 16; i++)
1058 printf(" %02x", tmp[i]);
1059 printf("\n");
1060 for(i = 0; i < 16; i++)
1061 printf(" %02x", out[i]);
1062 printf("\n");
1063 }
1064#endif
1065 return 0;
1066}
1067
4c2e5f8f
KW
1068/* We have no actual commit/abort logic for qcow2, but we need to write out any
1069 * unwritten data if we reopen read-only. */
21d82ac9
JC
1070static int qcow2_reopen_prepare(BDRVReopenState *state,
1071 BlockReopenQueue *queue, Error **errp)
1072{
4c2e5f8f
KW
1073 int ret;
1074
1075 if ((state->flags & BDRV_O_RDWR) == 0) {
1076 ret = bdrv_flush(state->bs);
1077 if (ret < 0) {
1078 return ret;
1079 }
1080
1081 ret = qcow2_mark_clean(state->bs);
1082 if (ret < 0) {
1083 return ret;
1084 }
1085 }
1086
21d82ac9
JC
1087 return 0;
1088}
1089
b6b8a333 1090static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
f8a2e5e3 1091 int64_t sector_num, int nb_sectors, int *pnum)
585f8587 1092{
f8a2e5e3 1093 BDRVQcowState *s = bs->opaque;
585f8587 1094 uint64_t cluster_offset;
4bc74be9
PB
1095 int index_in_cluster, ret;
1096 int64_t status = 0;
585f8587 1097
095a9c58 1098 *pnum = nb_sectors;
f8a2e5e3 1099 qemu_co_mutex_lock(&s->lock);
1c46efaa 1100 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
f8a2e5e3 1101 qemu_co_mutex_unlock(&s->lock);
1c46efaa 1102 if (ret < 0) {
d663640c 1103 return ret;
1c46efaa 1104 }
095a9c58 1105
4bc74be9
PB
1106 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1107 !s->crypt_method) {
1108 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1109 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1110 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1111 }
1112 if (ret == QCOW2_CLUSTER_ZERO) {
1113 status |= BDRV_BLOCK_ZERO;
1114 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1115 status |= BDRV_BLOCK_DATA;
1116 }
1117 return status;
585f8587
FB
1118}
1119
a9465922 1120/* handle reading after the end of the backing file */
bd28f835
KW
1121int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1122 int64_t sector_num, int nb_sectors)
a9465922
FB
1123{
1124 int n1;
1125 if ((sector_num + nb_sectors) <= bs->total_sectors)
1126 return nb_sectors;
1127 if (sector_num >= bs->total_sectors)
1128 n1 = 0;
1129 else
1130 n1 = bs->total_sectors - sector_num;
bd28f835 1131
3d9b4925 1132 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
bd28f835 1133
a9465922
FB
1134 return n1;
1135}
1136
a968168c 1137static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
3fc48d09 1138 int remaining_sectors, QEMUIOVector *qiov)
585f8587 1139{
585f8587 1140 BDRVQcowState *s = bs->opaque;
a9465922 1141 int index_in_cluster, n1;
68d100e9 1142 int ret;
faf575c1 1143 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 1144 uint64_t cluster_offset = 0;
3fc48d09
FZ
1145 uint64_t bytes_done = 0;
1146 QEMUIOVector hd_qiov;
1147 uint8_t *cluster_data = NULL;
585f8587 1148
3fc48d09
FZ
1149 qemu_iovec_init(&hd_qiov, qiov->niov);
1150
1151 qemu_co_mutex_lock(&s->lock);
1152
1153 while (remaining_sectors != 0) {
bd28f835 1154
5ebaa27e 1155 /* prepare next request */
3fc48d09 1156 cur_nr_sectors = remaining_sectors;
5ebaa27e
FZ
1157 if (s->crypt_method) {
1158 cur_nr_sectors = MIN(cur_nr_sectors,
1159 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
585f8587 1160 }
5ebaa27e 1161
3fc48d09 1162 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
5ebaa27e 1163 &cur_nr_sectors, &cluster_offset);
8af36488 1164 if (ret < 0) {
3fc48d09 1165 goto fail;
8af36488 1166 }
bd28f835 1167
3fc48d09 1168 index_in_cluster = sector_num & (s->cluster_sectors - 1);
c87c0672 1169
3fc48d09 1170 qemu_iovec_reset(&hd_qiov);
1b093c48 1171 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e
FZ
1172 cur_nr_sectors * 512);
1173
68d000a3
KW
1174 switch (ret) {
1175 case QCOW2_CLUSTER_UNALLOCATED:
5ebaa27e
FZ
1176
1177 if (bs->backing_hd) {
1178 /* read from the base image */
3fc48d09
FZ
1179 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1180 sector_num, cur_nr_sectors);
5ebaa27e 1181 if (n1 > 0) {
44deba5a
KW
1182 QEMUIOVector local_qiov;
1183
1184 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1185 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1186 n1 * BDRV_SECTOR_SIZE);
1187
5ebaa27e
FZ
1188 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1189 qemu_co_mutex_unlock(&s->lock);
3fc48d09 1190 ret = bdrv_co_readv(bs->backing_hd, sector_num,
44deba5a 1191 n1, &local_qiov);
5ebaa27e 1192 qemu_co_mutex_lock(&s->lock);
44deba5a
KW
1193
1194 qemu_iovec_destroy(&local_qiov);
1195
5ebaa27e 1196 if (ret < 0) {
3fc48d09 1197 goto fail;
5ebaa27e
FZ
1198 }
1199 }
1200 } else {
1201 /* Note: in this case, no need to wait */
3d9b4925 1202 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
5ebaa27e 1203 }
68d000a3
KW
1204 break;
1205
6377af48 1206 case QCOW2_CLUSTER_ZERO:
3d9b4925 1207 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
6377af48
KW
1208 break;
1209
68d000a3 1210 case QCOW2_CLUSTER_COMPRESSED:
5ebaa27e
FZ
1211 /* add AIO support for compressed blocks ? */
1212 ret = qcow2_decompress_cluster(bs, cluster_offset);
1213 if (ret < 0) {
3fc48d09 1214 goto fail;
bd28f835
KW
1215 }
1216
03396148 1217 qemu_iovec_from_buf(&hd_qiov, 0,
5ebaa27e 1218 s->cluster_cache + index_in_cluster * 512,
faf575c1 1219 512 * cur_nr_sectors);
68d000a3
KW
1220 break;
1221
1222 case QCOW2_CLUSTER_NORMAL:
5ebaa27e 1223 if ((cluster_offset & 511) != 0) {
3fc48d09
FZ
1224 ret = -EIO;
1225 goto fail;
5ebaa27e 1226 }
bd28f835 1227
8336aafa
DB
1228 if (bs->encrypted) {
1229 assert(s->crypt_method);
1230
5ebaa27e
FZ
1231 /*
1232 * For encrypted images, read everything into a temporary
1233 * contiguous buffer on which the AES functions can work.
1234 */
3fc48d09
FZ
1235 if (!cluster_data) {
1236 cluster_data =
de82815d
KW
1237 qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1238 * s->cluster_size);
1239 if (cluster_data == NULL) {
1240 ret = -ENOMEM;
1241 goto fail;
1242 }
5ebaa27e
FZ
1243 }
1244
1245 assert(cur_nr_sectors <=
1246 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
3fc48d09
FZ
1247 qemu_iovec_reset(&hd_qiov);
1248 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1249 512 * cur_nr_sectors);
1250 }
1251
1252 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1253 qemu_co_mutex_unlock(&s->lock);
1254 ret = bdrv_co_readv(bs->file,
1255 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1256 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1257 qemu_co_mutex_lock(&s->lock);
1258 if (ret < 0) {
3fc48d09 1259 goto fail;
5ebaa27e 1260 }
8336aafa
DB
1261 if (bs->encrypted) {
1262 assert(s->crypt_method);
3fc48d09
FZ
1263 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1264 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
03396148
MT
1265 qemu_iovec_from_buf(qiov, bytes_done,
1266 cluster_data, 512 * cur_nr_sectors);
5ebaa27e 1267 }
68d000a3
KW
1268 break;
1269
1270 default:
1271 g_assert_not_reached();
1272 ret = -EIO;
1273 goto fail;
faf575c1 1274 }
f141eafe 1275
3fc48d09
FZ
1276 remaining_sectors -= cur_nr_sectors;
1277 sector_num += cur_nr_sectors;
1278 bytes_done += cur_nr_sectors * 512;
5ebaa27e 1279 }
3fc48d09 1280 ret = 0;
faf575c1 1281
3fc48d09 1282fail:
68d100e9 1283 qemu_co_mutex_unlock(&s->lock);
42496d62 1284
3fc48d09 1285 qemu_iovec_destroy(&hd_qiov);
dea43a65 1286 qemu_vfree(cluster_data);
68d100e9
KW
1287
1288 return ret;
585f8587
FB
1289}
1290
a968168c 1291static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
3fc48d09
FZ
1292 int64_t sector_num,
1293 int remaining_sectors,
1294 QEMUIOVector *qiov)
585f8587 1295{
585f8587 1296 BDRVQcowState *s = bs->opaque;
585f8587 1297 int index_in_cluster;
68d100e9 1298 int ret;
faf575c1 1299 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 1300 uint64_t cluster_offset;
3fc48d09
FZ
1301 QEMUIOVector hd_qiov;
1302 uint64_t bytes_done = 0;
1303 uint8_t *cluster_data = NULL;
8d2497c3 1304 QCowL2Meta *l2meta = NULL;
c2271403 1305
3cce16f4
KW
1306 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1307 remaining_sectors);
1308
3fc48d09
FZ
1309 qemu_iovec_init(&hd_qiov, qiov->niov);
1310
1311 s->cluster_cache_offset = -1; /* disable compressed cache */
3b46e624 1312
3fc48d09
FZ
1313 qemu_co_mutex_lock(&s->lock);
1314
1315 while (remaining_sectors != 0) {
1316
f50f88b9 1317 l2meta = NULL;
cf5c1a23 1318
3cce16f4 1319 trace_qcow2_writev_start_part(qemu_coroutine_self());
3fc48d09 1320 index_in_cluster = sector_num & (s->cluster_sectors - 1);
16f0587e 1321 cur_nr_sectors = remaining_sectors;
8336aafa 1322 if (bs->encrypted &&
16f0587e
HT
1323 cur_nr_sectors >
1324 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1325 cur_nr_sectors =
1326 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
5ebaa27e 1327 }
095a9c58 1328
3fc48d09 1329 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
16f0587e 1330 &cur_nr_sectors, &cluster_offset, &l2meta);
5ebaa27e 1331 if (ret < 0) {
3fc48d09 1332 goto fail;
5ebaa27e 1333 }
148da7ea 1334
5ebaa27e 1335 assert((cluster_offset & 511) == 0);
148da7ea 1336
3fc48d09 1337 qemu_iovec_reset(&hd_qiov);
1b093c48 1338 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e 1339 cur_nr_sectors * 512);
6f5f060b 1340
8336aafa
DB
1341 if (bs->encrypted) {
1342 assert(s->crypt_method);
3fc48d09 1343 if (!cluster_data) {
de82815d
KW
1344 cluster_data = qemu_try_blockalign(bs->file,
1345 QCOW_MAX_CRYPT_CLUSTERS
1346 * s->cluster_size);
1347 if (cluster_data == NULL) {
1348 ret = -ENOMEM;
1349 goto fail;
1350 }
5ebaa27e 1351 }
6f5f060b 1352
3fc48d09 1353 assert(hd_qiov.size <=
5ebaa27e 1354 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
d5e6b161 1355 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
6f5f060b 1356
3fc48d09
FZ
1357 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1358 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
6f5f060b 1359
3fc48d09
FZ
1360 qemu_iovec_reset(&hd_qiov);
1361 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1362 cur_nr_sectors * 512);
1363 }
6f5f060b 1364
231bb267 1365 ret = qcow2_pre_write_overlap_check(bs, 0,
cf93980e
HR
1366 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1367 cur_nr_sectors * BDRV_SECTOR_SIZE);
1368 if (ret < 0) {
1369 goto fail;
1370 }
1371
5ebaa27e 1372 qemu_co_mutex_unlock(&s->lock);
67a7a0eb 1373 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
3cce16f4
KW
1374 trace_qcow2_writev_data(qemu_coroutine_self(),
1375 (cluster_offset >> 9) + index_in_cluster);
5ebaa27e
FZ
1376 ret = bdrv_co_writev(bs->file,
1377 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1378 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1379 qemu_co_mutex_lock(&s->lock);
1380 if (ret < 0) {
3fc48d09 1381 goto fail;
5ebaa27e 1382 }
f141eafe 1383
88c6588c
KW
1384 while (l2meta != NULL) {
1385 QCowL2Meta *next;
1386
f50f88b9
KW
1387 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1388 if (ret < 0) {
1389 goto fail;
1390 }
faf575c1 1391
4e95314e
KW
1392 /* Take the request off the list of running requests */
1393 if (l2meta->nb_clusters != 0) {
1394 QLIST_REMOVE(l2meta, next_in_flight);
1395 }
1396
4e95314e 1397 qemu_co_queue_restart_all(&l2meta->dependent_requests);
4e95314e 1398
88c6588c 1399 next = l2meta->next;
f50f88b9 1400 g_free(l2meta);
88c6588c 1401 l2meta = next;
f50f88b9 1402 }
0fa9131a 1403
3fc48d09
FZ
1404 remaining_sectors -= cur_nr_sectors;
1405 sector_num += cur_nr_sectors;
1406 bytes_done += cur_nr_sectors * 512;
3cce16f4 1407 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
5ebaa27e 1408 }
3fc48d09 1409 ret = 0;
faf575c1 1410
3fc48d09 1411fail:
4e95314e
KW
1412 qemu_co_mutex_unlock(&s->lock);
1413
88c6588c
KW
1414 while (l2meta != NULL) {
1415 QCowL2Meta *next;
1416
4e95314e
KW
1417 if (l2meta->nb_clusters != 0) {
1418 QLIST_REMOVE(l2meta, next_in_flight);
1419 }
1420 qemu_co_queue_restart_all(&l2meta->dependent_requests);
88c6588c
KW
1421
1422 next = l2meta->next;
cf5c1a23 1423 g_free(l2meta);
88c6588c 1424 l2meta = next;
cf5c1a23 1425 }
0fa9131a 1426
3fc48d09 1427 qemu_iovec_destroy(&hd_qiov);
dea43a65 1428 qemu_vfree(cluster_data);
3cce16f4 1429 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 1430
68d100e9 1431 return ret;
585f8587
FB
1432}
1433
7c80ab3f 1434static void qcow2_close(BlockDriverState *bs)
585f8587
FB
1435{
1436 BDRVQcowState *s = bs->opaque;
de82815d 1437 qemu_vfree(s->l1_table);
cf93980e
HR
1438 /* else pre-write overlap checks in cache_destroy may crash */
1439 s->l1_table = NULL;
29c1a730 1440
27eb6c09 1441 if (!(bs->open_flags & BDRV_O_INCOMING)) {
3b5e14c7 1442 int ret1, ret2;
29c1a730 1443
3b5e14c7
HR
1444 ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1445 ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1446
1447 if (ret1) {
1448 error_report("Failed to flush the L2 table cache: %s",
1449 strerror(-ret1));
1450 }
1451 if (ret2) {
1452 error_report("Failed to flush the refcount block cache: %s",
1453 strerror(-ret2));
1454 }
1455
1456 if (!ret1 && !ret2) {
1457 qcow2_mark_clean(bs);
1458 }
27eb6c09 1459 }
c61d0004 1460
29c1a730
KW
1461 qcow2_cache_destroy(bs, s->l2_table_cache);
1462 qcow2_cache_destroy(bs, s->refcount_block_cache);
1463
6744cbab 1464 g_free(s->unknown_header_fields);
75bab85c 1465 cleanup_unknown_header_ext(bs);
6744cbab 1466
e4603fe1
KW
1467 g_free(s->image_backing_file);
1468 g_free(s->image_backing_format);
1469
7267c094 1470 g_free(s->cluster_cache);
dea43a65 1471 qemu_vfree(s->cluster_data);
ed6ccf0f 1472 qcow2_refcount_close(bs);
28c1202b 1473 qcow2_free_snapshots(bs);
585f8587
FB
1474}
1475
5a8a30db 1476static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
06d9260f
AL
1477{
1478 BDRVQcowState *s = bs->opaque;
1479 int flags = s->flags;
1480 AES_KEY aes_encrypt_key;
1481 AES_KEY aes_decrypt_key;
1482 uint32_t crypt_method = 0;
acdfb480 1483 QDict *options;
5a8a30db
KW
1484 Error *local_err = NULL;
1485 int ret;
06d9260f
AL
1486
1487 /*
1488 * Backing files are read-only which makes all of their metadata immutable,
1489 * that means we don't have to worry about reopening them here.
1490 */
1491
8336aafa
DB
1492 if (bs->encrypted) {
1493 assert(s->crypt_method);
06d9260f
AL
1494 crypt_method = s->crypt_method;
1495 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1496 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1497 }
1498
1499 qcow2_close(bs);
1500
5a8a30db
KW
1501 bdrv_invalidate_cache(bs->file, &local_err);
1502 if (local_err) {
1503 error_propagate(errp, local_err);
1504 return;
1505 }
3456a8d1 1506
06d9260f 1507 memset(s, 0, sizeof(BDRVQcowState));
d475e5ac 1508 options = qdict_clone_shallow(bs->options);
5a8a30db
KW
1509
1510 ret = qcow2_open(bs, options, flags, &local_err);
a1904e48 1511 QDECREF(options);
5a8a30db
KW
1512 if (local_err) {
1513 error_setg(errp, "Could not reopen qcow2 layer: %s",
1514 error_get_pretty(local_err));
1515 error_free(local_err);
1516 return;
1517 } else if (ret < 0) {
1518 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1519 return;
1520 }
acdfb480 1521
8336aafa 1522 if (bs->encrypted) {
06d9260f
AL
1523 s->crypt_method = crypt_method;
1524 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1525 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1526 }
1527}
1528
e24e49e6
KW
1529static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1530 size_t len, size_t buflen)
1531{
1532 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1533 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1534
1535 if (buflen < ext_len) {
1536 return -ENOSPC;
1537 }
1538
1539 *ext_backing_fmt = (QCowExtension) {
1540 .magic = cpu_to_be32(magic),
1541 .len = cpu_to_be32(len),
1542 };
1543 memcpy(buf + sizeof(QCowExtension), s, len);
1544
1545 return ext_len;
1546}
1547
756e6736 1548/*
e24e49e6
KW
1549 * Updates the qcow2 header, including the variable length parts of it, i.e.
1550 * the backing file name and all extensions. qcow2 was not designed to allow
1551 * such changes, so if we run out of space (we can only use the first cluster)
1552 * this function may fail.
756e6736
KW
1553 *
1554 * Returns 0 on success, -errno in error cases.
1555 */
e24e49e6 1556int qcow2_update_header(BlockDriverState *bs)
756e6736 1557{
756e6736 1558 BDRVQcowState *s = bs->opaque;
e24e49e6
KW
1559 QCowHeader *header;
1560 char *buf;
1561 size_t buflen = s->cluster_size;
756e6736 1562 int ret;
e24e49e6
KW
1563 uint64_t total_size;
1564 uint32_t refcount_table_clusters;
6744cbab 1565 size_t header_length;
75bab85c 1566 Qcow2UnknownHeaderExtension *uext;
756e6736 1567
e24e49e6 1568 buf = qemu_blockalign(bs, buflen);
756e6736 1569
e24e49e6
KW
1570 /* Header structure */
1571 header = (QCowHeader*) buf;
756e6736 1572
e24e49e6
KW
1573 if (buflen < sizeof(*header)) {
1574 ret = -ENOSPC;
1575 goto fail;
756e6736
KW
1576 }
1577
6744cbab 1578 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
1579 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1580 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1581
1582 *header = (QCowHeader) {
6744cbab 1583 /* Version 2 fields */
e24e49e6 1584 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 1585 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
1586 .backing_file_offset = 0,
1587 .backing_file_size = 0,
1588 .cluster_bits = cpu_to_be32(s->cluster_bits),
1589 .size = cpu_to_be64(total_size),
1590 .crypt_method = cpu_to_be32(s->crypt_method_header),
1591 .l1_size = cpu_to_be32(s->l1_size),
1592 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1593 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1594 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1595 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1596 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
1597
1598 /* Version 3 fields */
1599 .incompatible_features = cpu_to_be64(s->incompatible_features),
1600 .compatible_features = cpu_to_be64(s->compatible_features),
1601 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 1602 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 1603 .header_length = cpu_to_be32(header_length),
e24e49e6 1604 };
756e6736 1605
6744cbab
KW
1606 /* For older versions, write a shorter header */
1607 switch (s->qcow_version) {
1608 case 2:
1609 ret = offsetof(QCowHeader, incompatible_features);
1610 break;
1611 case 3:
1612 ret = sizeof(*header);
1613 break;
1614 default:
b6c14762
JM
1615 ret = -EINVAL;
1616 goto fail;
6744cbab
KW
1617 }
1618
1619 buf += ret;
1620 buflen -= ret;
1621 memset(buf, 0, buflen);
1622
1623 /* Preserve any unknown field in the header */
1624 if (s->unknown_header_fields_size) {
1625 if (buflen < s->unknown_header_fields_size) {
1626 ret = -ENOSPC;
1627 goto fail;
1628 }
1629
1630 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1631 buf += s->unknown_header_fields_size;
1632 buflen -= s->unknown_header_fields_size;
1633 }
756e6736 1634
e24e49e6 1635 /* Backing file format header extension */
e4603fe1 1636 if (s->image_backing_format) {
e24e49e6 1637 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
e4603fe1
KW
1638 s->image_backing_format,
1639 strlen(s->image_backing_format),
e24e49e6
KW
1640 buflen);
1641 if (ret < 0) {
1642 goto fail;
756e6736
KW
1643 }
1644
e24e49e6
KW
1645 buf += ret;
1646 buflen -= ret;
756e6736
KW
1647 }
1648
cfcc4c62
KW
1649 /* Feature table */
1650 Qcow2Feature features[] = {
c61d0004
SH
1651 {
1652 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1653 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1654 .name = "dirty bit",
1655 },
69c98726
HR
1656 {
1657 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1658 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1659 .name = "corrupt bit",
1660 },
bfe8043e
SH
1661 {
1662 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1663 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1664 .name = "lazy refcounts",
1665 },
cfcc4c62
KW
1666 };
1667
1668 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1669 features, sizeof(features), buflen);
1670 if (ret < 0) {
1671 goto fail;
1672 }
1673 buf += ret;
1674 buflen -= ret;
1675
75bab85c
KW
1676 /* Keep unknown header extensions */
1677 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1678 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1679 if (ret < 0) {
1680 goto fail;
1681 }
1682
1683 buf += ret;
1684 buflen -= ret;
1685 }
1686
e24e49e6
KW
1687 /* End of header extensions */
1688 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
1689 if (ret < 0) {
1690 goto fail;
1691 }
1692
e24e49e6
KW
1693 buf += ret;
1694 buflen -= ret;
756e6736 1695
e24e49e6 1696 /* Backing file name */
e4603fe1
KW
1697 if (s->image_backing_file) {
1698 size_t backing_file_len = strlen(s->image_backing_file);
e24e49e6
KW
1699
1700 if (buflen < backing_file_len) {
1701 ret = -ENOSPC;
1702 goto fail;
1703 }
1704
00ea1881 1705 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e4603fe1 1706 strncpy(buf, s->image_backing_file, buflen);
e24e49e6
KW
1707
1708 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1709 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
1710 }
1711
e24e49e6
KW
1712 /* Write the new header */
1713 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
1714 if (ret < 0) {
1715 goto fail;
1716 }
1717
1718 ret = 0;
1719fail:
e24e49e6 1720 qemu_vfree(header);
756e6736
KW
1721 return ret;
1722}
1723
1724static int qcow2_change_backing_file(BlockDriverState *bs,
1725 const char *backing_file, const char *backing_fmt)
1726{
e4603fe1
KW
1727 BDRVQcowState *s = bs->opaque;
1728
e24e49e6
KW
1729 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1730 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1731
e4603fe1
KW
1732 g_free(s->image_backing_file);
1733 g_free(s->image_backing_format);
1734
1735 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1736 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1737
e24e49e6 1738 return qcow2_update_header(bs);
756e6736
KW
1739}
1740
a35e1c17
KW
1741static int preallocate(BlockDriverState *bs)
1742{
a35e1c17
KW
1743 uint64_t nb_sectors;
1744 uint64_t offset;
060bee89 1745 uint64_t host_offset = 0;
a35e1c17 1746 int num;
148da7ea 1747 int ret;
f50f88b9 1748 QCowL2Meta *meta;
a35e1c17 1749
57322b78 1750 nb_sectors = bdrv_nb_sectors(bs);
a35e1c17
KW
1751 offset = 0;
1752
1753 while (nb_sectors) {
7c2bbf4a 1754 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
16f0587e 1755 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
060bee89 1756 &host_offset, &meta);
148da7ea 1757 if (ret < 0) {
19dbcbf7 1758 return ret;
a35e1c17
KW
1759 }
1760
c792707f
SH
1761 while (meta) {
1762 QCowL2Meta *next = meta->next;
1763
7c2bbf4a
HT
1764 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1765 if (ret < 0) {
1766 qcow2_free_any_clusters(bs, meta->alloc_offset,
1767 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1768 return ret;
1769 }
1770
1771 /* There are no dependent requests, but we need to remove our
1772 * request from the list of in-flight requests */
4e95314e 1773 QLIST_REMOVE(meta, next_in_flight);
c792707f
SH
1774
1775 g_free(meta);
1776 meta = next;
f50f88b9 1777 }
f214978a 1778
a35e1c17
KW
1779 /* TODO Preallocate data if requested */
1780
1781 nb_sectors -= num;
7c2bbf4a 1782 offset += num << BDRV_SECTOR_BITS;
a35e1c17
KW
1783 }
1784
1785 /*
1786 * It is expected that the image file is large enough to actually contain
1787 * all of the allocated clusters (otherwise we get failing reads after
1788 * EOF). Extend the image to the last allocated sector.
1789 */
060bee89 1790 if (host_offset != 0) {
7c2bbf4a
HT
1791 uint8_t buf[BDRV_SECTOR_SIZE];
1792 memset(buf, 0, BDRV_SECTOR_SIZE);
1793 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1794 buf, 1);
19dbcbf7
KW
1795 if (ret < 0) {
1796 return ret;
1797 }
a35e1c17
KW
1798 }
1799
1800 return 0;
1801}
1802
7c80ab3f
JS
1803static int qcow2_create2(const char *filename, int64_t total_size,
1804 const char *backing_file, const char *backing_format,
ffeaac9b 1805 int flags, size_t cluster_size, PreallocMode prealloc,
bd4b167f 1806 QemuOpts *opts, int version, int refcount_order,
3ef6c40a 1807 Error **errp)
a9420734 1808{
9b2260cb 1809 /* Calculate cluster_bits */
a9420734 1810 int cluster_bits;
786a4ea8 1811 cluster_bits = ctz32(cluster_size);
a9420734
KW
1812 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1813 (1 << cluster_bits) != cluster_size)
1814 {
3ef6c40a
HR
1815 error_setg(errp, "Cluster size must be a power of two between %d and "
1816 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
a9420734
KW
1817 return -EINVAL;
1818 }
1819
1820 /*
1821 * Open the image file and write a minimal qcow2 header.
1822 *
1823 * We keep things simple and start with a zero-sized image. We also
1824 * do without refcount blocks or a L1 table for now. We'll fix the
1825 * inconsistency later.
1826 *
1827 * We do need a refcount table because growing the refcount table means
1828 * allocating two new refcount blocks - the seconds of which would be at
1829 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1830 * size for any qcow2 image.
1831 */
1832 BlockDriverState* bs;
f8413b3c 1833 QCowHeader *header;
b106ad91 1834 uint64_t* refcount_table;
3ef6c40a 1835 Error *local_err = NULL;
a9420734
KW
1836 int ret;
1837
0e4271b7 1838 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
bd4b167f
HR
1839 /* Note: The following calculation does not need to be exact; if it is a
1840 * bit off, either some bytes will be "leaked" (which is fine) or we
1841 * will need to increase the file size by some bytes (which is fine,
1842 * too, as long as the bulk is allocated here). Therefore, using
1843 * floating point arithmetic is fine. */
0e4271b7
HT
1844 int64_t meta_size = 0;
1845 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
1846 int64_t aligned_total_size = align_offset(total_size, cluster_size);
bd4b167f
HR
1847 int refblock_bits, refblock_size;
1848 /* refcount entry size in bytes */
1849 double rces = (1 << refcount_order) / 8.;
1850
1851 /* see qcow2_open() */
1852 refblock_bits = cluster_bits - (refcount_order - 3);
1853 refblock_size = 1 << refblock_bits;
0e4271b7
HT
1854
1855 /* header: 1 cluster */
1856 meta_size += cluster_size;
1857
1858 /* total size of L2 tables */
1859 nl2e = aligned_total_size / cluster_size;
1860 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
1861 meta_size += nl2e * sizeof(uint64_t);
1862
1863 /* total size of L1 tables */
1864 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
1865 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
1866 meta_size += nl1e * sizeof(uint64_t);
1867
1868 /* total size of refcount blocks
1869 *
1870 * note: every host cluster is reference-counted, including metadata
1871 * (even refcount blocks are recursively included).
1872 * Let:
1873 * a = total_size (this is the guest disk size)
1874 * m = meta size not including refcount blocks and refcount tables
1875 * c = cluster size
1876 * y1 = number of refcount blocks entries
1877 * y2 = meta size including everything
bd4b167f 1878 * rces = refcount entry size in bytes
0e4271b7
HT
1879 * then,
1880 * y1 = (y2 + a)/c
bd4b167f 1881 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
0e4271b7 1882 * we can get y1:
bd4b167f 1883 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
0e4271b7 1884 */
bd4b167f
HR
1885 nrefblocke = (aligned_total_size + meta_size + cluster_size)
1886 / (cluster_size - rces - rces * sizeof(uint64_t)
1887 / cluster_size);
1888 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
0e4271b7
HT
1889
1890 /* total size of refcount tables */
bd4b167f 1891 nreftablee = nrefblocke / refblock_size;
0e4271b7
HT
1892 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
1893 meta_size += nreftablee * sizeof(uint64_t);
1894
1895 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
39101f25 1896 aligned_total_size + meta_size, &error_abort);
f43e47db
MA
1897 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
1898 &error_abort);
0e4271b7
HT
1899 }
1900
c282e1fd 1901 ret = bdrv_create_file(filename, opts, &local_err);
a9420734 1902 if (ret < 0) {
3ef6c40a 1903 error_propagate(errp, local_err);
a9420734
KW
1904 return ret;
1905 }
1906
2e40134b
HR
1907 bs = NULL;
1908 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1909 NULL, &local_err);
a9420734 1910 if (ret < 0) {
3ef6c40a 1911 error_propagate(errp, local_err);
a9420734
KW
1912 return ret;
1913 }
1914
1915 /* Write the header */
f8413b3c
KW
1916 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1917 header = g_malloc0(cluster_size);
1918 *header = (QCowHeader) {
1919 .magic = cpu_to_be32(QCOW_MAGIC),
1920 .version = cpu_to_be32(version),
1921 .cluster_bits = cpu_to_be32(cluster_bits),
1922 .size = cpu_to_be64(0),
1923 .l1_table_offset = cpu_to_be64(0),
1924 .l1_size = cpu_to_be32(0),
1925 .refcount_table_offset = cpu_to_be64(cluster_size),
1926 .refcount_table_clusters = cpu_to_be32(1),
bd4b167f 1927 .refcount_order = cpu_to_be32(refcount_order),
f8413b3c
KW
1928 .header_length = cpu_to_be32(sizeof(*header)),
1929 };
a9420734
KW
1930
1931 if (flags & BLOCK_FLAG_ENCRYPT) {
f8413b3c 1932 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
a9420734 1933 } else {
f8413b3c 1934 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734
KW
1935 }
1936
bfe8043e 1937 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
f8413b3c 1938 header->compatible_features |=
bfe8043e
SH
1939 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1940 }
1941
f8413b3c
KW
1942 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1943 g_free(header);
a9420734 1944 if (ret < 0) {
3ef6c40a 1945 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
1946 goto out;
1947 }
1948
b106ad91
KW
1949 /* Write a refcount table with one refcount block */
1950 refcount_table = g_malloc0(2 * cluster_size);
1951 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1952 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
7267c094 1953 g_free(refcount_table);
a9420734
KW
1954
1955 if (ret < 0) {
3ef6c40a 1956 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
1957 goto out;
1958 }
1959
f67503e5
HR
1960 bdrv_unref(bs);
1961 bs = NULL;
a9420734
KW
1962
1963 /*
1964 * And now open the image and make it consistent first (i.e. increase the
1965 * refcount of the cluster that is occupied by the header and the refcount
1966 * table)
1967 */
ddf5636d 1968 ret = bdrv_open(&bs, filename, NULL, NULL,
ef810437
HR
1969 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
1970 &bdrv_qcow2, &local_err);
a9420734 1971 if (ret < 0) {
3ef6c40a 1972 error_propagate(errp, local_err);
a9420734
KW
1973 goto out;
1974 }
1975
b106ad91 1976 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
a9420734 1977 if (ret < 0) {
3ef6c40a
HR
1978 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1979 "header and refcount table");
a9420734
KW
1980 goto out;
1981
1982 } else if (ret != 0) {
1983 error_report("Huh, first cluster in empty image is already in use?");
1984 abort();
1985 }
1986
1987 /* Okay, now that we have a valid image, let's give it the right size */
180e9526 1988 ret = bdrv_truncate(bs, total_size);
a9420734 1989 if (ret < 0) {
3ef6c40a 1990 error_setg_errno(errp, -ret, "Could not resize image");
a9420734
KW
1991 goto out;
1992 }
1993
1994 /* Want a backing file? There you go.*/
1995 if (backing_file) {
1996 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1997 if (ret < 0) {
3ef6c40a
HR
1998 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1999 "with format '%s'", backing_file, backing_format);
a9420734
KW
2000 goto out;
2001 }
2002 }
2003
2004 /* And if we're supposed to preallocate metadata, do that now */
0e4271b7 2005 if (prealloc != PREALLOC_MODE_OFF) {
15552c4a
ZYW
2006 BDRVQcowState *s = bs->opaque;
2007 qemu_co_mutex_lock(&s->lock);
a9420734 2008 ret = preallocate(bs);
15552c4a 2009 qemu_co_mutex_unlock(&s->lock);
a9420734 2010 if (ret < 0) {
3ef6c40a 2011 error_setg_errno(errp, -ret, "Could not preallocate metadata");
a9420734
KW
2012 goto out;
2013 }
2014 }
2015
f67503e5
HR
2016 bdrv_unref(bs);
2017 bs = NULL;
ba2ab2f2
HR
2018
2019 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
ddf5636d 2020 ret = bdrv_open(&bs, filename, NULL, NULL,
c9fbb99d 2021 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
ef810437 2022 &bdrv_qcow2, &local_err);
84d18f06 2023 if (local_err) {
ba2ab2f2
HR
2024 error_propagate(errp, local_err);
2025 goto out;
2026 }
2027
a9420734
KW
2028 ret = 0;
2029out:
f67503e5
HR
2030 if (bs) {
2031 bdrv_unref(bs);
2032 }
a9420734
KW
2033 return ret;
2034}
de5f3f40 2035
1bd0e2d1 2036static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
de5f3f40 2037{
1bd0e2d1
CL
2038 char *backing_file = NULL;
2039 char *backing_fmt = NULL;
2040 char *buf = NULL;
180e9526 2041 uint64_t size = 0;
de5f3f40 2042 int flags = 0;
99cce9fa 2043 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
ffeaac9b 2044 PreallocMode prealloc;
8ad1898c 2045 int version = 3;
bd4b167f
HR
2046 uint64_t refcount_bits = 16;
2047 int refcount_order;
3ef6c40a
HR
2048 Error *local_err = NULL;
2049 int ret;
de5f3f40
KW
2050
2051 /* Read out options */
180e9526
HT
2052 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2053 BDRV_SECTOR_SIZE);
1bd0e2d1
CL
2054 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2055 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2056 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2057 flags |= BLOCK_FLAG_ENCRYPT;
2058 }
2059 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2060 DEFAULT_CLUSTER_SIZE);
2061 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
ffeaac9b
HT
2062 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2063 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
2064 &local_err);
2065 if (local_err) {
2066 error_propagate(errp, local_err);
1bd0e2d1
CL
2067 ret = -EINVAL;
2068 goto finish;
2069 }
2070 g_free(buf);
2071 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2072 if (!buf) {
2073 /* keep the default */
2074 } else if (!strcmp(buf, "0.10")) {
2075 version = 2;
2076 } else if (!strcmp(buf, "1.1")) {
2077 version = 3;
2078 } else {
2079 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2080 ret = -EINVAL;
2081 goto finish;
2082 }
2083
2084 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2085 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
de5f3f40
KW
2086 }
2087
ffeaac9b 2088 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
3ef6c40a
HR
2089 error_setg(errp, "Backing file and preallocation cannot be used at "
2090 "the same time");
1bd0e2d1
CL
2091 ret = -EINVAL;
2092 goto finish;
de5f3f40
KW
2093 }
2094
bfe8043e 2095 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
3ef6c40a
HR
2096 error_setg(errp, "Lazy refcounts only supported with compatibility "
2097 "level 1.1 and above (use compat=1.1 or greater)");
1bd0e2d1
CL
2098 ret = -EINVAL;
2099 goto finish;
bfe8043e
SH
2100 }
2101
06d05fa7
HR
2102 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2103 refcount_bits);
2104 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2105 error_setg(errp, "Refcount width must be a power of two and may not "
2106 "exceed 64 bits");
2107 ret = -EINVAL;
2108 goto finish;
2109 }
2110
bd4b167f
HR
2111 if (version < 3 && refcount_bits != 16) {
2112 error_setg(errp, "Different refcount widths than 16 bits require "
2113 "compatibility level 1.1 or above (use compat=1.1 or "
2114 "greater)");
2115 ret = -EINVAL;
2116 goto finish;
2117 }
2118
786a4ea8 2119 refcount_order = ctz32(refcount_bits);
bd4b167f 2120
180e9526 2121 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
bd4b167f
HR
2122 cluster_size, prealloc, opts, version, refcount_order,
2123 &local_err);
84d18f06 2124 if (local_err) {
3ef6c40a
HR
2125 error_propagate(errp, local_err);
2126 }
1bd0e2d1
CL
2127
2128finish:
2129 g_free(backing_file);
2130 g_free(backing_fmt);
2131 g_free(buf);
3ef6c40a 2132 return ret;
de5f3f40
KW
2133}
2134
621f0589 2135static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
aa7bfbff 2136 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
621f0589
KW
2137{
2138 int ret;
2139 BDRVQcowState *s = bs->opaque;
2140
2141 /* Emulate misaligned zero writes */
2142 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2143 return -ENOTSUP;
2144 }
2145
2146 /* Whatever is left can use real zero clusters */
2147 qemu_co_mutex_lock(&s->lock);
2148 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2149 nb_sectors);
2150 qemu_co_mutex_unlock(&s->lock);
2151
2152 return ret;
2153}
2154
6db39ae2
PB
2155static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2156 int64_t sector_num, int nb_sectors)
5ea929e3 2157{
6db39ae2
PB
2158 int ret;
2159 BDRVQcowState *s = bs->opaque;
2160
2161 qemu_co_mutex_lock(&s->lock);
2162 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
808c4b6f 2163 nb_sectors, QCOW2_DISCARD_REQUEST, false);
6db39ae2
PB
2164 qemu_co_mutex_unlock(&s->lock);
2165 return ret;
5ea929e3
KW
2166}
2167
419b19d9
SH
2168static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2169{
2170 BDRVQcowState *s = bs->opaque;
2cf7cfa1
KW
2171 int64_t new_l1_size;
2172 int ret;
419b19d9
SH
2173
2174 if (offset & 511) {
259b2173 2175 error_report("The new size must be a multiple of 512");
419b19d9
SH
2176 return -EINVAL;
2177 }
2178
2179 /* cannot proceed if image has snapshots */
2180 if (s->nb_snapshots) {
259b2173 2181 error_report("Can't resize an image which has snapshots");
419b19d9
SH
2182 return -ENOTSUP;
2183 }
2184
2185 /* shrinking is currently not supported */
2186 if (offset < bs->total_sectors * 512) {
259b2173 2187 error_report("qcow2 doesn't support shrinking images yet");
419b19d9
SH
2188 return -ENOTSUP;
2189 }
2190
2191 new_l1_size = size_to_l1(s, offset);
72893756 2192 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
419b19d9
SH
2193 if (ret < 0) {
2194 return ret;
2195 }
2196
2197 /* write updated header.size */
2198 offset = cpu_to_be64(offset);
8b3b7206
KW
2199 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2200 &offset, sizeof(uint64_t));
419b19d9
SH
2201 if (ret < 0) {
2202 return ret;
2203 }
2204
2205 s->l1_vm_state_index = new_l1_size;
2206 return 0;
2207}
2208
20d97356
BS
2209/* XXX: put compressed sectors first, then all the cluster aligned
2210 tables to avoid losing bytes in alignment */
7c80ab3f
JS
2211static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2212 const uint8_t *buf, int nb_sectors)
20d97356
BS
2213{
2214 BDRVQcowState *s = bs->opaque;
2215 z_stream strm;
2216 int ret, out_len;
2217 uint8_t *out_buf;
2218 uint64_t cluster_offset;
2219
2220 if (nb_sectors == 0) {
2221 /* align end of file to a sector boundary to ease reading with
2222 sector based I/Os */
66f82cee 2223 cluster_offset = bdrv_getlength(bs->file);
6a69b962 2224 return bdrv_truncate(bs->file, cluster_offset);
20d97356
BS
2225 }
2226
f4d38bef
SH
2227 if (nb_sectors != s->cluster_sectors) {
2228 ret = -EINVAL;
2229
2230 /* Zero-pad last write if image size is not cluster aligned */
2231 if (sector_num + nb_sectors == bs->total_sectors &&
2232 nb_sectors < s->cluster_sectors) {
2233 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2234 memset(pad_buf, 0, s->cluster_size);
2235 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2236 ret = qcow2_write_compressed(bs, sector_num,
2237 pad_buf, s->cluster_sectors);
2238 qemu_vfree(pad_buf);
2239 }
2240 return ret;
2241 }
20d97356 2242
7267c094 2243 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
20d97356
BS
2244
2245 /* best compression, small window, no zlib header */
2246 memset(&strm, 0, sizeof(strm));
2247 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2248 Z_DEFLATED, -12,
2249 9, Z_DEFAULT_STRATEGY);
2250 if (ret != 0) {
8f1efd00
KW
2251 ret = -EINVAL;
2252 goto fail;
20d97356
BS
2253 }
2254
2255 strm.avail_in = s->cluster_size;
2256 strm.next_in = (uint8_t *)buf;
2257 strm.avail_out = s->cluster_size;
2258 strm.next_out = out_buf;
2259
2260 ret = deflate(&strm, Z_FINISH);
2261 if (ret != Z_STREAM_END && ret != Z_OK) {
20d97356 2262 deflateEnd(&strm);
8f1efd00
KW
2263 ret = -EINVAL;
2264 goto fail;
20d97356
BS
2265 }
2266 out_len = strm.next_out - out_buf;
2267
2268 deflateEnd(&strm);
2269
2270 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2271 /* could not compress: write normal cluster */
8f1efd00
KW
2272 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2273 if (ret < 0) {
2274 goto fail;
2275 }
20d97356
BS
2276 } else {
2277 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2278 sector_num << 9, out_len);
8f1efd00
KW
2279 if (!cluster_offset) {
2280 ret = -EIO;
2281 goto fail;
2282 }
20d97356 2283 cluster_offset &= s->cluster_offset_mask;
cf93980e 2284
231bb267 2285 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
cf93980e
HR
2286 if (ret < 0) {
2287 goto fail;
2288 }
2289
66f82cee 2290 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
8f1efd00
KW
2291 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2292 if (ret < 0) {
2293 goto fail;
20d97356
BS
2294 }
2295 }
2296
8f1efd00
KW
2297 ret = 0;
2298fail:
7267c094 2299 g_free(out_buf);
8f1efd00 2300 return ret;
20d97356
BS
2301}
2302
94054183
HR
2303static int make_completely_empty(BlockDriverState *bs)
2304{
2305 BDRVQcowState *s = bs->opaque;
2306 int ret, l1_clusters;
2307 int64_t offset;
2308 uint64_t *new_reftable = NULL;
2309 uint64_t rt_entry, l1_size2;
2310 struct {
2311 uint64_t l1_offset;
2312 uint64_t reftable_offset;
2313 uint32_t reftable_clusters;
2314 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2315
2316 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2317 if (ret < 0) {
2318 goto fail;
2319 }
2320
2321 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2322 if (ret < 0) {
2323 goto fail;
2324 }
2325
2326 /* Refcounts will be broken utterly */
2327 ret = qcow2_mark_dirty(bs);
2328 if (ret < 0) {
2329 goto fail;
2330 }
2331
2332 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2333
2334 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2335 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2336
2337 /* After this call, neither the in-memory nor the on-disk refcount
2338 * information accurately describe the actual references */
2339
2340 ret = bdrv_write_zeroes(bs->file, s->l1_table_offset / BDRV_SECTOR_SIZE,
2341 l1_clusters * s->cluster_sectors, 0);
2342 if (ret < 0) {
2343 goto fail_broken_refcounts;
2344 }
2345 memset(s->l1_table, 0, l1_size2);
2346
2347 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2348
2349 /* Overwrite enough clusters at the beginning of the sectors to place
2350 * the refcount table, a refcount block and the L1 table in; this may
2351 * overwrite parts of the existing refcount and L1 table, which is not
2352 * an issue because the dirty flag is set, complete data loss is in fact
2353 * desired and partial data loss is consequently fine as well */
2354 ret = bdrv_write_zeroes(bs->file, s->cluster_size / BDRV_SECTOR_SIZE,
2355 (2 + l1_clusters) * s->cluster_size /
2356 BDRV_SECTOR_SIZE, 0);
2357 /* This call (even if it failed overall) may have overwritten on-disk
2358 * refcount structures; in that case, the in-memory refcount information
2359 * will probably differ from the on-disk information which makes the BDS
2360 * unusable */
2361 if (ret < 0) {
2362 goto fail_broken_refcounts;
2363 }
2364
2365 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2366 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2367
2368 /* "Create" an empty reftable (one cluster) directly after the image
2369 * header and an empty L1 table three clusters after the image header;
2370 * the cluster between those two will be used as the first refblock */
2371 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2372 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2373 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2374 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2375 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2376 if (ret < 0) {
2377 goto fail_broken_refcounts;
2378 }
2379
2380 s->l1_table_offset = 3 * s->cluster_size;
2381
2382 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2383 if (!new_reftable) {
2384 ret = -ENOMEM;
2385 goto fail_broken_refcounts;
2386 }
2387
2388 s->refcount_table_offset = s->cluster_size;
2389 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2390
2391 g_free(s->refcount_table);
2392 s->refcount_table = new_reftable;
2393 new_reftable = NULL;
2394
2395 /* Now the in-memory refcount information again corresponds to the on-disk
2396 * information (reftable is empty and no refblocks (the refblock cache is
2397 * empty)); however, this means some clusters (e.g. the image header) are
2398 * referenced, but not refcounted, but the normal qcow2 code assumes that
2399 * the in-memory information is always correct */
2400
2401 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2402
2403 /* Enter the first refblock into the reftable */
2404 rt_entry = cpu_to_be64(2 * s->cluster_size);
2405 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2406 &rt_entry, sizeof(rt_entry));
2407 if (ret < 0) {
2408 goto fail_broken_refcounts;
2409 }
2410 s->refcount_table[0] = 2 * s->cluster_size;
2411
2412 s->free_cluster_index = 0;
2413 assert(3 + l1_clusters <= s->refcount_block_size);
2414 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2415 if (offset < 0) {
2416 ret = offset;
2417 goto fail_broken_refcounts;
2418 } else if (offset > 0) {
2419 error_report("First cluster in emptied image is in use");
2420 abort();
2421 }
2422
2423 /* Now finally the in-memory information corresponds to the on-disk
2424 * structures and is correct */
2425 ret = qcow2_mark_clean(bs);
2426 if (ret < 0) {
2427 goto fail;
2428 }
2429
2430 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size);
2431 if (ret < 0) {
2432 goto fail;
2433 }
2434
2435 return 0;
2436
2437fail_broken_refcounts:
2438 /* The BDS is unusable at this point. If we wanted to make it usable, we
2439 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2440 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2441 * again. However, because the functions which could have caused this error
2442 * path to be taken are used by those functions as well, it's very likely
2443 * that that sequence will fail as well. Therefore, just eject the BDS. */
2444 bs->drv = NULL;
2445
2446fail:
2447 g_free(new_reftable);
2448 return ret;
2449}
2450
491d27e2
HR
2451static int qcow2_make_empty(BlockDriverState *bs)
2452{
94054183 2453 BDRVQcowState *s = bs->opaque;
491d27e2
HR
2454 uint64_t start_sector;
2455 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
94054183
HR
2456 int l1_clusters, ret = 0;
2457
2458 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2459
2460 if (s->qcow_version >= 3 && !s->snapshots &&
2461 3 + l1_clusters <= s->refcount_block_size) {
2462 /* The following function only works for qcow2 v3 images (it requires
2463 * the dirty flag) and only as long as there are no snapshots (because
2464 * it completely empties the image). Furthermore, the L1 table and three
2465 * additional clusters (image header, refcount table, one refcount
2466 * block) have to fit inside one refcount block. */
2467 return make_completely_empty(bs);
2468 }
491d27e2 2469
94054183
HR
2470 /* This fallback code simply discards every active cluster; this is slow,
2471 * but works in all cases */
491d27e2
HR
2472 for (start_sector = 0; start_sector < bs->total_sectors;
2473 start_sector += sector_step)
2474 {
2475 /* As this function is generally used after committing an external
2476 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2477 * default action for this kind of discard is to pass the discard,
2478 * which will ideally result in an actually smaller image file, as
2479 * is probably desired. */
2480 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2481 MIN(sector_step,
2482 bs->total_sectors - start_sector),
2483 QCOW2_DISCARD_SNAPSHOT, true);
2484 if (ret < 0) {
2485 break;
2486 }
2487 }
2488
2489 return ret;
2490}
2491
a968168c 2492static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 2493{
29c1a730
KW
2494 BDRVQcowState *s = bs->opaque;
2495 int ret;
2496
8b94ff85 2497 qemu_co_mutex_lock(&s->lock);
29c1a730
KW
2498 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2499 if (ret < 0) {
c95de7e2 2500 qemu_co_mutex_unlock(&s->lock);
8b94ff85 2501 return ret;
29c1a730
KW
2502 }
2503
bfe8043e
SH
2504 if (qcow2_need_accurate_refcounts(s)) {
2505 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2506 if (ret < 0) {
2507 qemu_co_mutex_unlock(&s->lock);
2508 return ret;
2509 }
29c1a730 2510 }
8b94ff85 2511 qemu_co_mutex_unlock(&s->lock);
29c1a730 2512
eb489bb1
KW
2513 return 0;
2514}
2515
7c80ab3f 2516static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356
BS
2517{
2518 BDRVQcowState *s = bs->opaque;
95de6d70
PB
2519 bdi->unallocated_blocks_are_zero = true;
2520 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
20d97356 2521 bdi->cluster_size = s->cluster_size;
7c80ab3f 2522 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
2523 return 0;
2524}
2525
37764dfb
HR
2526static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2527{
2528 BDRVQcowState *s = bs->opaque;
2529 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2530
2531 *spec_info = (ImageInfoSpecific){
2532 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2533 {
2534 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2535 },
2536 };
2537 if (s->qcow_version == 2) {
2538 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
0709c5a1
HR
2539 .compat = g_strdup("0.10"),
2540 .refcount_bits = s->refcount_bits,
37764dfb
HR
2541 };
2542 } else if (s->qcow_version == 3) {
2543 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2544 .compat = g_strdup("1.1"),
2545 .lazy_refcounts = s->compatible_features &
2546 QCOW2_COMPAT_LAZY_REFCOUNTS,
2547 .has_lazy_refcounts = true,
9009b196
HR
2548 .corrupt = s->incompatible_features &
2549 QCOW2_INCOMPAT_CORRUPT,
2550 .has_corrupt = true,
0709c5a1 2551 .refcount_bits = s->refcount_bits,
37764dfb
HR
2552 };
2553 }
2554
2555 return spec_info;
2556}
2557
20d97356
BS
2558#if 0
2559static void dump_refcounts(BlockDriverState *bs)
2560{
2561 BDRVQcowState *s = bs->opaque;
2562 int64_t nb_clusters, k, k1, size;
2563 int refcount;
2564
66f82cee 2565 size = bdrv_getlength(bs->file);
20d97356
BS
2566 nb_clusters = size_to_clusters(s, size);
2567 for(k = 0; k < nb_clusters;) {
2568 k1 = k;
2569 refcount = get_refcount(bs, k);
2570 k++;
2571 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2572 k++;
0bfcd599
BS
2573 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2574 k - k1);
20d97356
BS
2575 }
2576}
2577#endif
2578
cf8074b3
KW
2579static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2580 int64_t pos)
20d97356
BS
2581{
2582 BDRVQcowState *s = bs->opaque;
eedff66f 2583 int64_t total_sectors = bs->total_sectors;
6e13610a 2584 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2585 int ret;
2586
66f82cee 2587 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
6e13610a 2588 bs->zero_beyond_eof = false;
8d3b1a2d 2589 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
6e13610a 2590 bs->zero_beyond_eof = zero_beyond_eof;
20d97356 2591
eedff66f
HR
2592 /* bdrv_co_do_writev will have increased the total_sectors value to include
2593 * the VM state - the VM state is however not an actual part of the block
2594 * device, therefore, we need to restore the old value. */
2595 bs->total_sectors = total_sectors;
2596
20d97356
BS
2597 return ret;
2598}
2599
7c80ab3f
JS
2600static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2601 int64_t pos, int size)
20d97356
BS
2602{
2603 BDRVQcowState *s = bs->opaque;
0d51b4de 2604 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2605 int ret;
2606
66f82cee 2607 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
0d51b4de 2608 bs->zero_beyond_eof = false;
7c80ab3f 2609 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
0d51b4de 2610 bs->zero_beyond_eof = zero_beyond_eof;
20d97356
BS
2611
2612 return ret;
2613}
2614
9296b3ed
HR
2615/*
2616 * Downgrades an image's version. To achieve this, any incompatible features
2617 * have to be removed.
2618 */
4057a2b2
HR
2619static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2620 BlockDriverAmendStatusCB *status_cb)
9296b3ed
HR
2621{
2622 BDRVQcowState *s = bs->opaque;
2623 int current_version = s->qcow_version;
2624 int ret;
2625
2626 if (target_version == current_version) {
2627 return 0;
2628 } else if (target_version > current_version) {
2629 return -EINVAL;
2630 } else if (target_version != 2) {
2631 return -EINVAL;
2632 }
2633
2634 if (s->refcount_order != 4) {
2635 /* we would have to convert the image to a refcount_order == 4 image
2636 * here; however, since qemu (at the time of writing this) does not
2637 * support anything different than 4 anyway, there is no point in doing
2638 * so right now; however, we should error out (if qemu supports this in
2639 * the future and this code has not been adapted) */
9e3f0892 2640 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
9296b3ed
HR
2641 "currently not supported.");
2642 return -ENOTSUP;
2643 }
2644
2645 /* clear incompatible features */
2646 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2647 ret = qcow2_mark_clean(bs);
2648 if (ret < 0) {
2649 return ret;
2650 }
2651 }
2652
2653 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2654 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2655 * best thing to do anyway */
2656
2657 if (s->incompatible_features) {
2658 return -ENOTSUP;
2659 }
2660
2661 /* since we can ignore compatible features, we can set them to 0 as well */
2662 s->compatible_features = 0;
2663 /* if lazy refcounts have been used, they have already been fixed through
2664 * clearing the dirty flag */
2665
2666 /* clearing autoclear features is trivial */
2667 s->autoclear_features = 0;
2668
4057a2b2 2669 ret = qcow2_expand_zero_clusters(bs, status_cb);
9296b3ed
HR
2670 if (ret < 0) {
2671 return ret;
2672 }
2673
2674 s->qcow_version = target_version;
2675 ret = qcow2_update_header(bs);
2676 if (ret < 0) {
2677 s->qcow_version = current_version;
2678 return ret;
2679 }
2680 return 0;
2681}
2682
77485434
HR
2683static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
2684 BlockDriverAmendStatusCB *status_cb)
9296b3ed
HR
2685{
2686 BDRVQcowState *s = bs->opaque;
2687 int old_version = s->qcow_version, new_version = old_version;
2688 uint64_t new_size = 0;
2689 const char *backing_file = NULL, *backing_format = NULL;
2690 bool lazy_refcounts = s->use_lazy_refcounts;
1bd0e2d1
CL
2691 const char *compat = NULL;
2692 uint64_t cluster_size = s->cluster_size;
2693 bool encrypt;
9296b3ed 2694 int ret;
1bd0e2d1 2695 QemuOptDesc *desc = opts->list->desc;
9296b3ed 2696
1bd0e2d1
CL
2697 while (desc && desc->name) {
2698 if (!qemu_opt_find(opts, desc->name)) {
9296b3ed 2699 /* only change explicitly defined options */
1bd0e2d1 2700 desc++;
9296b3ed
HR
2701 continue;
2702 }
2703
8a17b83c
HR
2704 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
2705 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
1bd0e2d1 2706 if (!compat) {
9296b3ed 2707 /* preserve default */
1bd0e2d1 2708 } else if (!strcmp(compat, "0.10")) {
9296b3ed 2709 new_version = 2;
1bd0e2d1 2710 } else if (!strcmp(compat, "1.1")) {
9296b3ed
HR
2711 new_version = 3;
2712 } else {
1bd0e2d1 2713 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
9296b3ed
HR
2714 return -EINVAL;
2715 }
8a17b83c 2716 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
9296b3ed
HR
2717 fprintf(stderr, "Cannot change preallocation mode.\n");
2718 return -ENOTSUP;
8a17b83c
HR
2719 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
2720 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
2721 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
2722 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2723 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
2724 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
2725 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
2726 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
2727 s->crypt_method);
1bd0e2d1 2728 if (encrypt != !!s->crypt_method) {
9296b3ed
HR
2729 fprintf(stderr, "Changing the encryption flag is not "
2730 "supported.\n");
2731 return -ENOTSUP;
2732 }
8a17b83c
HR
2733 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
2734 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
1bd0e2d1
CL
2735 cluster_size);
2736 if (cluster_size != s->cluster_size) {
9296b3ed
HR
2737 fprintf(stderr, "Changing the cluster size is not "
2738 "supported.\n");
2739 return -ENOTSUP;
2740 }
8a17b83c
HR
2741 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
2742 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
1bd0e2d1 2743 lazy_refcounts);
06d05fa7
HR
2744 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
2745 error_report("Cannot change refcount entry width");
2746 return -ENOTSUP;
9296b3ed
HR
2747 } else {
2748 /* if this assertion fails, this probably means a new option was
2749 * added without having it covered here */
2750 assert(false);
2751 }
1bd0e2d1
CL
2752
2753 desc++;
9296b3ed
HR
2754 }
2755
2756 if (new_version != old_version) {
2757 if (new_version > old_version) {
2758 /* Upgrade */
2759 s->qcow_version = new_version;
2760 ret = qcow2_update_header(bs);
2761 if (ret < 0) {
2762 s->qcow_version = old_version;
2763 return ret;
2764 }
2765 } else {
4057a2b2 2766 ret = qcow2_downgrade(bs, new_version, status_cb);
9296b3ed
HR
2767 if (ret < 0) {
2768 return ret;
2769 }
2770 }
2771 }
2772
2773 if (backing_file || backing_format) {
e4603fe1
KW
2774 ret = qcow2_change_backing_file(bs,
2775 backing_file ?: s->image_backing_file,
2776 backing_format ?: s->image_backing_format);
9296b3ed
HR
2777 if (ret < 0) {
2778 return ret;
2779 }
2780 }
2781
2782 if (s->use_lazy_refcounts != lazy_refcounts) {
2783 if (lazy_refcounts) {
2784 if (s->qcow_version < 3) {
2785 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2786 "level 1.1 and above (use compat=1.1 or greater)\n");
2787 return -EINVAL;
2788 }
2789 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2790 ret = qcow2_update_header(bs);
2791 if (ret < 0) {
2792 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2793 return ret;
2794 }
2795 s->use_lazy_refcounts = true;
2796 } else {
2797 /* make image clean first */
2798 ret = qcow2_mark_clean(bs);
2799 if (ret < 0) {
2800 return ret;
2801 }
2802 /* now disallow lazy refcounts */
2803 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2804 ret = qcow2_update_header(bs);
2805 if (ret < 0) {
2806 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2807 return ret;
2808 }
2809 s->use_lazy_refcounts = false;
2810 }
2811 }
2812
2813 if (new_size) {
2814 ret = bdrv_truncate(bs, new_size);
2815 if (ret < 0) {
2816 return ret;
2817 }
2818 }
2819
2820 return 0;
2821}
2822
85186ebd
HR
2823/*
2824 * If offset or size are negative, respectively, they will not be included in
2825 * the BLOCK_IMAGE_CORRUPTED event emitted.
2826 * fatal will be ignored for read-only BDS; corruptions found there will always
2827 * be considered non-fatal.
2828 */
2829void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
2830 int64_t size, const char *message_format, ...)
2831{
2832 BDRVQcowState *s = bs->opaque;
dc881b44 2833 const char *node_name;
85186ebd
HR
2834 char *message;
2835 va_list ap;
2836
2837 fatal = fatal && !bs->read_only;
2838
2839 if (s->signaled_corruption &&
2840 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
2841 {
2842 return;
2843 }
2844
2845 va_start(ap, message_format);
2846 message = g_strdup_vprintf(message_format, ap);
2847 va_end(ap);
2848
2849 if (fatal) {
2850 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
2851 "corruption events will be suppressed\n", message);
2852 } else {
2853 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
2854 "corruption events will be suppressed\n", message);
2855 }
2856
dc881b44
AG
2857 node_name = bdrv_get_node_name(bs);
2858 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
2859 *node_name != '\0', node_name,
2860 message, offset >= 0, offset,
2861 size >= 0, size,
85186ebd
HR
2862 fatal, &error_abort);
2863 g_free(message);
2864
2865 if (fatal) {
2866 qcow2_mark_corrupt(bs);
2867 bs->drv = NULL; /* make BDS unusable */
2868 }
2869
2870 s->signaled_corruption = true;
2871}
2872
1bd0e2d1
CL
2873static QemuOptsList qcow2_create_opts = {
2874 .name = "qcow2-create-opts",
2875 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2876 .desc = {
2877 {
2878 .name = BLOCK_OPT_SIZE,
2879 .type = QEMU_OPT_SIZE,
2880 .help = "Virtual disk size"
2881 },
2882 {
2883 .name = BLOCK_OPT_COMPAT_LEVEL,
2884 .type = QEMU_OPT_STRING,
2885 .help = "Compatibility level (0.10 or 1.1)"
2886 },
2887 {
2888 .name = BLOCK_OPT_BACKING_FILE,
2889 .type = QEMU_OPT_STRING,
2890 .help = "File name of a base image"
2891 },
2892 {
2893 .name = BLOCK_OPT_BACKING_FMT,
2894 .type = QEMU_OPT_STRING,
2895 .help = "Image format of the base image"
2896 },
2897 {
2898 .name = BLOCK_OPT_ENCRYPT,
2899 .type = QEMU_OPT_BOOL,
2900 .help = "Encrypt the image",
2901 .def_value_str = "off"
2902 },
2903 {
2904 .name = BLOCK_OPT_CLUSTER_SIZE,
2905 .type = QEMU_OPT_SIZE,
2906 .help = "qcow2 cluster size",
2907 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
2908 },
2909 {
2910 .name = BLOCK_OPT_PREALLOC,
2911 .type = QEMU_OPT_STRING,
0e4271b7
HT
2912 .help = "Preallocation mode (allowed values: off, metadata, "
2913 "falloc, full)"
1bd0e2d1
CL
2914 },
2915 {
2916 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2917 .type = QEMU_OPT_BOOL,
2918 .help = "Postpone refcount updates",
2919 .def_value_str = "off"
2920 },
06d05fa7
HR
2921 {
2922 .name = BLOCK_OPT_REFCOUNT_BITS,
2923 .type = QEMU_OPT_NUMBER,
2924 .help = "Width of a reference count entry in bits",
2925 .def_value_str = "16"
2926 },
1bd0e2d1
CL
2927 { /* end of list */ }
2928 }
20d97356
BS
2929};
2930
5f535a94 2931BlockDriver bdrv_qcow2 = {
7c80ab3f
JS
2932 .format_name = "qcow2",
2933 .instance_size = sizeof(BDRVQcowState),
2934 .bdrv_probe = qcow2_probe,
2935 .bdrv_open = qcow2_open,
2936 .bdrv_close = qcow2_close,
21d82ac9 2937 .bdrv_reopen_prepare = qcow2_reopen_prepare,
c282e1fd 2938 .bdrv_create = qcow2_create,
3ac21627 2939 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 2940 .bdrv_co_get_block_status = qcow2_co_get_block_status,
7c80ab3f 2941 .bdrv_set_key = qcow2_set_key,
7c80ab3f 2942
c68b89ac
KW
2943 .bdrv_co_readv = qcow2_co_readv,
2944 .bdrv_co_writev = qcow2_co_writev,
eb489bb1 2945 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 2946
621f0589 2947 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
6db39ae2 2948 .bdrv_co_discard = qcow2_co_discard,
419b19d9 2949 .bdrv_truncate = qcow2_truncate,
7c80ab3f 2950 .bdrv_write_compressed = qcow2_write_compressed,
491d27e2 2951 .bdrv_make_empty = qcow2_make_empty,
20d97356
BS
2952
2953 .bdrv_snapshot_create = qcow2_snapshot_create,
2954 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2955 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2956 .bdrv_snapshot_list = qcow2_snapshot_list,
1bd0e2d1
CL
2957 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2958 .bdrv_get_info = qcow2_get_info,
37764dfb 2959 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 2960
7c80ab3f
JS
2961 .bdrv_save_vmstate = qcow2_save_vmstate,
2962 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356 2963
8ee79e70 2964 .supports_backing = true,
20d97356
BS
2965 .bdrv_change_backing_file = qcow2_change_backing_file,
2966
d34682cd 2967 .bdrv_refresh_limits = qcow2_refresh_limits,
06d9260f
AL
2968 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2969
1bd0e2d1
CL
2970 .create_opts = &qcow2_create_opts,
2971 .bdrv_check = qcow2_check,
c282e1fd 2972 .bdrv_amend_options = qcow2_amend_options,
20d97356
BS
2973};
2974
5efa9d5a
AL
2975static void bdrv_qcow2_init(void)
2976{
2977 bdrv_register(&bdrv_qcow2);
2978}
2979
2980block_init(bdrv_qcow2_init);