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