]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
qcow2: Validate refcount table offset
[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"
3cce16f4 33#include "trace.h"
585f8587
FB
34
35/*
36 Differences with QCOW:
37
38 - Support for multiple incremental snapshots.
39 - Memory management by reference counts.
40 - Clusters which have a reference count of one have the bit
41 QCOW_OFLAG_COPIED to optimize write performance.
5fafdf24 42 - Size of compressed clusters is stored in sectors to reduce bit usage
585f8587
FB
43 in the cluster offsets.
44 - Support for storing additional data (such as the VM state) in the
3b46e624 45 snapshots.
585f8587
FB
46 - If a backing store is used, the cluster size is not constrained
47 (could be backported to QCOW).
48 - L2 tables have always a size of one cluster.
49*/
50
9b80ddf3
AL
51
52typedef struct {
53 uint32_t magic;
54 uint32_t len;
c4217f64 55} QEMU_PACKED QCowExtension;
21d82ac9 56
7c80ab3f
JS
57#define QCOW2_EXT_MAGIC_END 0
58#define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
cfcc4c62 59#define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
9b80ddf3 60
7c80ab3f 61static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
585f8587
FB
62{
63 const QCowHeader *cow_header = (const void *)buf;
3b46e624 64
585f8587
FB
65 if (buf_size >= sizeof(QCowHeader) &&
66 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
6744cbab 67 be32_to_cpu(cow_header->version) >= 2)
585f8587
FB
68 return 100;
69 else
70 return 0;
71}
72
9b80ddf3
AL
73
74/*
75 * read qcow2 extension and fill bs
76 * start reading from start_offset
77 * finish reading upon magic of value 0 or when end_offset reached
78 * unknown magic is skipped (future extension this version knows nothing about)
79 * return 0 upon success, non-0 otherwise
80 */
7c80ab3f 81static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
3ef6c40a
HR
82 uint64_t end_offset, void **p_feature_table,
83 Error **errp)
9b80ddf3 84{
75bab85c 85 BDRVQcowState *s = bs->opaque;
9b80ddf3
AL
86 QCowExtension ext;
87 uint64_t offset;
75bab85c 88 int ret;
9b80ddf3
AL
89
90#ifdef DEBUG_EXT
7c80ab3f 91 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
9b80ddf3
AL
92#endif
93 offset = start_offset;
94 while (offset < end_offset) {
95
96#ifdef DEBUG_EXT
97 /* Sanity check */
98 if (offset > s->cluster_size)
7c80ab3f 99 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
9b80ddf3 100
9b2260cb 101 printf("attempting to read extended header in offset %lu\n", offset);
9b80ddf3
AL
102#endif
103
3ef6c40a
HR
104 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
105 if (ret < 0) {
106 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
107 "pread fail from offset %" PRIu64, offset);
9b80ddf3
AL
108 return 1;
109 }
110 be32_to_cpus(&ext.magic);
111 be32_to_cpus(&ext.len);
112 offset += sizeof(ext);
113#ifdef DEBUG_EXT
114 printf("ext.magic = 0x%x\n", ext.magic);
115#endif
64ca6aee 116 if (ext.len > end_offset - offset) {
3ef6c40a 117 error_setg(errp, "Header extension too large");
64ca6aee
KW
118 return -EINVAL;
119 }
120
9b80ddf3 121 switch (ext.magic) {
7c80ab3f 122 case QCOW2_EXT_MAGIC_END:
9b80ddf3 123 return 0;
f965509c 124
7c80ab3f 125 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
f965509c 126 if (ext.len >= sizeof(bs->backing_format)) {
3ef6c40a
HR
127 error_setg(errp, "ERROR: ext_backing_format: len=%u too large"
128 " (>=%zu)", ext.len, sizeof(bs->backing_format));
f965509c
AL
129 return 2;
130 }
3ef6c40a
HR
131 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
132 if (ret < 0) {
133 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
134 "Could not read format name");
f965509c 135 return 3;
3ef6c40a 136 }
f965509c
AL
137 bs->backing_format[ext.len] = '\0';
138#ifdef DEBUG_EXT
139 printf("Qcow2: Got format extension %s\n", bs->backing_format);
140#endif
f965509c
AL
141 break;
142
cfcc4c62
KW
143 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
144 if (p_feature_table != NULL) {
145 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
146 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
147 if (ret < 0) {
3ef6c40a
HR
148 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
149 "Could not read table");
cfcc4c62
KW
150 return ret;
151 }
152
153 *p_feature_table = feature_table;
154 }
155 break;
156
9b80ddf3 157 default:
75bab85c
KW
158 /* unknown magic - save it in case we need to rewrite the header */
159 {
160 Qcow2UnknownHeaderExtension *uext;
161
162 uext = g_malloc0(sizeof(*uext) + ext.len);
163 uext->magic = ext.magic;
164 uext->len = ext.len;
165 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
166
167 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
168 if (ret < 0) {
3ef6c40a
HR
169 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
170 "Could not read data");
75bab85c
KW
171 return ret;
172 }
75bab85c 173 }
9b80ddf3
AL
174 break;
175 }
fd29b4bb
KW
176
177 offset += ((ext.len + 7) & ~7);
9b80ddf3
AL
178 }
179
180 return 0;
181}
182
75bab85c
KW
183static void cleanup_unknown_header_ext(BlockDriverState *bs)
184{
185 BDRVQcowState *s = bs->opaque;
186 Qcow2UnknownHeaderExtension *uext, *next;
187
188 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
189 QLIST_REMOVE(uext, next);
190 g_free(uext);
191 }
192}
9b80ddf3 193
3ef6c40a
HR
194static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
195 Error **errp, const char *fmt, ...)
6744cbab
KW
196{
197 char msg[64];
198 va_list ap;
199
200 va_start(ap, fmt);
201 vsnprintf(msg, sizeof(msg), fmt, ap);
202 va_end(ap);
203
3ef6c40a
HR
204 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
205 msg);
6744cbab
KW
206}
207
cfcc4c62 208static void report_unsupported_feature(BlockDriverState *bs,
3ef6c40a 209 Error **errp, Qcow2Feature *table, uint64_t mask)
cfcc4c62
KW
210{
211 while (table && table->name[0] != '\0') {
212 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
213 if (mask & (1 << table->bit)) {
3ef6c40a 214 report_unsupported(bs, errp, "%.46s", table->name);
cfcc4c62
KW
215 mask &= ~(1 << table->bit);
216 }
217 }
218 table++;
219 }
220
221 if (mask) {
3ef6c40a
HR
222 report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64,
223 mask);
cfcc4c62
KW
224 }
225}
226
bfe8043e
SH
227/*
228 * Sets the dirty bit and flushes afterwards if necessary.
229 *
230 * The incompatible_features bit is only set if the image file header was
231 * updated successfully. Therefore it is not required to check the return
232 * value of this function.
233 */
280d3735 234int qcow2_mark_dirty(BlockDriverState *bs)
bfe8043e
SH
235{
236 BDRVQcowState *s = bs->opaque;
237 uint64_t val;
238 int ret;
239
240 assert(s->qcow_version >= 3);
241
242 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
243 return 0; /* already dirty */
244 }
245
246 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
247 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
248 &val, sizeof(val));
249 if (ret < 0) {
250 return ret;
251 }
252 ret = bdrv_flush(bs->file);
253 if (ret < 0) {
254 return ret;
255 }
256
257 /* Only treat image as dirty if the header was updated successfully */
258 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
259 return 0;
260}
261
c61d0004
SH
262/*
263 * Clears the dirty bit and flushes before if necessary. Only call this
264 * function when there are no pending requests, it does not guard against
265 * concurrent requests dirtying the image.
266 */
267static int qcow2_mark_clean(BlockDriverState *bs)
268{
269 BDRVQcowState *s = bs->opaque;
270
271 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
272 int ret = bdrv_flush(bs);
273 if (ret < 0) {
274 return ret;
275 }
276
277 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
278 return qcow2_update_header(bs);
279 }
280 return 0;
281}
282
69c98726
HR
283/*
284 * Marks the image as corrupt.
285 */
286int qcow2_mark_corrupt(BlockDriverState *bs)
287{
288 BDRVQcowState *s = bs->opaque;
289
290 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
291 return qcow2_update_header(bs);
292}
293
294/*
295 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
296 * before if necessary.
297 */
298int qcow2_mark_consistent(BlockDriverState *bs)
299{
300 BDRVQcowState *s = bs->opaque;
301
302 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
303 int ret = bdrv_flush(bs);
304 if (ret < 0) {
305 return ret;
306 }
307
308 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
309 return qcow2_update_header(bs);
310 }
311 return 0;
312}
313
acbe5982
SH
314static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
315 BdrvCheckMode fix)
316{
317 int ret = qcow2_check_refcounts(bs, result, fix);
318 if (ret < 0) {
319 return ret;
320 }
321
322 if (fix && result->check_errors == 0 && result->corruptions == 0) {
24530f3e
HR
323 ret = qcow2_mark_clean(bs);
324 if (ret < 0) {
325 return ret;
326 }
327 return qcow2_mark_consistent(bs);
acbe5982
SH
328 }
329 return ret;
330}
331
8c7de283
KW
332static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
333 uint64_t entries, size_t entry_len)
334{
335 BDRVQcowState *s = bs->opaque;
336 uint64_t size;
337
338 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
339 * because values will be passed to qemu functions taking int64_t. */
340 if (entries > INT64_MAX / entry_len) {
341 return -EINVAL;
342 }
343
344 size = entries * entry_len;
345
346 if (INT64_MAX - size < offset) {
347 return -EINVAL;
348 }
349
350 /* Tables must be cluster aligned */
351 if (offset & (s->cluster_size - 1)) {
352 return -EINVAL;
353 }
354
355 return 0;
356}
357
74c4510a
KW
358static QemuOptsList qcow2_runtime_opts = {
359 .name = "qcow2",
360 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
361 .desc = {
362 {
64aa99d3 363 .name = QCOW2_OPT_LAZY_REFCOUNTS,
74c4510a
KW
364 .type = QEMU_OPT_BOOL,
365 .help = "Postpone refcount updates",
366 },
67af674e
KW
367 {
368 .name = QCOW2_OPT_DISCARD_REQUEST,
369 .type = QEMU_OPT_BOOL,
370 .help = "Pass guest discard requests to the layer below",
371 },
372 {
373 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
374 .type = QEMU_OPT_BOOL,
375 .help = "Generate discard requests when snapshot related space "
376 "is freed",
377 },
378 {
379 .name = QCOW2_OPT_DISCARD_OTHER,
380 .type = QEMU_OPT_BOOL,
381 .help = "Generate discard requests when other clusters are freed",
382 },
05de7e86
HR
383 {
384 .name = QCOW2_OPT_OVERLAP,
385 .type = QEMU_OPT_STRING,
386 .help = "Selects which overlap checks to perform from a range of "
387 "templates (none, constant, cached, all)",
388 },
389 {
390 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
391 .type = QEMU_OPT_BOOL,
392 .help = "Check for unintended writes into the main qcow2 header",
393 },
394 {
395 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
396 .type = QEMU_OPT_BOOL,
397 .help = "Check for unintended writes into the active L1 table",
398 },
399 {
400 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
401 .type = QEMU_OPT_BOOL,
402 .help = "Check for unintended writes into an active L2 table",
403 },
404 {
405 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
406 .type = QEMU_OPT_BOOL,
407 .help = "Check for unintended writes into the refcount table",
408 },
409 {
410 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
411 .type = QEMU_OPT_BOOL,
412 .help = "Check for unintended writes into a refcount block",
413 },
414 {
415 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
416 .type = QEMU_OPT_BOOL,
417 .help = "Check for unintended writes into the snapshot table",
418 },
419 {
420 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
421 .type = QEMU_OPT_BOOL,
422 .help = "Check for unintended writes into an inactive L1 table",
423 },
424 {
425 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
426 .type = QEMU_OPT_BOOL,
427 .help = "Check for unintended writes into an inactive L2 table",
428 },
74c4510a
KW
429 { /* end of list */ }
430 },
431};
432
4092e99d
HR
433static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
434 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
435 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
436 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
437 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
438 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
439 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
440 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
441 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
442};
443
015a1036
HR
444static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
445 Error **errp)
585f8587
FB
446{
447 BDRVQcowState *s = bs->opaque;
6d85a57e 448 int len, i, ret = 0;
585f8587 449 QCowHeader header;
74c4510a
KW
450 QemuOpts *opts;
451 Error *local_err = NULL;
9b80ddf3 452 uint64_t ext_end;
2cf7cfa1 453 uint64_t l1_vm_state_index;
1fa5cc83
HR
454 const char *opt_overlap_check;
455 int overlap_check_template = 0;
585f8587 456
6d85a57e
JS
457 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
458 if (ret < 0) {
3ef6c40a 459 error_setg_errno(errp, -ret, "Could not read qcow2 header");
585f8587 460 goto fail;
6d85a57e 461 }
585f8587
FB
462 be32_to_cpus(&header.magic);
463 be32_to_cpus(&header.version);
464 be64_to_cpus(&header.backing_file_offset);
465 be32_to_cpus(&header.backing_file_size);
466 be64_to_cpus(&header.size);
467 be32_to_cpus(&header.cluster_bits);
468 be32_to_cpus(&header.crypt_method);
469 be64_to_cpus(&header.l1_table_offset);
470 be32_to_cpus(&header.l1_size);
471 be64_to_cpus(&header.refcount_table_offset);
472 be32_to_cpus(&header.refcount_table_clusters);
473 be64_to_cpus(&header.snapshots_offset);
474 be32_to_cpus(&header.nb_snapshots);
3b46e624 475
e8cdcec1 476 if (header.magic != QCOW_MAGIC) {
3ef6c40a 477 error_setg(errp, "Image is not in qcow2 format");
76abe407 478 ret = -EINVAL;
585f8587 479 goto fail;
6d85a57e 480 }
6744cbab 481 if (header.version < 2 || header.version > 3) {
3ef6c40a 482 report_unsupported(bs, errp, "QCOW version %d", header.version);
6744cbab
KW
483 ret = -ENOTSUP;
484 goto fail;
485 }
486
487 s->qcow_version = header.version;
488
24342f2c
KW
489 /* Initialise cluster size */
490 if (header.cluster_bits < MIN_CLUSTER_BITS ||
491 header.cluster_bits > MAX_CLUSTER_BITS) {
492 error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
493 ret = -EINVAL;
494 goto fail;
495 }
496
497 s->cluster_bits = header.cluster_bits;
498 s->cluster_size = 1 << s->cluster_bits;
499 s->cluster_sectors = 1 << (s->cluster_bits - 9);
500
6744cbab
KW
501 /* Initialise version 3 header fields */
502 if (header.version == 2) {
503 header.incompatible_features = 0;
504 header.compatible_features = 0;
505 header.autoclear_features = 0;
506 header.refcount_order = 4;
507 header.header_length = 72;
508 } else {
509 be64_to_cpus(&header.incompatible_features);
510 be64_to_cpus(&header.compatible_features);
511 be64_to_cpus(&header.autoclear_features);
512 be32_to_cpus(&header.refcount_order);
513 be32_to_cpus(&header.header_length);
24342f2c
KW
514
515 if (header.header_length < 104) {
516 error_setg(errp, "qcow2 header too short");
517 ret = -EINVAL;
518 goto fail;
519 }
520 }
521
522 if (header.header_length > s->cluster_size) {
523 error_setg(errp, "qcow2 header exceeds cluster size");
524 ret = -EINVAL;
525 goto fail;
6744cbab
KW
526 }
527
528 if (header.header_length > sizeof(header)) {
529 s->unknown_header_fields_size = header.header_length - sizeof(header);
530 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
531 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
532 s->unknown_header_fields_size);
533 if (ret < 0) {
3ef6c40a
HR
534 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
535 "fields");
6744cbab
KW
536 goto fail;
537 }
538 }
539
a1b3955c
KW
540 if (header.backing_file_offset > s->cluster_size) {
541 error_setg(errp, "Invalid backing file offset");
542 ret = -EINVAL;
543 goto fail;
544 }
545
cfcc4c62
KW
546 if (header.backing_file_offset) {
547 ext_end = header.backing_file_offset;
548 } else {
549 ext_end = 1 << header.cluster_bits;
550 }
551
6744cbab
KW
552 /* Handle feature bits */
553 s->incompatible_features = header.incompatible_features;
554 s->compatible_features = header.compatible_features;
555 s->autoclear_features = header.autoclear_features;
556
c61d0004 557 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
cfcc4c62
KW
558 void *feature_table = NULL;
559 qcow2_read_extensions(bs, header.header_length, ext_end,
3ef6c40a
HR
560 &feature_table, NULL);
561 report_unsupported_feature(bs, errp, feature_table,
c61d0004
SH
562 s->incompatible_features &
563 ~QCOW2_INCOMPAT_MASK);
6744cbab 564 ret = -ENOTSUP;
c5a33ee9 565 g_free(feature_table);
6744cbab
KW
566 goto fail;
567 }
568
69c98726
HR
569 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
570 /* Corrupt images may not be written to unless they are being repaired
571 */
572 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
3ef6c40a
HR
573 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
574 "read/write");
69c98726
HR
575 ret = -EACCES;
576 goto fail;
577 }
578 }
579
6744cbab
KW
580 /* Check support for various header values */
581 if (header.refcount_order != 4) {
3ef6c40a 582 report_unsupported(bs, errp, "%d bit reference counts",
6744cbab 583 1 << header.refcount_order);
e8cdcec1
KW
584 ret = -ENOTSUP;
585 goto fail;
586 }
b6481f37 587 s->refcount_order = header.refcount_order;
6744cbab 588
6d85a57e 589 if (header.crypt_method > QCOW_CRYPT_AES) {
3ef6c40a
HR
590 error_setg(errp, "Unsupported encryption method: %i",
591 header.crypt_method);
6d85a57e 592 ret = -EINVAL;
585f8587 593 goto fail;
6d85a57e 594 }
585f8587 595 s->crypt_method_header = header.crypt_method;
6d85a57e 596 if (s->crypt_method_header) {
585f8587 597 bs->encrypted = 1;
6d85a57e 598 }
24342f2c 599
585f8587
FB
600 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
601 s->l2_size = 1 << s->l2_bits;
602 bs->total_sectors = header.size / 512;
603 s->csize_shift = (62 - (s->cluster_bits - 8));
604 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
605 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
5dab2fad 606
585f8587 607 s->refcount_table_offset = header.refcount_table_offset;
5fafdf24 608 s->refcount_table_size =
585f8587
FB
609 header.refcount_table_clusters << (s->cluster_bits - 3);
610
5dab2fad
KW
611 if (header.refcount_table_clusters > (0x800000 >> s->cluster_bits)) {
612 /* 8 MB refcount table is enough for 2 PB images at 64k cluster size
613 * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
614 error_setg(errp, "Reference count table too large");
615 ret = -EINVAL;
616 goto fail;
617 }
618
8c7de283
KW
619 ret = validate_table_offset(bs, s->refcount_table_offset,
620 s->refcount_table_size, sizeof(uint64_t));
621 if (ret < 0) {
622 error_setg(errp, "Invalid reference count table offset");
623 goto fail;
624 }
625
585f8587
FB
626 s->snapshots_offset = header.snapshots_offset;
627 s->nb_snapshots = header.nb_snapshots;
628
629 /* read the level 1 table */
630 s->l1_size = header.l1_size;
2cf7cfa1
KW
631
632 l1_vm_state_index = size_to_l1(s, header.size);
633 if (l1_vm_state_index > INT_MAX) {
3ef6c40a 634 error_setg(errp, "Image is too big");
2cf7cfa1
KW
635 ret = -EFBIG;
636 goto fail;
637 }
638 s->l1_vm_state_index = l1_vm_state_index;
639
585f8587
FB
640 /* the L1 table must contain at least enough entries to put
641 header.size bytes */
6d85a57e 642 if (s->l1_size < s->l1_vm_state_index) {
3ef6c40a 643 error_setg(errp, "L1 table is too small");
6d85a57e 644 ret = -EINVAL;
585f8587 645 goto fail;
6d85a57e 646 }
585f8587 647 s->l1_table_offset = header.l1_table_offset;
d191d12d 648 if (s->l1_size > 0) {
7267c094 649 s->l1_table = g_malloc0(
d191d12d 650 align_offset(s->l1_size * sizeof(uint64_t), 512));
6d85a57e
JS
651 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
652 s->l1_size * sizeof(uint64_t));
653 if (ret < 0) {
3ef6c40a 654 error_setg_errno(errp, -ret, "Could not read L1 table");
d191d12d 655 goto fail;
6d85a57e 656 }
d191d12d
SW
657 for(i = 0;i < s->l1_size; i++) {
658 be64_to_cpus(&s->l1_table[i]);
659 }
585f8587 660 }
29c1a730
KW
661
662 /* alloc L2 table/refcount block cache */
6af4e9ea
PB
663 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
664 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
29c1a730 665
7267c094 666 s->cluster_cache = g_malloc(s->cluster_size);
585f8587 667 /* one more sector for decompressed data alignment */
dea43a65 668 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
095a9c58 669 + 512);
585f8587 670 s->cluster_cache_offset = -1;
06d9260f 671 s->flags = flags;
3b46e624 672
6d85a57e
JS
673 ret = qcow2_refcount_init(bs);
674 if (ret != 0) {
3ef6c40a 675 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
585f8587 676 goto fail;
6d85a57e 677 }
585f8587 678
72cf2d4f 679 QLIST_INIT(&s->cluster_allocs);
0b919fae 680 QTAILQ_INIT(&s->discards);
f214978a 681
9b80ddf3 682 /* read qcow2 extensions */
3ef6c40a
HR
683 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
684 &local_err)) {
685 error_propagate(errp, local_err);
6d85a57e 686 ret = -EINVAL;
9b80ddf3 687 goto fail;
6d85a57e 688 }
9b80ddf3 689
585f8587
FB
690 /* read the backing file name */
691 if (header.backing_file_offset != 0) {
692 len = header.backing_file_size;
6d85a57e 693 if (len > 1023) {
585f8587 694 len = 1023;
6d85a57e
JS
695 }
696 ret = bdrv_pread(bs->file, header.backing_file_offset,
697 bs->backing_file, len);
698 if (ret < 0) {
3ef6c40a 699 error_setg_errno(errp, -ret, "Could not read backing file name");
585f8587 700 goto fail;
6d85a57e 701 }
585f8587
FB
702 bs->backing_file[len] = '\0';
703 }
42deb29f
KW
704
705 ret = qcow2_read_snapshots(bs);
706 if (ret < 0) {
3ef6c40a 707 error_setg_errno(errp, -ret, "Could not read snapshots");
585f8587 708 goto fail;
6d85a57e 709 }
585f8587 710
af7b708d 711 /* Clear unknown autoclear feature bits */
27eb6c09 712 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
af7b708d
SH
713 s->autoclear_features = 0;
714 ret = qcow2_update_header(bs);
715 if (ret < 0) {
3ef6c40a 716 error_setg_errno(errp, -ret, "Could not update qcow2 header");
af7b708d
SH
717 goto fail;
718 }
719 }
720
68d100e9
KW
721 /* Initialise locks */
722 qemu_co_mutex_init(&s->lock);
723
c61d0004 724 /* Repair image if dirty */
27eb6c09 725 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
058f8f16 726 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
c61d0004
SH
727 BdrvCheckResult result = {0};
728
acbe5982 729 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
c61d0004 730 if (ret < 0) {
3ef6c40a 731 error_setg_errno(errp, -ret, "Could not repair dirty image");
c61d0004
SH
732 goto fail;
733 }
734 }
735
74c4510a 736 /* Enable lazy_refcounts according to image and command line options */
87ea75d5 737 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
74c4510a 738 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 739 if (local_err) {
3ef6c40a 740 error_propagate(errp, local_err);
74c4510a
KW
741 ret = -EINVAL;
742 goto fail;
743 }
744
acdfb480 745 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
74c4510a
KW
746 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
747
67af674e
KW
748 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
749 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
750 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
751 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
752 flags & BDRV_O_UNMAP);
753 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
754 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
755 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
756 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
757
1fa5cc83
HR
758 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
759 if (!strcmp(opt_overlap_check, "none")) {
760 overlap_check_template = 0;
761 } else if (!strcmp(opt_overlap_check, "constant")) {
762 overlap_check_template = QCOW2_OL_CONSTANT;
763 } else if (!strcmp(opt_overlap_check, "cached")) {
764 overlap_check_template = QCOW2_OL_CACHED;
765 } else if (!strcmp(opt_overlap_check, "all")) {
766 overlap_check_template = QCOW2_OL_ALL;
767 } else {
768 error_setg(errp, "Unsupported value '%s' for qcow2 option "
769 "'overlap-check'. Allowed are either of the following: "
770 "none, constant, cached, all", opt_overlap_check);
771 qemu_opts_del(opts);
772 ret = -EINVAL;
773 goto fail;
774 }
775
776 s->overlap_check = 0;
777 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
778 /* overlap-check defines a template bitmask, but every flag may be
779 * overwritten through the associated boolean option */
780 s->overlap_check |=
781 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
782 overlap_check_template & (1 << i)) << i;
783 }
3e355390 784
74c4510a
KW
785 qemu_opts_del(opts);
786
787 if (s->use_lazy_refcounts && s->qcow_version < 3) {
3ef6c40a
HR
788 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
789 "qemu 1.1 compatibility level");
74c4510a
KW
790 ret = -EINVAL;
791 goto fail;
792 }
793
585f8587 794#ifdef DEBUG_ALLOC
6cbc3031
PH
795 {
796 BdrvCheckResult result = {0};
b35278f7 797 qcow2_check_refcounts(bs, &result, 0);
6cbc3031 798 }
585f8587 799#endif
6d85a57e 800 return ret;
585f8587
FB
801
802 fail:
6744cbab 803 g_free(s->unknown_header_fields);
75bab85c 804 cleanup_unknown_header_ext(bs);
ed6ccf0f
KW
805 qcow2_free_snapshots(bs);
806 qcow2_refcount_close(bs);
7267c094 807 g_free(s->l1_table);
cf93980e
HR
808 /* else pre-write overlap checks in cache_destroy may crash */
809 s->l1_table = NULL;
29c1a730
KW
810 if (s->l2_table_cache) {
811 qcow2_cache_destroy(bs, s->l2_table_cache);
812 }
c5a33ee9
PJ
813 if (s->refcount_block_cache) {
814 qcow2_cache_destroy(bs, s->refcount_block_cache);
815 }
7267c094 816 g_free(s->cluster_cache);
dea43a65 817 qemu_vfree(s->cluster_data);
6d85a57e 818 return ret;
585f8587
FB
819}
820
d34682cd
KW
821static int qcow2_refresh_limits(BlockDriverState *bs)
822{
823 BDRVQcowState *s = bs->opaque;
824
825 bs->bl.write_zeroes_alignment = s->cluster_sectors;
826
827 return 0;
828}
829
7c80ab3f 830static int qcow2_set_key(BlockDriverState *bs, const char *key)
585f8587
FB
831{
832 BDRVQcowState *s = bs->opaque;
833 uint8_t keybuf[16];
834 int len, i;
3b46e624 835
585f8587
FB
836 memset(keybuf, 0, 16);
837 len = strlen(key);
838 if (len > 16)
839 len = 16;
840 /* XXX: we could compress the chars to 7 bits to increase
841 entropy */
842 for(i = 0;i < len;i++) {
843 keybuf[i] = key[i];
844 }
845 s->crypt_method = s->crypt_method_header;
846
847 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
848 return -1;
849 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
850 return -1;
851#if 0
852 /* test */
853 {
854 uint8_t in[16];
855 uint8_t out[16];
856 uint8_t tmp[16];
857 for(i=0;i<16;i++)
858 in[i] = i;
859 AES_encrypt(in, tmp, &s->aes_encrypt_key);
860 AES_decrypt(tmp, out, &s->aes_decrypt_key);
861 for(i = 0; i < 16; i++)
862 printf(" %02x", tmp[i]);
863 printf("\n");
864 for(i = 0; i < 16; i++)
865 printf(" %02x", out[i]);
866 printf("\n");
867 }
868#endif
869 return 0;
870}
871
21d82ac9
JC
872/* We have nothing to do for QCOW2 reopen, stubs just return
873 * success */
874static int qcow2_reopen_prepare(BDRVReopenState *state,
875 BlockReopenQueue *queue, Error **errp)
876{
877 return 0;
878}
879
b6b8a333 880static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
f8a2e5e3 881 int64_t sector_num, int nb_sectors, int *pnum)
585f8587 882{
f8a2e5e3 883 BDRVQcowState *s = bs->opaque;
585f8587 884 uint64_t cluster_offset;
4bc74be9
PB
885 int index_in_cluster, ret;
886 int64_t status = 0;
585f8587 887
095a9c58 888 *pnum = nb_sectors;
f8a2e5e3 889 qemu_co_mutex_lock(&s->lock);
1c46efaa 890 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
f8a2e5e3 891 qemu_co_mutex_unlock(&s->lock);
1c46efaa 892 if (ret < 0) {
d663640c 893 return ret;
1c46efaa 894 }
095a9c58 895
4bc74be9
PB
896 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
897 !s->crypt_method) {
898 index_in_cluster = sector_num & (s->cluster_sectors - 1);
899 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
900 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
901 }
902 if (ret == QCOW2_CLUSTER_ZERO) {
903 status |= BDRV_BLOCK_ZERO;
904 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
905 status |= BDRV_BLOCK_DATA;
906 }
907 return status;
585f8587
FB
908}
909
a9465922 910/* handle reading after the end of the backing file */
bd28f835
KW
911int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
912 int64_t sector_num, int nb_sectors)
a9465922
FB
913{
914 int n1;
915 if ((sector_num + nb_sectors) <= bs->total_sectors)
916 return nb_sectors;
917 if (sector_num >= bs->total_sectors)
918 n1 = 0;
919 else
920 n1 = bs->total_sectors - sector_num;
bd28f835 921
3d9b4925 922 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
bd28f835 923
a9465922
FB
924 return n1;
925}
926
a968168c 927static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
3fc48d09 928 int remaining_sectors, QEMUIOVector *qiov)
585f8587 929{
585f8587 930 BDRVQcowState *s = bs->opaque;
a9465922 931 int index_in_cluster, n1;
68d100e9 932 int ret;
faf575c1 933 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 934 uint64_t cluster_offset = 0;
3fc48d09
FZ
935 uint64_t bytes_done = 0;
936 QEMUIOVector hd_qiov;
937 uint8_t *cluster_data = NULL;
585f8587 938
3fc48d09
FZ
939 qemu_iovec_init(&hd_qiov, qiov->niov);
940
941 qemu_co_mutex_lock(&s->lock);
942
943 while (remaining_sectors != 0) {
bd28f835 944
5ebaa27e 945 /* prepare next request */
3fc48d09 946 cur_nr_sectors = remaining_sectors;
5ebaa27e
FZ
947 if (s->crypt_method) {
948 cur_nr_sectors = MIN(cur_nr_sectors,
949 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
585f8587 950 }
5ebaa27e 951
3fc48d09 952 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
5ebaa27e 953 &cur_nr_sectors, &cluster_offset);
8af36488 954 if (ret < 0) {
3fc48d09 955 goto fail;
8af36488 956 }
bd28f835 957
3fc48d09 958 index_in_cluster = sector_num & (s->cluster_sectors - 1);
c87c0672 959
3fc48d09 960 qemu_iovec_reset(&hd_qiov);
1b093c48 961 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e
FZ
962 cur_nr_sectors * 512);
963
68d000a3
KW
964 switch (ret) {
965 case QCOW2_CLUSTER_UNALLOCATED:
5ebaa27e
FZ
966
967 if (bs->backing_hd) {
968 /* read from the base image */
3fc48d09
FZ
969 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
970 sector_num, cur_nr_sectors);
5ebaa27e
FZ
971 if (n1 > 0) {
972 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
973 qemu_co_mutex_unlock(&s->lock);
3fc48d09
FZ
974 ret = bdrv_co_readv(bs->backing_hd, sector_num,
975 n1, &hd_qiov);
5ebaa27e
FZ
976 qemu_co_mutex_lock(&s->lock);
977 if (ret < 0) {
3fc48d09 978 goto fail;
5ebaa27e
FZ
979 }
980 }
981 } else {
982 /* Note: in this case, no need to wait */
3d9b4925 983 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
5ebaa27e 984 }
68d000a3
KW
985 break;
986
6377af48 987 case QCOW2_CLUSTER_ZERO:
3d9b4925 988 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
6377af48
KW
989 break;
990
68d000a3 991 case QCOW2_CLUSTER_COMPRESSED:
5ebaa27e
FZ
992 /* add AIO support for compressed blocks ? */
993 ret = qcow2_decompress_cluster(bs, cluster_offset);
994 if (ret < 0) {
3fc48d09 995 goto fail;
bd28f835
KW
996 }
997
03396148 998 qemu_iovec_from_buf(&hd_qiov, 0,
5ebaa27e 999 s->cluster_cache + index_in_cluster * 512,
faf575c1 1000 512 * cur_nr_sectors);
68d000a3
KW
1001 break;
1002
1003 case QCOW2_CLUSTER_NORMAL:
5ebaa27e 1004 if ((cluster_offset & 511) != 0) {
3fc48d09
FZ
1005 ret = -EIO;
1006 goto fail;
5ebaa27e 1007 }
bd28f835 1008
5ebaa27e
FZ
1009 if (s->crypt_method) {
1010 /*
1011 * For encrypted images, read everything into a temporary
1012 * contiguous buffer on which the AES functions can work.
1013 */
3fc48d09
FZ
1014 if (!cluster_data) {
1015 cluster_data =
dea43a65 1016 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
5ebaa27e
FZ
1017 }
1018
1019 assert(cur_nr_sectors <=
1020 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
3fc48d09
FZ
1021 qemu_iovec_reset(&hd_qiov);
1022 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1023 512 * cur_nr_sectors);
1024 }
1025
1026 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1027 qemu_co_mutex_unlock(&s->lock);
1028 ret = bdrv_co_readv(bs->file,
1029 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1030 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1031 qemu_co_mutex_lock(&s->lock);
1032 if (ret < 0) {
3fc48d09 1033 goto fail;
5ebaa27e
FZ
1034 }
1035 if (s->crypt_method) {
3fc48d09
FZ
1036 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1037 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
03396148
MT
1038 qemu_iovec_from_buf(qiov, bytes_done,
1039 cluster_data, 512 * cur_nr_sectors);
5ebaa27e 1040 }
68d000a3
KW
1041 break;
1042
1043 default:
1044 g_assert_not_reached();
1045 ret = -EIO;
1046 goto fail;
faf575c1 1047 }
f141eafe 1048
3fc48d09
FZ
1049 remaining_sectors -= cur_nr_sectors;
1050 sector_num += cur_nr_sectors;
1051 bytes_done += cur_nr_sectors * 512;
5ebaa27e 1052 }
3fc48d09 1053 ret = 0;
faf575c1 1054
3fc48d09 1055fail:
68d100e9 1056 qemu_co_mutex_unlock(&s->lock);
42496d62 1057
3fc48d09 1058 qemu_iovec_destroy(&hd_qiov);
dea43a65 1059 qemu_vfree(cluster_data);
68d100e9
KW
1060
1061 return ret;
585f8587
FB
1062}
1063
a968168c 1064static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
3fc48d09
FZ
1065 int64_t sector_num,
1066 int remaining_sectors,
1067 QEMUIOVector *qiov)
585f8587 1068{
585f8587 1069 BDRVQcowState *s = bs->opaque;
585f8587 1070 int index_in_cluster;
68d100e9 1071 int ret;
faf575c1 1072 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 1073 uint64_t cluster_offset;
3fc48d09
FZ
1074 QEMUIOVector hd_qiov;
1075 uint64_t bytes_done = 0;
1076 uint8_t *cluster_data = NULL;
8d2497c3 1077 QCowL2Meta *l2meta = NULL;
c2271403 1078
3cce16f4
KW
1079 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1080 remaining_sectors);
1081
3fc48d09
FZ
1082 qemu_iovec_init(&hd_qiov, qiov->niov);
1083
1084 s->cluster_cache_offset = -1; /* disable compressed cache */
3b46e624 1085
3fc48d09
FZ
1086 qemu_co_mutex_lock(&s->lock);
1087
1088 while (remaining_sectors != 0) {
1089
f50f88b9 1090 l2meta = NULL;
cf5c1a23 1091
3cce16f4 1092 trace_qcow2_writev_start_part(qemu_coroutine_self());
3fc48d09 1093 index_in_cluster = sector_num & (s->cluster_sectors - 1);
16f0587e 1094 cur_nr_sectors = remaining_sectors;
5ebaa27e 1095 if (s->crypt_method &&
16f0587e
HT
1096 cur_nr_sectors >
1097 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1098 cur_nr_sectors =
1099 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
5ebaa27e 1100 }
095a9c58 1101
3fc48d09 1102 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
16f0587e 1103 &cur_nr_sectors, &cluster_offset, &l2meta);
5ebaa27e 1104 if (ret < 0) {
3fc48d09 1105 goto fail;
5ebaa27e 1106 }
148da7ea 1107
5ebaa27e 1108 assert((cluster_offset & 511) == 0);
148da7ea 1109
3fc48d09 1110 qemu_iovec_reset(&hd_qiov);
1b093c48 1111 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e 1112 cur_nr_sectors * 512);
6f5f060b 1113
5ebaa27e 1114 if (s->crypt_method) {
3fc48d09 1115 if (!cluster_data) {
dea43a65 1116 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
5ebaa27e
FZ
1117 s->cluster_size);
1118 }
6f5f060b 1119
3fc48d09 1120 assert(hd_qiov.size <=
5ebaa27e 1121 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
d5e6b161 1122 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
6f5f060b 1123
3fc48d09
FZ
1124 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1125 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
6f5f060b 1126
3fc48d09
FZ
1127 qemu_iovec_reset(&hd_qiov);
1128 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1129 cur_nr_sectors * 512);
1130 }
6f5f060b 1131
231bb267 1132 ret = qcow2_pre_write_overlap_check(bs, 0,
cf93980e
HR
1133 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1134 cur_nr_sectors * BDRV_SECTOR_SIZE);
1135 if (ret < 0) {
1136 goto fail;
1137 }
1138
5ebaa27e 1139 qemu_co_mutex_unlock(&s->lock);
67a7a0eb 1140 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
3cce16f4
KW
1141 trace_qcow2_writev_data(qemu_coroutine_self(),
1142 (cluster_offset >> 9) + index_in_cluster);
5ebaa27e
FZ
1143 ret = bdrv_co_writev(bs->file,
1144 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1145 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1146 qemu_co_mutex_lock(&s->lock);
1147 if (ret < 0) {
3fc48d09 1148 goto fail;
5ebaa27e 1149 }
f141eafe 1150
88c6588c
KW
1151 while (l2meta != NULL) {
1152 QCowL2Meta *next;
1153
f50f88b9
KW
1154 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1155 if (ret < 0) {
1156 goto fail;
1157 }
faf575c1 1158
4e95314e
KW
1159 /* Take the request off the list of running requests */
1160 if (l2meta->nb_clusters != 0) {
1161 QLIST_REMOVE(l2meta, next_in_flight);
1162 }
1163
4e95314e 1164 qemu_co_queue_restart_all(&l2meta->dependent_requests);
4e95314e 1165
88c6588c 1166 next = l2meta->next;
f50f88b9 1167 g_free(l2meta);
88c6588c 1168 l2meta = next;
f50f88b9 1169 }
0fa9131a 1170
3fc48d09
FZ
1171 remaining_sectors -= cur_nr_sectors;
1172 sector_num += cur_nr_sectors;
1173 bytes_done += cur_nr_sectors * 512;
3cce16f4 1174 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
5ebaa27e 1175 }
3fc48d09 1176 ret = 0;
faf575c1 1177
3fc48d09 1178fail:
4e95314e
KW
1179 qemu_co_mutex_unlock(&s->lock);
1180
88c6588c
KW
1181 while (l2meta != NULL) {
1182 QCowL2Meta *next;
1183
4e95314e
KW
1184 if (l2meta->nb_clusters != 0) {
1185 QLIST_REMOVE(l2meta, next_in_flight);
1186 }
1187 qemu_co_queue_restart_all(&l2meta->dependent_requests);
88c6588c
KW
1188
1189 next = l2meta->next;
cf5c1a23 1190 g_free(l2meta);
88c6588c 1191 l2meta = next;
cf5c1a23 1192 }
0fa9131a 1193
3fc48d09 1194 qemu_iovec_destroy(&hd_qiov);
dea43a65 1195 qemu_vfree(cluster_data);
3cce16f4 1196 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 1197
68d100e9 1198 return ret;
585f8587
FB
1199}
1200
7c80ab3f 1201static void qcow2_close(BlockDriverState *bs)
585f8587
FB
1202{
1203 BDRVQcowState *s = bs->opaque;
7267c094 1204 g_free(s->l1_table);
cf93980e
HR
1205 /* else pre-write overlap checks in cache_destroy may crash */
1206 s->l1_table = NULL;
29c1a730 1207
27eb6c09
KW
1208 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1209 qcow2_cache_flush(bs, s->l2_table_cache);
1210 qcow2_cache_flush(bs, s->refcount_block_cache);
29c1a730 1211
27eb6c09
KW
1212 qcow2_mark_clean(bs);
1213 }
c61d0004 1214
29c1a730
KW
1215 qcow2_cache_destroy(bs, s->l2_table_cache);
1216 qcow2_cache_destroy(bs, s->refcount_block_cache);
1217
6744cbab 1218 g_free(s->unknown_header_fields);
75bab85c 1219 cleanup_unknown_header_ext(bs);
6744cbab 1220
7267c094 1221 g_free(s->cluster_cache);
dea43a65 1222 qemu_vfree(s->cluster_data);
ed6ccf0f 1223 qcow2_refcount_close(bs);
28c1202b 1224 qcow2_free_snapshots(bs);
585f8587
FB
1225}
1226
5a8a30db 1227static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
06d9260f
AL
1228{
1229 BDRVQcowState *s = bs->opaque;
1230 int flags = s->flags;
1231 AES_KEY aes_encrypt_key;
1232 AES_KEY aes_decrypt_key;
1233 uint32_t crypt_method = 0;
acdfb480 1234 QDict *options;
5a8a30db
KW
1235 Error *local_err = NULL;
1236 int ret;
06d9260f
AL
1237
1238 /*
1239 * Backing files are read-only which makes all of their metadata immutable,
1240 * that means we don't have to worry about reopening them here.
1241 */
1242
1243 if (s->crypt_method) {
1244 crypt_method = s->crypt_method;
1245 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1246 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1247 }
1248
1249 qcow2_close(bs);
1250
5a8a30db
KW
1251 bdrv_invalidate_cache(bs->file, &local_err);
1252 if (local_err) {
1253 error_propagate(errp, local_err);
1254 return;
1255 }
3456a8d1 1256
06d9260f 1257 memset(s, 0, sizeof(BDRVQcowState));
d475e5ac 1258 options = qdict_clone_shallow(bs->options);
5a8a30db
KW
1259
1260 ret = qcow2_open(bs, options, flags, &local_err);
1261 if (local_err) {
1262 error_setg(errp, "Could not reopen qcow2 layer: %s",
1263 error_get_pretty(local_err));
1264 error_free(local_err);
1265 return;
1266 } else if (ret < 0) {
1267 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1268 return;
1269 }
acdfb480
KW
1270
1271 QDECREF(options);
06d9260f
AL
1272
1273 if (crypt_method) {
1274 s->crypt_method = crypt_method;
1275 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1276 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1277 }
1278}
1279
e24e49e6
KW
1280static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1281 size_t len, size_t buflen)
1282{
1283 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1284 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1285
1286 if (buflen < ext_len) {
1287 return -ENOSPC;
1288 }
1289
1290 *ext_backing_fmt = (QCowExtension) {
1291 .magic = cpu_to_be32(magic),
1292 .len = cpu_to_be32(len),
1293 };
1294 memcpy(buf + sizeof(QCowExtension), s, len);
1295
1296 return ext_len;
1297}
1298
756e6736 1299/*
e24e49e6
KW
1300 * Updates the qcow2 header, including the variable length parts of it, i.e.
1301 * the backing file name and all extensions. qcow2 was not designed to allow
1302 * such changes, so if we run out of space (we can only use the first cluster)
1303 * this function may fail.
756e6736
KW
1304 *
1305 * Returns 0 on success, -errno in error cases.
1306 */
e24e49e6 1307int qcow2_update_header(BlockDriverState *bs)
756e6736 1308{
756e6736 1309 BDRVQcowState *s = bs->opaque;
e24e49e6
KW
1310 QCowHeader *header;
1311 char *buf;
1312 size_t buflen = s->cluster_size;
756e6736 1313 int ret;
e24e49e6
KW
1314 uint64_t total_size;
1315 uint32_t refcount_table_clusters;
6744cbab 1316 size_t header_length;
75bab85c 1317 Qcow2UnknownHeaderExtension *uext;
756e6736 1318
e24e49e6 1319 buf = qemu_blockalign(bs, buflen);
756e6736 1320
e24e49e6
KW
1321 /* Header structure */
1322 header = (QCowHeader*) buf;
756e6736 1323
e24e49e6
KW
1324 if (buflen < sizeof(*header)) {
1325 ret = -ENOSPC;
1326 goto fail;
756e6736
KW
1327 }
1328
6744cbab 1329 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
1330 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1331 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1332
1333 *header = (QCowHeader) {
6744cbab 1334 /* Version 2 fields */
e24e49e6 1335 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 1336 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
1337 .backing_file_offset = 0,
1338 .backing_file_size = 0,
1339 .cluster_bits = cpu_to_be32(s->cluster_bits),
1340 .size = cpu_to_be64(total_size),
1341 .crypt_method = cpu_to_be32(s->crypt_method_header),
1342 .l1_size = cpu_to_be32(s->l1_size),
1343 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1344 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1345 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1346 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1347 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
1348
1349 /* Version 3 fields */
1350 .incompatible_features = cpu_to_be64(s->incompatible_features),
1351 .compatible_features = cpu_to_be64(s->compatible_features),
1352 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 1353 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 1354 .header_length = cpu_to_be32(header_length),
e24e49e6 1355 };
756e6736 1356
6744cbab
KW
1357 /* For older versions, write a shorter header */
1358 switch (s->qcow_version) {
1359 case 2:
1360 ret = offsetof(QCowHeader, incompatible_features);
1361 break;
1362 case 3:
1363 ret = sizeof(*header);
1364 break;
1365 default:
b6c14762
JM
1366 ret = -EINVAL;
1367 goto fail;
6744cbab
KW
1368 }
1369
1370 buf += ret;
1371 buflen -= ret;
1372 memset(buf, 0, buflen);
1373
1374 /* Preserve any unknown field in the header */
1375 if (s->unknown_header_fields_size) {
1376 if (buflen < s->unknown_header_fields_size) {
1377 ret = -ENOSPC;
1378 goto fail;
1379 }
1380
1381 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1382 buf += s->unknown_header_fields_size;
1383 buflen -= s->unknown_header_fields_size;
1384 }
756e6736 1385
e24e49e6
KW
1386 /* Backing file format header extension */
1387 if (*bs->backing_format) {
1388 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1389 bs->backing_format, strlen(bs->backing_format),
1390 buflen);
1391 if (ret < 0) {
1392 goto fail;
756e6736
KW
1393 }
1394
e24e49e6
KW
1395 buf += ret;
1396 buflen -= ret;
756e6736
KW
1397 }
1398
cfcc4c62
KW
1399 /* Feature table */
1400 Qcow2Feature features[] = {
c61d0004
SH
1401 {
1402 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1403 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1404 .name = "dirty bit",
1405 },
69c98726
HR
1406 {
1407 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1408 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1409 .name = "corrupt bit",
1410 },
bfe8043e
SH
1411 {
1412 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1413 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1414 .name = "lazy refcounts",
1415 },
cfcc4c62
KW
1416 };
1417
1418 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1419 features, sizeof(features), buflen);
1420 if (ret < 0) {
1421 goto fail;
1422 }
1423 buf += ret;
1424 buflen -= ret;
1425
75bab85c
KW
1426 /* Keep unknown header extensions */
1427 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1428 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1429 if (ret < 0) {
1430 goto fail;
1431 }
1432
1433 buf += ret;
1434 buflen -= ret;
1435 }
1436
e24e49e6
KW
1437 /* End of header extensions */
1438 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
1439 if (ret < 0) {
1440 goto fail;
1441 }
1442
e24e49e6
KW
1443 buf += ret;
1444 buflen -= ret;
756e6736 1445
e24e49e6
KW
1446 /* Backing file name */
1447 if (*bs->backing_file) {
1448 size_t backing_file_len = strlen(bs->backing_file);
1449
1450 if (buflen < backing_file_len) {
1451 ret = -ENOSPC;
1452 goto fail;
1453 }
1454
00ea1881 1455 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e24e49e6
KW
1456 strncpy(buf, bs->backing_file, buflen);
1457
1458 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1459 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
1460 }
1461
e24e49e6
KW
1462 /* Write the new header */
1463 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
1464 if (ret < 0) {
1465 goto fail;
1466 }
1467
1468 ret = 0;
1469fail:
e24e49e6 1470 qemu_vfree(header);
756e6736
KW
1471 return ret;
1472}
1473
1474static int qcow2_change_backing_file(BlockDriverState *bs,
1475 const char *backing_file, const char *backing_fmt)
1476{
e24e49e6
KW
1477 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1478 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1479
1480 return qcow2_update_header(bs);
756e6736
KW
1481}
1482
a35e1c17
KW
1483static int preallocate(BlockDriverState *bs)
1484{
a35e1c17
KW
1485 uint64_t nb_sectors;
1486 uint64_t offset;
060bee89 1487 uint64_t host_offset = 0;
a35e1c17 1488 int num;
148da7ea 1489 int ret;
f50f88b9 1490 QCowL2Meta *meta;
a35e1c17 1491
7c2bbf4a 1492 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
a35e1c17
KW
1493 offset = 0;
1494
1495 while (nb_sectors) {
7c2bbf4a 1496 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
16f0587e 1497 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
060bee89 1498 &host_offset, &meta);
148da7ea 1499 if (ret < 0) {
19dbcbf7 1500 return ret;
a35e1c17
KW
1501 }
1502
f50f88b9 1503 if (meta != NULL) {
7c2bbf4a
HT
1504 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1505 if (ret < 0) {
1506 qcow2_free_any_clusters(bs, meta->alloc_offset,
1507 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1508 return ret;
1509 }
1510
1511 /* There are no dependent requests, but we need to remove our
1512 * request from the list of in-flight requests */
4e95314e 1513 QLIST_REMOVE(meta, next_in_flight);
f50f88b9 1514 }
f214978a 1515
a35e1c17
KW
1516 /* TODO Preallocate data if requested */
1517
1518 nb_sectors -= num;
7c2bbf4a 1519 offset += num << BDRV_SECTOR_BITS;
a35e1c17
KW
1520 }
1521
1522 /*
1523 * It is expected that the image file is large enough to actually contain
1524 * all of the allocated clusters (otherwise we get failing reads after
1525 * EOF). Extend the image to the last allocated sector.
1526 */
060bee89 1527 if (host_offset != 0) {
7c2bbf4a
HT
1528 uint8_t buf[BDRV_SECTOR_SIZE];
1529 memset(buf, 0, BDRV_SECTOR_SIZE);
1530 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1531 buf, 1);
19dbcbf7
KW
1532 if (ret < 0) {
1533 return ret;
1534 }
a35e1c17
KW
1535 }
1536
1537 return 0;
1538}
1539
7c80ab3f
JS
1540static int qcow2_create2(const char *filename, int64_t total_size,
1541 const char *backing_file, const char *backing_format,
1542 int flags, size_t cluster_size, int prealloc,
3ef6c40a
HR
1543 QEMUOptionParameter *options, int version,
1544 Error **errp)
a9420734 1545{
9b2260cb 1546 /* Calculate cluster_bits */
a9420734
KW
1547 int cluster_bits;
1548 cluster_bits = ffs(cluster_size) - 1;
1549 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1550 (1 << cluster_bits) != cluster_size)
1551 {
3ef6c40a
HR
1552 error_setg(errp, "Cluster size must be a power of two between %d and "
1553 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
a9420734
KW
1554 return -EINVAL;
1555 }
1556
1557 /*
1558 * Open the image file and write a minimal qcow2 header.
1559 *
1560 * We keep things simple and start with a zero-sized image. We also
1561 * do without refcount blocks or a L1 table for now. We'll fix the
1562 * inconsistency later.
1563 *
1564 * We do need a refcount table because growing the refcount table means
1565 * allocating two new refcount blocks - the seconds of which would be at
1566 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1567 * size for any qcow2 image.
1568 */
1569 BlockDriverState* bs;
f8413b3c 1570 QCowHeader *header;
a9420734 1571 uint8_t* refcount_table;
3ef6c40a 1572 Error *local_err = NULL;
a9420734
KW
1573 int ret;
1574
3ef6c40a 1575 ret = bdrv_create_file(filename, options, &local_err);
a9420734 1576 if (ret < 0) {
3ef6c40a 1577 error_propagate(errp, local_err);
a9420734
KW
1578 return ret;
1579 }
1580
2e40134b
HR
1581 bs = NULL;
1582 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1583 NULL, &local_err);
a9420734 1584 if (ret < 0) {
3ef6c40a 1585 error_propagate(errp, local_err);
a9420734
KW
1586 return ret;
1587 }
1588
1589 /* Write the header */
f8413b3c
KW
1590 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1591 header = g_malloc0(cluster_size);
1592 *header = (QCowHeader) {
1593 .magic = cpu_to_be32(QCOW_MAGIC),
1594 .version = cpu_to_be32(version),
1595 .cluster_bits = cpu_to_be32(cluster_bits),
1596 .size = cpu_to_be64(0),
1597 .l1_table_offset = cpu_to_be64(0),
1598 .l1_size = cpu_to_be32(0),
1599 .refcount_table_offset = cpu_to_be64(cluster_size),
1600 .refcount_table_clusters = cpu_to_be32(1),
1601 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1602 .header_length = cpu_to_be32(sizeof(*header)),
1603 };
a9420734
KW
1604
1605 if (flags & BLOCK_FLAG_ENCRYPT) {
f8413b3c 1606 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
a9420734 1607 } else {
f8413b3c 1608 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734
KW
1609 }
1610
bfe8043e 1611 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
f8413b3c 1612 header->compatible_features |=
bfe8043e
SH
1613 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1614 }
1615
f8413b3c
KW
1616 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1617 g_free(header);
a9420734 1618 if (ret < 0) {
3ef6c40a 1619 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
1620 goto out;
1621 }
1622
1623 /* Write an empty refcount table */
7267c094 1624 refcount_table = g_malloc0(cluster_size);
a9420734 1625 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
7267c094 1626 g_free(refcount_table);
a9420734
KW
1627
1628 if (ret < 0) {
3ef6c40a 1629 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
1630 goto out;
1631 }
1632
f67503e5
HR
1633 bdrv_unref(bs);
1634 bs = NULL;
a9420734
KW
1635
1636 /*
1637 * And now open the image and make it consistent first (i.e. increase the
1638 * refcount of the cluster that is occupied by the header and the refcount
1639 * table)
1640 */
1641 BlockDriver* drv = bdrv_find_format("qcow2");
1642 assert(drv != NULL);
ddf5636d 1643 ret = bdrv_open(&bs, filename, NULL, NULL,
3ef6c40a 1644 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
a9420734 1645 if (ret < 0) {
3ef6c40a 1646 error_propagate(errp, local_err);
a9420734
KW
1647 goto out;
1648 }
1649
1650 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1651 if (ret < 0) {
3ef6c40a
HR
1652 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1653 "header and refcount table");
a9420734
KW
1654 goto out;
1655
1656 } else if (ret != 0) {
1657 error_report("Huh, first cluster in empty image is already in use?");
1658 abort();
1659 }
1660
1661 /* Okay, now that we have a valid image, let's give it the right size */
1662 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1663 if (ret < 0) {
3ef6c40a 1664 error_setg_errno(errp, -ret, "Could not resize image");
a9420734
KW
1665 goto out;
1666 }
1667
1668 /* Want a backing file? There you go.*/
1669 if (backing_file) {
1670 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1671 if (ret < 0) {
3ef6c40a
HR
1672 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1673 "with format '%s'", backing_file, backing_format);
a9420734
KW
1674 goto out;
1675 }
1676 }
1677
1678 /* And if we're supposed to preallocate metadata, do that now */
1679 if (prealloc) {
15552c4a
ZYW
1680 BDRVQcowState *s = bs->opaque;
1681 qemu_co_mutex_lock(&s->lock);
a9420734 1682 ret = preallocate(bs);
15552c4a 1683 qemu_co_mutex_unlock(&s->lock);
a9420734 1684 if (ret < 0) {
3ef6c40a 1685 error_setg_errno(errp, -ret, "Could not preallocate metadata");
a9420734
KW
1686 goto out;
1687 }
1688 }
1689
f67503e5
HR
1690 bdrv_unref(bs);
1691 bs = NULL;
ba2ab2f2
HR
1692
1693 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
ddf5636d 1694 ret = bdrv_open(&bs, filename, NULL, NULL,
c9fbb99d
KW
1695 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1696 drv, &local_err);
84d18f06 1697 if (local_err) {
ba2ab2f2
HR
1698 error_propagate(errp, local_err);
1699 goto out;
1700 }
1701
a9420734
KW
1702 ret = 0;
1703out:
f67503e5
HR
1704 if (bs) {
1705 bdrv_unref(bs);
1706 }
a9420734
KW
1707 return ret;
1708}
de5f3f40 1709
d5124c00
HR
1710static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1711 Error **errp)
de5f3f40
KW
1712{
1713 const char *backing_file = NULL;
1714 const char *backing_fmt = NULL;
1715 uint64_t sectors = 0;
1716 int flags = 0;
99cce9fa 1717 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
de5f3f40 1718 int prealloc = 0;
8ad1898c 1719 int version = 3;
3ef6c40a
HR
1720 Error *local_err = NULL;
1721 int ret;
de5f3f40
KW
1722
1723 /* Read out options */
1724 while (options && options->name) {
1725 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1726 sectors = options->value.n / 512;
1727 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1728 backing_file = options->value.s;
1729 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1730 backing_fmt = options->value.s;
1731 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1732 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1733 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1734 if (options->value.n) {
1735 cluster_size = options->value.n;
1736 }
1737 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1738 if (!options->value.s || !strcmp(options->value.s, "off")) {
1739 prealloc = 0;
1740 } else if (!strcmp(options->value.s, "metadata")) {
1741 prealloc = 1;
1742 } else {
3ef6c40a
HR
1743 error_setg(errp, "Invalid preallocation mode: '%s'",
1744 options->value.s);
de5f3f40
KW
1745 return -EINVAL;
1746 }
6744cbab 1747 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
9117b477
KW
1748 if (!options->value.s) {
1749 /* keep the default */
1750 } else if (!strcmp(options->value.s, "0.10")) {
6744cbab
KW
1751 version = 2;
1752 } else if (!strcmp(options->value.s, "1.1")) {
1753 version = 3;
1754 } else {
3ef6c40a
HR
1755 error_setg(errp, "Invalid compatibility level: '%s'",
1756 options->value.s);
6744cbab
KW
1757 return -EINVAL;
1758 }
bfe8043e
SH
1759 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1760 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
de5f3f40
KW
1761 }
1762 options++;
1763 }
1764
1765 if (backing_file && prealloc) {
3ef6c40a
HR
1766 error_setg(errp, "Backing file and preallocation cannot be used at "
1767 "the same time");
de5f3f40
KW
1768 return -EINVAL;
1769 }
1770
bfe8043e 1771 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
3ef6c40a
HR
1772 error_setg(errp, "Lazy refcounts only supported with compatibility "
1773 "level 1.1 and above (use compat=1.1 or greater)");
bfe8043e
SH
1774 return -EINVAL;
1775 }
1776
3ef6c40a
HR
1777 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1778 cluster_size, prealloc, options, version, &local_err);
84d18f06 1779 if (local_err) {
3ef6c40a
HR
1780 error_propagate(errp, local_err);
1781 }
1782 return ret;
de5f3f40
KW
1783}
1784
621f0589 1785static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
aa7bfbff 1786 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
621f0589
KW
1787{
1788 int ret;
1789 BDRVQcowState *s = bs->opaque;
1790
1791 /* Emulate misaligned zero writes */
1792 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1793 return -ENOTSUP;
1794 }
1795
1796 /* Whatever is left can use real zero clusters */
1797 qemu_co_mutex_lock(&s->lock);
1798 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1799 nb_sectors);
1800 qemu_co_mutex_unlock(&s->lock);
1801
1802 return ret;
1803}
1804
6db39ae2
PB
1805static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1806 int64_t sector_num, int nb_sectors)
5ea929e3 1807{
6db39ae2
PB
1808 int ret;
1809 BDRVQcowState *s = bs->opaque;
1810
1811 qemu_co_mutex_lock(&s->lock);
1812 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
670df5e3 1813 nb_sectors, QCOW2_DISCARD_REQUEST);
6db39ae2
PB
1814 qemu_co_mutex_unlock(&s->lock);
1815 return ret;
5ea929e3
KW
1816}
1817
419b19d9
SH
1818static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1819{
1820 BDRVQcowState *s = bs->opaque;
2cf7cfa1
KW
1821 int64_t new_l1_size;
1822 int ret;
419b19d9
SH
1823
1824 if (offset & 511) {
259b2173 1825 error_report("The new size must be a multiple of 512");
419b19d9
SH
1826 return -EINVAL;
1827 }
1828
1829 /* cannot proceed if image has snapshots */
1830 if (s->nb_snapshots) {
259b2173 1831 error_report("Can't resize an image which has snapshots");
419b19d9
SH
1832 return -ENOTSUP;
1833 }
1834
1835 /* shrinking is currently not supported */
1836 if (offset < bs->total_sectors * 512) {
259b2173 1837 error_report("qcow2 doesn't support shrinking images yet");
419b19d9
SH
1838 return -ENOTSUP;
1839 }
1840
1841 new_l1_size = size_to_l1(s, offset);
72893756 1842 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
419b19d9
SH
1843 if (ret < 0) {
1844 return ret;
1845 }
1846
1847 /* write updated header.size */
1848 offset = cpu_to_be64(offset);
8b3b7206
KW
1849 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1850 &offset, sizeof(uint64_t));
419b19d9
SH
1851 if (ret < 0) {
1852 return ret;
1853 }
1854
1855 s->l1_vm_state_index = new_l1_size;
1856 return 0;
1857}
1858
20d97356
BS
1859/* XXX: put compressed sectors first, then all the cluster aligned
1860 tables to avoid losing bytes in alignment */
7c80ab3f
JS
1861static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1862 const uint8_t *buf, int nb_sectors)
20d97356
BS
1863{
1864 BDRVQcowState *s = bs->opaque;
1865 z_stream strm;
1866 int ret, out_len;
1867 uint8_t *out_buf;
1868 uint64_t cluster_offset;
1869
1870 if (nb_sectors == 0) {
1871 /* align end of file to a sector boundary to ease reading with
1872 sector based I/Os */
66f82cee 1873 cluster_offset = bdrv_getlength(bs->file);
20d97356 1874 cluster_offset = (cluster_offset + 511) & ~511;
66f82cee 1875 bdrv_truncate(bs->file, cluster_offset);
20d97356
BS
1876 return 0;
1877 }
1878
f4d38bef
SH
1879 if (nb_sectors != s->cluster_sectors) {
1880 ret = -EINVAL;
1881
1882 /* Zero-pad last write if image size is not cluster aligned */
1883 if (sector_num + nb_sectors == bs->total_sectors &&
1884 nb_sectors < s->cluster_sectors) {
1885 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1886 memset(pad_buf, 0, s->cluster_size);
1887 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1888 ret = qcow2_write_compressed(bs, sector_num,
1889 pad_buf, s->cluster_sectors);
1890 qemu_vfree(pad_buf);
1891 }
1892 return ret;
1893 }
20d97356 1894
7267c094 1895 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
20d97356
BS
1896
1897 /* best compression, small window, no zlib header */
1898 memset(&strm, 0, sizeof(strm));
1899 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1900 Z_DEFLATED, -12,
1901 9, Z_DEFAULT_STRATEGY);
1902 if (ret != 0) {
8f1efd00
KW
1903 ret = -EINVAL;
1904 goto fail;
20d97356
BS
1905 }
1906
1907 strm.avail_in = s->cluster_size;
1908 strm.next_in = (uint8_t *)buf;
1909 strm.avail_out = s->cluster_size;
1910 strm.next_out = out_buf;
1911
1912 ret = deflate(&strm, Z_FINISH);
1913 if (ret != Z_STREAM_END && ret != Z_OK) {
20d97356 1914 deflateEnd(&strm);
8f1efd00
KW
1915 ret = -EINVAL;
1916 goto fail;
20d97356
BS
1917 }
1918 out_len = strm.next_out - out_buf;
1919
1920 deflateEnd(&strm);
1921
1922 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1923 /* could not compress: write normal cluster */
8f1efd00
KW
1924 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1925 if (ret < 0) {
1926 goto fail;
1927 }
20d97356
BS
1928 } else {
1929 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1930 sector_num << 9, out_len);
8f1efd00
KW
1931 if (!cluster_offset) {
1932 ret = -EIO;
1933 goto fail;
1934 }
20d97356 1935 cluster_offset &= s->cluster_offset_mask;
cf93980e 1936
231bb267 1937 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
cf93980e
HR
1938 if (ret < 0) {
1939 goto fail;
1940 }
1941
66f82cee 1942 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
8f1efd00
KW
1943 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1944 if (ret < 0) {
1945 goto fail;
20d97356
BS
1946 }
1947 }
1948
8f1efd00
KW
1949 ret = 0;
1950fail:
7267c094 1951 g_free(out_buf);
8f1efd00 1952 return ret;
20d97356
BS
1953}
1954
a968168c 1955static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 1956{
29c1a730
KW
1957 BDRVQcowState *s = bs->opaque;
1958 int ret;
1959
8b94ff85 1960 qemu_co_mutex_lock(&s->lock);
29c1a730
KW
1961 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1962 if (ret < 0) {
c95de7e2 1963 qemu_co_mutex_unlock(&s->lock);
8b94ff85 1964 return ret;
29c1a730
KW
1965 }
1966
bfe8043e
SH
1967 if (qcow2_need_accurate_refcounts(s)) {
1968 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1969 if (ret < 0) {
1970 qemu_co_mutex_unlock(&s->lock);
1971 return ret;
1972 }
29c1a730 1973 }
8b94ff85 1974 qemu_co_mutex_unlock(&s->lock);
29c1a730 1975
eb489bb1
KW
1976 return 0;
1977}
1978
7c80ab3f 1979static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356
BS
1980{
1981 BDRVQcowState *s = bs->opaque;
95de6d70
PB
1982 bdi->unallocated_blocks_are_zero = true;
1983 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
20d97356 1984 bdi->cluster_size = s->cluster_size;
7c80ab3f 1985 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
1986 return 0;
1987}
1988
37764dfb
HR
1989static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
1990{
1991 BDRVQcowState *s = bs->opaque;
1992 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
1993
1994 *spec_info = (ImageInfoSpecific){
1995 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
1996 {
1997 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
1998 },
1999 };
2000 if (s->qcow_version == 2) {
2001 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2002 .compat = g_strdup("0.10"),
2003 };
2004 } else if (s->qcow_version == 3) {
2005 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2006 .compat = g_strdup("1.1"),
2007 .lazy_refcounts = s->compatible_features &
2008 QCOW2_COMPAT_LAZY_REFCOUNTS,
2009 .has_lazy_refcounts = true,
2010 };
2011 }
2012
2013 return spec_info;
2014}
2015
20d97356
BS
2016#if 0
2017static void dump_refcounts(BlockDriverState *bs)
2018{
2019 BDRVQcowState *s = bs->opaque;
2020 int64_t nb_clusters, k, k1, size;
2021 int refcount;
2022
66f82cee 2023 size = bdrv_getlength(bs->file);
20d97356
BS
2024 nb_clusters = size_to_clusters(s, size);
2025 for(k = 0; k < nb_clusters;) {
2026 k1 = k;
2027 refcount = get_refcount(bs, k);
2028 k++;
2029 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2030 k++;
0bfcd599
BS
2031 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2032 k - k1);
20d97356
BS
2033 }
2034}
2035#endif
2036
cf8074b3
KW
2037static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2038 int64_t pos)
20d97356
BS
2039{
2040 BDRVQcowState *s = bs->opaque;
eedff66f 2041 int64_t total_sectors = bs->total_sectors;
20d97356 2042 int growable = bs->growable;
6e13610a 2043 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2044 int ret;
2045
66f82cee 2046 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
20d97356 2047 bs->growable = 1;
6e13610a 2048 bs->zero_beyond_eof = false;
8d3b1a2d 2049 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
20d97356 2050 bs->growable = growable;
6e13610a 2051 bs->zero_beyond_eof = zero_beyond_eof;
20d97356 2052
eedff66f
HR
2053 /* bdrv_co_do_writev will have increased the total_sectors value to include
2054 * the VM state - the VM state is however not an actual part of the block
2055 * device, therefore, we need to restore the old value. */
2056 bs->total_sectors = total_sectors;
2057
20d97356
BS
2058 return ret;
2059}
2060
7c80ab3f
JS
2061static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2062 int64_t pos, int size)
20d97356
BS
2063{
2064 BDRVQcowState *s = bs->opaque;
2065 int growable = bs->growable;
0d51b4de 2066 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2067 int ret;
2068
66f82cee 2069 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
20d97356 2070 bs->growable = 1;
0d51b4de 2071 bs->zero_beyond_eof = false;
7c80ab3f 2072 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
20d97356 2073 bs->growable = growable;
0d51b4de 2074 bs->zero_beyond_eof = zero_beyond_eof;
20d97356
BS
2075
2076 return ret;
2077}
2078
9296b3ed
HR
2079/*
2080 * Downgrades an image's version. To achieve this, any incompatible features
2081 * have to be removed.
2082 */
2083static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2084{
2085 BDRVQcowState *s = bs->opaque;
2086 int current_version = s->qcow_version;
2087 int ret;
2088
2089 if (target_version == current_version) {
2090 return 0;
2091 } else if (target_version > current_version) {
2092 return -EINVAL;
2093 } else if (target_version != 2) {
2094 return -EINVAL;
2095 }
2096
2097 if (s->refcount_order != 4) {
2098 /* we would have to convert the image to a refcount_order == 4 image
2099 * here; however, since qemu (at the time of writing this) does not
2100 * support anything different than 4 anyway, there is no point in doing
2101 * so right now; however, we should error out (if qemu supports this in
2102 * the future and this code has not been adapted) */
9e3f0892 2103 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
9296b3ed
HR
2104 "currently not supported.");
2105 return -ENOTSUP;
2106 }
2107
2108 /* clear incompatible features */
2109 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2110 ret = qcow2_mark_clean(bs);
2111 if (ret < 0) {
2112 return ret;
2113 }
2114 }
2115
2116 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2117 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2118 * best thing to do anyway */
2119
2120 if (s->incompatible_features) {
2121 return -ENOTSUP;
2122 }
2123
2124 /* since we can ignore compatible features, we can set them to 0 as well */
2125 s->compatible_features = 0;
2126 /* if lazy refcounts have been used, they have already been fixed through
2127 * clearing the dirty flag */
2128
2129 /* clearing autoclear features is trivial */
2130 s->autoclear_features = 0;
2131
2132 ret = qcow2_expand_zero_clusters(bs);
2133 if (ret < 0) {
2134 return ret;
2135 }
2136
2137 s->qcow_version = target_version;
2138 ret = qcow2_update_header(bs);
2139 if (ret < 0) {
2140 s->qcow_version = current_version;
2141 return ret;
2142 }
2143 return 0;
2144}
2145
2146static int qcow2_amend_options(BlockDriverState *bs,
2147 QEMUOptionParameter *options)
2148{
2149 BDRVQcowState *s = bs->opaque;
2150 int old_version = s->qcow_version, new_version = old_version;
2151 uint64_t new_size = 0;
2152 const char *backing_file = NULL, *backing_format = NULL;
2153 bool lazy_refcounts = s->use_lazy_refcounts;
2154 int ret;
2155 int i;
2156
2157 for (i = 0; options[i].name; i++)
2158 {
2159 if (!options[i].assigned) {
2160 /* only change explicitly defined options */
2161 continue;
2162 }
2163
2164 if (!strcmp(options[i].name, "compat")) {
2165 if (!options[i].value.s) {
2166 /* preserve default */
2167 } else if (!strcmp(options[i].value.s, "0.10")) {
2168 new_version = 2;
2169 } else if (!strcmp(options[i].value.s, "1.1")) {
2170 new_version = 3;
2171 } else {
2172 fprintf(stderr, "Unknown compatibility level %s.\n",
2173 options[i].value.s);
2174 return -EINVAL;
2175 }
2176 } else if (!strcmp(options[i].name, "preallocation")) {
2177 fprintf(stderr, "Cannot change preallocation mode.\n");
2178 return -ENOTSUP;
2179 } else if (!strcmp(options[i].name, "size")) {
2180 new_size = options[i].value.n;
2181 } else if (!strcmp(options[i].name, "backing_file")) {
2182 backing_file = options[i].value.s;
2183 } else if (!strcmp(options[i].name, "backing_fmt")) {
2184 backing_format = options[i].value.s;
2185 } else if (!strcmp(options[i].name, "encryption")) {
2186 if ((options[i].value.n != !!s->crypt_method)) {
2187 fprintf(stderr, "Changing the encryption flag is not "
2188 "supported.\n");
2189 return -ENOTSUP;
2190 }
2191 } else if (!strcmp(options[i].name, "cluster_size")) {
2192 if (options[i].value.n != s->cluster_size) {
2193 fprintf(stderr, "Changing the cluster size is not "
2194 "supported.\n");
2195 return -ENOTSUP;
2196 }
2197 } else if (!strcmp(options[i].name, "lazy_refcounts")) {
2198 lazy_refcounts = options[i].value.n;
2199 } else {
2200 /* if this assertion fails, this probably means a new option was
2201 * added without having it covered here */
2202 assert(false);
2203 }
2204 }
2205
2206 if (new_version != old_version) {
2207 if (new_version > old_version) {
2208 /* Upgrade */
2209 s->qcow_version = new_version;
2210 ret = qcow2_update_header(bs);
2211 if (ret < 0) {
2212 s->qcow_version = old_version;
2213 return ret;
2214 }
2215 } else {
2216 ret = qcow2_downgrade(bs, new_version);
2217 if (ret < 0) {
2218 return ret;
2219 }
2220 }
2221 }
2222
2223 if (backing_file || backing_format) {
2224 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2225 backing_format ?: bs->backing_format);
2226 if (ret < 0) {
2227 return ret;
2228 }
2229 }
2230
2231 if (s->use_lazy_refcounts != lazy_refcounts) {
2232 if (lazy_refcounts) {
2233 if (s->qcow_version < 3) {
2234 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2235 "level 1.1 and above (use compat=1.1 or greater)\n");
2236 return -EINVAL;
2237 }
2238 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2239 ret = qcow2_update_header(bs);
2240 if (ret < 0) {
2241 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2242 return ret;
2243 }
2244 s->use_lazy_refcounts = true;
2245 } else {
2246 /* make image clean first */
2247 ret = qcow2_mark_clean(bs);
2248 if (ret < 0) {
2249 return ret;
2250 }
2251 /* now disallow lazy refcounts */
2252 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2253 ret = qcow2_update_header(bs);
2254 if (ret < 0) {
2255 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2256 return ret;
2257 }
2258 s->use_lazy_refcounts = false;
2259 }
2260 }
2261
2262 if (new_size) {
2263 ret = bdrv_truncate(bs, new_size);
2264 if (ret < 0) {
2265 return ret;
2266 }
2267 }
2268
2269 return 0;
2270}
2271
7c80ab3f 2272static QEMUOptionParameter qcow2_create_options[] = {
20d97356
BS
2273 {
2274 .name = BLOCK_OPT_SIZE,
2275 .type = OPT_SIZE,
2276 .help = "Virtual disk size"
2277 },
6744cbab
KW
2278 {
2279 .name = BLOCK_OPT_COMPAT_LEVEL,
2280 .type = OPT_STRING,
2281 .help = "Compatibility level (0.10 or 1.1)"
2282 },
20d97356
BS
2283 {
2284 .name = BLOCK_OPT_BACKING_FILE,
2285 .type = OPT_STRING,
2286 .help = "File name of a base image"
2287 },
2288 {
2289 .name = BLOCK_OPT_BACKING_FMT,
2290 .type = OPT_STRING,
2291 .help = "Image format of the base image"
2292 },
2293 {
2294 .name = BLOCK_OPT_ENCRYPT,
2295 .type = OPT_FLAG,
2296 .help = "Encrypt the image"
2297 },
2298 {
2299 .name = BLOCK_OPT_CLUSTER_SIZE,
2300 .type = OPT_SIZE,
99cce9fa
KW
2301 .help = "qcow2 cluster size",
2302 .value = { .n = DEFAULT_CLUSTER_SIZE },
20d97356
BS
2303 },
2304 {
2305 .name = BLOCK_OPT_PREALLOC,
2306 .type = OPT_STRING,
2307 .help = "Preallocation mode (allowed values: off, metadata)"
2308 },
bfe8043e
SH
2309 {
2310 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2311 .type = OPT_FLAG,
2312 .help = "Postpone refcount updates",
2313 },
20d97356
BS
2314 { NULL }
2315};
2316
2317static BlockDriver bdrv_qcow2 = {
7c80ab3f
JS
2318 .format_name = "qcow2",
2319 .instance_size = sizeof(BDRVQcowState),
2320 .bdrv_probe = qcow2_probe,
2321 .bdrv_open = qcow2_open,
2322 .bdrv_close = qcow2_close,
21d82ac9 2323 .bdrv_reopen_prepare = qcow2_reopen_prepare,
7c80ab3f 2324 .bdrv_create = qcow2_create,
3ac21627 2325 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 2326 .bdrv_co_get_block_status = qcow2_co_get_block_status,
7c80ab3f 2327 .bdrv_set_key = qcow2_set_key,
7c80ab3f 2328
c68b89ac
KW
2329 .bdrv_co_readv = qcow2_co_readv,
2330 .bdrv_co_writev = qcow2_co_writev,
eb489bb1 2331 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 2332
621f0589 2333 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
6db39ae2 2334 .bdrv_co_discard = qcow2_co_discard,
419b19d9 2335 .bdrv_truncate = qcow2_truncate,
7c80ab3f 2336 .bdrv_write_compressed = qcow2_write_compressed,
20d97356
BS
2337
2338 .bdrv_snapshot_create = qcow2_snapshot_create,
2339 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2340 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2341 .bdrv_snapshot_list = qcow2_snapshot_list,
51ef6727 2342 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
7c80ab3f 2343 .bdrv_get_info = qcow2_get_info,
37764dfb 2344 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 2345
7c80ab3f
JS
2346 .bdrv_save_vmstate = qcow2_save_vmstate,
2347 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356
BS
2348
2349 .bdrv_change_backing_file = qcow2_change_backing_file,
2350
d34682cd 2351 .bdrv_refresh_limits = qcow2_refresh_limits,
06d9260f
AL
2352 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2353
7c80ab3f
JS
2354 .create_options = qcow2_create_options,
2355 .bdrv_check = qcow2_check,
9296b3ed 2356 .bdrv_amend_options = qcow2_amend_options,
20d97356
BS
2357};
2358
5efa9d5a
AL
2359static void bdrv_qcow2_init(void)
2360{
2361 bdrv_register(&bdrv_qcow2);
2362}
2363
2364block_init(bdrv_qcow2_init);