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