]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
qcow2: Validate snapshot table offset/size (CVE-2014-0144)
[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
ce48f2f4
KW
626 /* Snapshot table offset/length */
627 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
628 error_setg(errp, "Too many snapshots");
629 ret = -EINVAL;
630 goto fail;
631 }
632
633 ret = validate_table_offset(bs, header.snapshots_offset,
634 header.nb_snapshots,
635 sizeof(QCowSnapshotHeader));
636 if (ret < 0) {
637 error_setg(errp, "Invalid snapshot table offset");
638 goto fail;
639 }
640
585f8587
FB
641 s->snapshots_offset = header.snapshots_offset;
642 s->nb_snapshots = header.nb_snapshots;
643
644 /* read the level 1 table */
645 s->l1_size = header.l1_size;
2cf7cfa1
KW
646
647 l1_vm_state_index = size_to_l1(s, header.size);
648 if (l1_vm_state_index > INT_MAX) {
3ef6c40a 649 error_setg(errp, "Image is too big");
2cf7cfa1
KW
650 ret = -EFBIG;
651 goto fail;
652 }
653 s->l1_vm_state_index = l1_vm_state_index;
654
585f8587
FB
655 /* the L1 table must contain at least enough entries to put
656 header.size bytes */
6d85a57e 657 if (s->l1_size < s->l1_vm_state_index) {
3ef6c40a 658 error_setg(errp, "L1 table is too small");
6d85a57e 659 ret = -EINVAL;
585f8587 660 goto fail;
6d85a57e 661 }
585f8587 662 s->l1_table_offset = header.l1_table_offset;
d191d12d 663 if (s->l1_size > 0) {
7267c094 664 s->l1_table = g_malloc0(
d191d12d 665 align_offset(s->l1_size * sizeof(uint64_t), 512));
6d85a57e
JS
666 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
667 s->l1_size * sizeof(uint64_t));
668 if (ret < 0) {
3ef6c40a 669 error_setg_errno(errp, -ret, "Could not read L1 table");
d191d12d 670 goto fail;
6d85a57e 671 }
d191d12d
SW
672 for(i = 0;i < s->l1_size; i++) {
673 be64_to_cpus(&s->l1_table[i]);
674 }
585f8587 675 }
29c1a730
KW
676
677 /* alloc L2 table/refcount block cache */
6af4e9ea
PB
678 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
679 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
29c1a730 680
7267c094 681 s->cluster_cache = g_malloc(s->cluster_size);
585f8587 682 /* one more sector for decompressed data alignment */
dea43a65 683 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
095a9c58 684 + 512);
585f8587 685 s->cluster_cache_offset = -1;
06d9260f 686 s->flags = flags;
3b46e624 687
6d85a57e
JS
688 ret = qcow2_refcount_init(bs);
689 if (ret != 0) {
3ef6c40a 690 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
585f8587 691 goto fail;
6d85a57e 692 }
585f8587 693
72cf2d4f 694 QLIST_INIT(&s->cluster_allocs);
0b919fae 695 QTAILQ_INIT(&s->discards);
f214978a 696
9b80ddf3 697 /* read qcow2 extensions */
3ef6c40a
HR
698 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
699 &local_err)) {
700 error_propagate(errp, local_err);
6d85a57e 701 ret = -EINVAL;
9b80ddf3 702 goto fail;
6d85a57e 703 }
9b80ddf3 704
585f8587
FB
705 /* read the backing file name */
706 if (header.backing_file_offset != 0) {
707 len = header.backing_file_size;
6d85a57e 708 if (len > 1023) {
585f8587 709 len = 1023;
6d85a57e
JS
710 }
711 ret = bdrv_pread(bs->file, header.backing_file_offset,
712 bs->backing_file, len);
713 if (ret < 0) {
3ef6c40a 714 error_setg_errno(errp, -ret, "Could not read backing file name");
585f8587 715 goto fail;
6d85a57e 716 }
585f8587
FB
717 bs->backing_file[len] = '\0';
718 }
42deb29f
KW
719
720 ret = qcow2_read_snapshots(bs);
721 if (ret < 0) {
3ef6c40a 722 error_setg_errno(errp, -ret, "Could not read snapshots");
585f8587 723 goto fail;
6d85a57e 724 }
585f8587 725
af7b708d 726 /* Clear unknown autoclear feature bits */
27eb6c09 727 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
af7b708d
SH
728 s->autoclear_features = 0;
729 ret = qcow2_update_header(bs);
730 if (ret < 0) {
3ef6c40a 731 error_setg_errno(errp, -ret, "Could not update qcow2 header");
af7b708d
SH
732 goto fail;
733 }
734 }
735
68d100e9
KW
736 /* Initialise locks */
737 qemu_co_mutex_init(&s->lock);
738
c61d0004 739 /* Repair image if dirty */
27eb6c09 740 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
058f8f16 741 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
c61d0004
SH
742 BdrvCheckResult result = {0};
743
acbe5982 744 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
c61d0004 745 if (ret < 0) {
3ef6c40a 746 error_setg_errno(errp, -ret, "Could not repair dirty image");
c61d0004
SH
747 goto fail;
748 }
749 }
750
74c4510a 751 /* Enable lazy_refcounts according to image and command line options */
87ea75d5 752 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
74c4510a 753 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 754 if (local_err) {
3ef6c40a 755 error_propagate(errp, local_err);
74c4510a
KW
756 ret = -EINVAL;
757 goto fail;
758 }
759
acdfb480 760 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
74c4510a
KW
761 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
762
67af674e
KW
763 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
764 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
765 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
766 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
767 flags & BDRV_O_UNMAP);
768 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
769 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
770 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
771 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
772
1fa5cc83
HR
773 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
774 if (!strcmp(opt_overlap_check, "none")) {
775 overlap_check_template = 0;
776 } else if (!strcmp(opt_overlap_check, "constant")) {
777 overlap_check_template = QCOW2_OL_CONSTANT;
778 } else if (!strcmp(opt_overlap_check, "cached")) {
779 overlap_check_template = QCOW2_OL_CACHED;
780 } else if (!strcmp(opt_overlap_check, "all")) {
781 overlap_check_template = QCOW2_OL_ALL;
782 } else {
783 error_setg(errp, "Unsupported value '%s' for qcow2 option "
784 "'overlap-check'. Allowed are either of the following: "
785 "none, constant, cached, all", opt_overlap_check);
786 qemu_opts_del(opts);
787 ret = -EINVAL;
788 goto fail;
789 }
790
791 s->overlap_check = 0;
792 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
793 /* overlap-check defines a template bitmask, but every flag may be
794 * overwritten through the associated boolean option */
795 s->overlap_check |=
796 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
797 overlap_check_template & (1 << i)) << i;
798 }
3e355390 799
74c4510a
KW
800 qemu_opts_del(opts);
801
802 if (s->use_lazy_refcounts && s->qcow_version < 3) {
3ef6c40a
HR
803 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
804 "qemu 1.1 compatibility level");
74c4510a
KW
805 ret = -EINVAL;
806 goto fail;
807 }
808
585f8587 809#ifdef DEBUG_ALLOC
6cbc3031
PH
810 {
811 BdrvCheckResult result = {0};
b35278f7 812 qcow2_check_refcounts(bs, &result, 0);
6cbc3031 813 }
585f8587 814#endif
6d85a57e 815 return ret;
585f8587
FB
816
817 fail:
6744cbab 818 g_free(s->unknown_header_fields);
75bab85c 819 cleanup_unknown_header_ext(bs);
ed6ccf0f
KW
820 qcow2_free_snapshots(bs);
821 qcow2_refcount_close(bs);
7267c094 822 g_free(s->l1_table);
cf93980e
HR
823 /* else pre-write overlap checks in cache_destroy may crash */
824 s->l1_table = NULL;
29c1a730
KW
825 if (s->l2_table_cache) {
826 qcow2_cache_destroy(bs, s->l2_table_cache);
827 }
c5a33ee9
PJ
828 if (s->refcount_block_cache) {
829 qcow2_cache_destroy(bs, s->refcount_block_cache);
830 }
7267c094 831 g_free(s->cluster_cache);
dea43a65 832 qemu_vfree(s->cluster_data);
6d85a57e 833 return ret;
585f8587
FB
834}
835
d34682cd
KW
836static int qcow2_refresh_limits(BlockDriverState *bs)
837{
838 BDRVQcowState *s = bs->opaque;
839
840 bs->bl.write_zeroes_alignment = s->cluster_sectors;
841
842 return 0;
843}
844
7c80ab3f 845static int qcow2_set_key(BlockDriverState *bs, const char *key)
585f8587
FB
846{
847 BDRVQcowState *s = bs->opaque;
848 uint8_t keybuf[16];
849 int len, i;
3b46e624 850
585f8587
FB
851 memset(keybuf, 0, 16);
852 len = strlen(key);
853 if (len > 16)
854 len = 16;
855 /* XXX: we could compress the chars to 7 bits to increase
856 entropy */
857 for(i = 0;i < len;i++) {
858 keybuf[i] = key[i];
859 }
860 s->crypt_method = s->crypt_method_header;
861
862 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
863 return -1;
864 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
865 return -1;
866#if 0
867 /* test */
868 {
869 uint8_t in[16];
870 uint8_t out[16];
871 uint8_t tmp[16];
872 for(i=0;i<16;i++)
873 in[i] = i;
874 AES_encrypt(in, tmp, &s->aes_encrypt_key);
875 AES_decrypt(tmp, out, &s->aes_decrypt_key);
876 for(i = 0; i < 16; i++)
877 printf(" %02x", tmp[i]);
878 printf("\n");
879 for(i = 0; i < 16; i++)
880 printf(" %02x", out[i]);
881 printf("\n");
882 }
883#endif
884 return 0;
885}
886
21d82ac9
JC
887/* We have nothing to do for QCOW2 reopen, stubs just return
888 * success */
889static int qcow2_reopen_prepare(BDRVReopenState *state,
890 BlockReopenQueue *queue, Error **errp)
891{
892 return 0;
893}
894
b6b8a333 895static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
f8a2e5e3 896 int64_t sector_num, int nb_sectors, int *pnum)
585f8587 897{
f8a2e5e3 898 BDRVQcowState *s = bs->opaque;
585f8587 899 uint64_t cluster_offset;
4bc74be9
PB
900 int index_in_cluster, ret;
901 int64_t status = 0;
585f8587 902
095a9c58 903 *pnum = nb_sectors;
f8a2e5e3 904 qemu_co_mutex_lock(&s->lock);
1c46efaa 905 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
f8a2e5e3 906 qemu_co_mutex_unlock(&s->lock);
1c46efaa 907 if (ret < 0) {
d663640c 908 return ret;
1c46efaa 909 }
095a9c58 910
4bc74be9
PB
911 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
912 !s->crypt_method) {
913 index_in_cluster = sector_num & (s->cluster_sectors - 1);
914 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
915 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
916 }
917 if (ret == QCOW2_CLUSTER_ZERO) {
918 status |= BDRV_BLOCK_ZERO;
919 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
920 status |= BDRV_BLOCK_DATA;
921 }
922 return status;
585f8587
FB
923}
924
a9465922 925/* handle reading after the end of the backing file */
bd28f835
KW
926int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
927 int64_t sector_num, int nb_sectors)
a9465922
FB
928{
929 int n1;
930 if ((sector_num + nb_sectors) <= bs->total_sectors)
931 return nb_sectors;
932 if (sector_num >= bs->total_sectors)
933 n1 = 0;
934 else
935 n1 = bs->total_sectors - sector_num;
bd28f835 936
3d9b4925 937 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
bd28f835 938
a9465922
FB
939 return n1;
940}
941
a968168c 942static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
3fc48d09 943 int remaining_sectors, QEMUIOVector *qiov)
585f8587 944{
585f8587 945 BDRVQcowState *s = bs->opaque;
a9465922 946 int index_in_cluster, n1;
68d100e9 947 int ret;
faf575c1 948 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 949 uint64_t cluster_offset = 0;
3fc48d09
FZ
950 uint64_t bytes_done = 0;
951 QEMUIOVector hd_qiov;
952 uint8_t *cluster_data = NULL;
585f8587 953
3fc48d09
FZ
954 qemu_iovec_init(&hd_qiov, qiov->niov);
955
956 qemu_co_mutex_lock(&s->lock);
957
958 while (remaining_sectors != 0) {
bd28f835 959
5ebaa27e 960 /* prepare next request */
3fc48d09 961 cur_nr_sectors = remaining_sectors;
5ebaa27e
FZ
962 if (s->crypt_method) {
963 cur_nr_sectors = MIN(cur_nr_sectors,
964 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
585f8587 965 }
5ebaa27e 966
3fc48d09 967 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
5ebaa27e 968 &cur_nr_sectors, &cluster_offset);
8af36488 969 if (ret < 0) {
3fc48d09 970 goto fail;
8af36488 971 }
bd28f835 972
3fc48d09 973 index_in_cluster = sector_num & (s->cluster_sectors - 1);
c87c0672 974
3fc48d09 975 qemu_iovec_reset(&hd_qiov);
1b093c48 976 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e
FZ
977 cur_nr_sectors * 512);
978
68d000a3
KW
979 switch (ret) {
980 case QCOW2_CLUSTER_UNALLOCATED:
5ebaa27e
FZ
981
982 if (bs->backing_hd) {
983 /* read from the base image */
3fc48d09
FZ
984 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
985 sector_num, cur_nr_sectors);
5ebaa27e
FZ
986 if (n1 > 0) {
987 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
988 qemu_co_mutex_unlock(&s->lock);
3fc48d09
FZ
989 ret = bdrv_co_readv(bs->backing_hd, sector_num,
990 n1, &hd_qiov);
5ebaa27e
FZ
991 qemu_co_mutex_lock(&s->lock);
992 if (ret < 0) {
3fc48d09 993 goto fail;
5ebaa27e
FZ
994 }
995 }
996 } else {
997 /* Note: in this case, no need to wait */
3d9b4925 998 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
5ebaa27e 999 }
68d000a3
KW
1000 break;
1001
6377af48 1002 case QCOW2_CLUSTER_ZERO:
3d9b4925 1003 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
6377af48
KW
1004 break;
1005
68d000a3 1006 case QCOW2_CLUSTER_COMPRESSED:
5ebaa27e
FZ
1007 /* add AIO support for compressed blocks ? */
1008 ret = qcow2_decompress_cluster(bs, cluster_offset);
1009 if (ret < 0) {
3fc48d09 1010 goto fail;
bd28f835
KW
1011 }
1012
03396148 1013 qemu_iovec_from_buf(&hd_qiov, 0,
5ebaa27e 1014 s->cluster_cache + index_in_cluster * 512,
faf575c1 1015 512 * cur_nr_sectors);
68d000a3
KW
1016 break;
1017
1018 case QCOW2_CLUSTER_NORMAL:
5ebaa27e 1019 if ((cluster_offset & 511) != 0) {
3fc48d09
FZ
1020 ret = -EIO;
1021 goto fail;
5ebaa27e 1022 }
bd28f835 1023
5ebaa27e
FZ
1024 if (s->crypt_method) {
1025 /*
1026 * For encrypted images, read everything into a temporary
1027 * contiguous buffer on which the AES functions can work.
1028 */
3fc48d09
FZ
1029 if (!cluster_data) {
1030 cluster_data =
dea43a65 1031 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
5ebaa27e
FZ
1032 }
1033
1034 assert(cur_nr_sectors <=
1035 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
3fc48d09
FZ
1036 qemu_iovec_reset(&hd_qiov);
1037 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1038 512 * cur_nr_sectors);
1039 }
1040
1041 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1042 qemu_co_mutex_unlock(&s->lock);
1043 ret = bdrv_co_readv(bs->file,
1044 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1045 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1046 qemu_co_mutex_lock(&s->lock);
1047 if (ret < 0) {
3fc48d09 1048 goto fail;
5ebaa27e
FZ
1049 }
1050 if (s->crypt_method) {
3fc48d09
FZ
1051 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1052 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
03396148
MT
1053 qemu_iovec_from_buf(qiov, bytes_done,
1054 cluster_data, 512 * cur_nr_sectors);
5ebaa27e 1055 }
68d000a3
KW
1056 break;
1057
1058 default:
1059 g_assert_not_reached();
1060 ret = -EIO;
1061 goto fail;
faf575c1 1062 }
f141eafe 1063
3fc48d09
FZ
1064 remaining_sectors -= cur_nr_sectors;
1065 sector_num += cur_nr_sectors;
1066 bytes_done += cur_nr_sectors * 512;
5ebaa27e 1067 }
3fc48d09 1068 ret = 0;
faf575c1 1069
3fc48d09 1070fail:
68d100e9 1071 qemu_co_mutex_unlock(&s->lock);
42496d62 1072
3fc48d09 1073 qemu_iovec_destroy(&hd_qiov);
dea43a65 1074 qemu_vfree(cluster_data);
68d100e9
KW
1075
1076 return ret;
585f8587
FB
1077}
1078
a968168c 1079static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
3fc48d09
FZ
1080 int64_t sector_num,
1081 int remaining_sectors,
1082 QEMUIOVector *qiov)
585f8587 1083{
585f8587 1084 BDRVQcowState *s = bs->opaque;
585f8587 1085 int index_in_cluster;
68d100e9 1086 int ret;
faf575c1 1087 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 1088 uint64_t cluster_offset;
3fc48d09
FZ
1089 QEMUIOVector hd_qiov;
1090 uint64_t bytes_done = 0;
1091 uint8_t *cluster_data = NULL;
8d2497c3 1092 QCowL2Meta *l2meta = NULL;
c2271403 1093
3cce16f4
KW
1094 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1095 remaining_sectors);
1096
3fc48d09
FZ
1097 qemu_iovec_init(&hd_qiov, qiov->niov);
1098
1099 s->cluster_cache_offset = -1; /* disable compressed cache */
3b46e624 1100
3fc48d09
FZ
1101 qemu_co_mutex_lock(&s->lock);
1102
1103 while (remaining_sectors != 0) {
1104
f50f88b9 1105 l2meta = NULL;
cf5c1a23 1106
3cce16f4 1107 trace_qcow2_writev_start_part(qemu_coroutine_self());
3fc48d09 1108 index_in_cluster = sector_num & (s->cluster_sectors - 1);
16f0587e 1109 cur_nr_sectors = remaining_sectors;
5ebaa27e 1110 if (s->crypt_method &&
16f0587e
HT
1111 cur_nr_sectors >
1112 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1113 cur_nr_sectors =
1114 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
5ebaa27e 1115 }
095a9c58 1116
3fc48d09 1117 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
16f0587e 1118 &cur_nr_sectors, &cluster_offset, &l2meta);
5ebaa27e 1119 if (ret < 0) {
3fc48d09 1120 goto fail;
5ebaa27e 1121 }
148da7ea 1122
5ebaa27e 1123 assert((cluster_offset & 511) == 0);
148da7ea 1124
3fc48d09 1125 qemu_iovec_reset(&hd_qiov);
1b093c48 1126 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e 1127 cur_nr_sectors * 512);
6f5f060b 1128
5ebaa27e 1129 if (s->crypt_method) {
3fc48d09 1130 if (!cluster_data) {
dea43a65 1131 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
5ebaa27e
FZ
1132 s->cluster_size);
1133 }
6f5f060b 1134
3fc48d09 1135 assert(hd_qiov.size <=
5ebaa27e 1136 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
d5e6b161 1137 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
6f5f060b 1138
3fc48d09
FZ
1139 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1140 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
6f5f060b 1141
3fc48d09
FZ
1142 qemu_iovec_reset(&hd_qiov);
1143 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
1144 cur_nr_sectors * 512);
1145 }
6f5f060b 1146
231bb267 1147 ret = qcow2_pre_write_overlap_check(bs, 0,
cf93980e
HR
1148 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1149 cur_nr_sectors * BDRV_SECTOR_SIZE);
1150 if (ret < 0) {
1151 goto fail;
1152 }
1153
5ebaa27e 1154 qemu_co_mutex_unlock(&s->lock);
67a7a0eb 1155 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
3cce16f4
KW
1156 trace_qcow2_writev_data(qemu_coroutine_self(),
1157 (cluster_offset >> 9) + index_in_cluster);
5ebaa27e
FZ
1158 ret = bdrv_co_writev(bs->file,
1159 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 1160 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
1161 qemu_co_mutex_lock(&s->lock);
1162 if (ret < 0) {
3fc48d09 1163 goto fail;
5ebaa27e 1164 }
f141eafe 1165
88c6588c
KW
1166 while (l2meta != NULL) {
1167 QCowL2Meta *next;
1168
f50f88b9
KW
1169 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1170 if (ret < 0) {
1171 goto fail;
1172 }
faf575c1 1173
4e95314e
KW
1174 /* Take the request off the list of running requests */
1175 if (l2meta->nb_clusters != 0) {
1176 QLIST_REMOVE(l2meta, next_in_flight);
1177 }
1178
4e95314e 1179 qemu_co_queue_restart_all(&l2meta->dependent_requests);
4e95314e 1180
88c6588c 1181 next = l2meta->next;
f50f88b9 1182 g_free(l2meta);
88c6588c 1183 l2meta = next;
f50f88b9 1184 }
0fa9131a 1185
3fc48d09
FZ
1186 remaining_sectors -= cur_nr_sectors;
1187 sector_num += cur_nr_sectors;
1188 bytes_done += cur_nr_sectors * 512;
3cce16f4 1189 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
5ebaa27e 1190 }
3fc48d09 1191 ret = 0;
faf575c1 1192
3fc48d09 1193fail:
4e95314e
KW
1194 qemu_co_mutex_unlock(&s->lock);
1195
88c6588c
KW
1196 while (l2meta != NULL) {
1197 QCowL2Meta *next;
1198
4e95314e
KW
1199 if (l2meta->nb_clusters != 0) {
1200 QLIST_REMOVE(l2meta, next_in_flight);
1201 }
1202 qemu_co_queue_restart_all(&l2meta->dependent_requests);
88c6588c
KW
1203
1204 next = l2meta->next;
cf5c1a23 1205 g_free(l2meta);
88c6588c 1206 l2meta = next;
cf5c1a23 1207 }
0fa9131a 1208
3fc48d09 1209 qemu_iovec_destroy(&hd_qiov);
dea43a65 1210 qemu_vfree(cluster_data);
3cce16f4 1211 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 1212
68d100e9 1213 return ret;
585f8587
FB
1214}
1215
7c80ab3f 1216static void qcow2_close(BlockDriverState *bs)
585f8587
FB
1217{
1218 BDRVQcowState *s = bs->opaque;
7267c094 1219 g_free(s->l1_table);
cf93980e
HR
1220 /* else pre-write overlap checks in cache_destroy may crash */
1221 s->l1_table = NULL;
29c1a730 1222
27eb6c09
KW
1223 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1224 qcow2_cache_flush(bs, s->l2_table_cache);
1225 qcow2_cache_flush(bs, s->refcount_block_cache);
29c1a730 1226
27eb6c09
KW
1227 qcow2_mark_clean(bs);
1228 }
c61d0004 1229
29c1a730
KW
1230 qcow2_cache_destroy(bs, s->l2_table_cache);
1231 qcow2_cache_destroy(bs, s->refcount_block_cache);
1232
6744cbab 1233 g_free(s->unknown_header_fields);
75bab85c 1234 cleanup_unknown_header_ext(bs);
6744cbab 1235
7267c094 1236 g_free(s->cluster_cache);
dea43a65 1237 qemu_vfree(s->cluster_data);
ed6ccf0f 1238 qcow2_refcount_close(bs);
28c1202b 1239 qcow2_free_snapshots(bs);
585f8587
FB
1240}
1241
5a8a30db 1242static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
06d9260f
AL
1243{
1244 BDRVQcowState *s = bs->opaque;
1245 int flags = s->flags;
1246 AES_KEY aes_encrypt_key;
1247 AES_KEY aes_decrypt_key;
1248 uint32_t crypt_method = 0;
acdfb480 1249 QDict *options;
5a8a30db
KW
1250 Error *local_err = NULL;
1251 int ret;
06d9260f
AL
1252
1253 /*
1254 * Backing files are read-only which makes all of their metadata immutable,
1255 * that means we don't have to worry about reopening them here.
1256 */
1257
1258 if (s->crypt_method) {
1259 crypt_method = s->crypt_method;
1260 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1261 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1262 }
1263
1264 qcow2_close(bs);
1265
5a8a30db
KW
1266 bdrv_invalidate_cache(bs->file, &local_err);
1267 if (local_err) {
1268 error_propagate(errp, local_err);
1269 return;
1270 }
3456a8d1 1271
06d9260f 1272 memset(s, 0, sizeof(BDRVQcowState));
d475e5ac 1273 options = qdict_clone_shallow(bs->options);
5a8a30db
KW
1274
1275 ret = qcow2_open(bs, options, flags, &local_err);
1276 if (local_err) {
1277 error_setg(errp, "Could not reopen qcow2 layer: %s",
1278 error_get_pretty(local_err));
1279 error_free(local_err);
1280 return;
1281 } else if (ret < 0) {
1282 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1283 return;
1284 }
acdfb480
KW
1285
1286 QDECREF(options);
06d9260f
AL
1287
1288 if (crypt_method) {
1289 s->crypt_method = crypt_method;
1290 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1291 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1292 }
1293}
1294
e24e49e6
KW
1295static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1296 size_t len, size_t buflen)
1297{
1298 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1299 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1300
1301 if (buflen < ext_len) {
1302 return -ENOSPC;
1303 }
1304
1305 *ext_backing_fmt = (QCowExtension) {
1306 .magic = cpu_to_be32(magic),
1307 .len = cpu_to_be32(len),
1308 };
1309 memcpy(buf + sizeof(QCowExtension), s, len);
1310
1311 return ext_len;
1312}
1313
756e6736 1314/*
e24e49e6
KW
1315 * Updates the qcow2 header, including the variable length parts of it, i.e.
1316 * the backing file name and all extensions. qcow2 was not designed to allow
1317 * such changes, so if we run out of space (we can only use the first cluster)
1318 * this function may fail.
756e6736
KW
1319 *
1320 * Returns 0 on success, -errno in error cases.
1321 */
e24e49e6 1322int qcow2_update_header(BlockDriverState *bs)
756e6736 1323{
756e6736 1324 BDRVQcowState *s = bs->opaque;
e24e49e6
KW
1325 QCowHeader *header;
1326 char *buf;
1327 size_t buflen = s->cluster_size;
756e6736 1328 int ret;
e24e49e6
KW
1329 uint64_t total_size;
1330 uint32_t refcount_table_clusters;
6744cbab 1331 size_t header_length;
75bab85c 1332 Qcow2UnknownHeaderExtension *uext;
756e6736 1333
e24e49e6 1334 buf = qemu_blockalign(bs, buflen);
756e6736 1335
e24e49e6
KW
1336 /* Header structure */
1337 header = (QCowHeader*) buf;
756e6736 1338
e24e49e6
KW
1339 if (buflen < sizeof(*header)) {
1340 ret = -ENOSPC;
1341 goto fail;
756e6736
KW
1342 }
1343
6744cbab 1344 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
1345 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1346 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1347
1348 *header = (QCowHeader) {
6744cbab 1349 /* Version 2 fields */
e24e49e6 1350 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 1351 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
1352 .backing_file_offset = 0,
1353 .backing_file_size = 0,
1354 .cluster_bits = cpu_to_be32(s->cluster_bits),
1355 .size = cpu_to_be64(total_size),
1356 .crypt_method = cpu_to_be32(s->crypt_method_header),
1357 .l1_size = cpu_to_be32(s->l1_size),
1358 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1359 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1360 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1361 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1362 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
1363
1364 /* Version 3 fields */
1365 .incompatible_features = cpu_to_be64(s->incompatible_features),
1366 .compatible_features = cpu_to_be64(s->compatible_features),
1367 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 1368 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 1369 .header_length = cpu_to_be32(header_length),
e24e49e6 1370 };
756e6736 1371
6744cbab
KW
1372 /* For older versions, write a shorter header */
1373 switch (s->qcow_version) {
1374 case 2:
1375 ret = offsetof(QCowHeader, incompatible_features);
1376 break;
1377 case 3:
1378 ret = sizeof(*header);
1379 break;
1380 default:
b6c14762
JM
1381 ret = -EINVAL;
1382 goto fail;
6744cbab
KW
1383 }
1384
1385 buf += ret;
1386 buflen -= ret;
1387 memset(buf, 0, buflen);
1388
1389 /* Preserve any unknown field in the header */
1390 if (s->unknown_header_fields_size) {
1391 if (buflen < s->unknown_header_fields_size) {
1392 ret = -ENOSPC;
1393 goto fail;
1394 }
1395
1396 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1397 buf += s->unknown_header_fields_size;
1398 buflen -= s->unknown_header_fields_size;
1399 }
756e6736 1400
e24e49e6
KW
1401 /* Backing file format header extension */
1402 if (*bs->backing_format) {
1403 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1404 bs->backing_format, strlen(bs->backing_format),
1405 buflen);
1406 if (ret < 0) {
1407 goto fail;
756e6736
KW
1408 }
1409
e24e49e6
KW
1410 buf += ret;
1411 buflen -= ret;
756e6736
KW
1412 }
1413
cfcc4c62
KW
1414 /* Feature table */
1415 Qcow2Feature features[] = {
c61d0004
SH
1416 {
1417 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1418 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1419 .name = "dirty bit",
1420 },
69c98726
HR
1421 {
1422 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1423 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1424 .name = "corrupt bit",
1425 },
bfe8043e
SH
1426 {
1427 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1428 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1429 .name = "lazy refcounts",
1430 },
cfcc4c62
KW
1431 };
1432
1433 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1434 features, sizeof(features), buflen);
1435 if (ret < 0) {
1436 goto fail;
1437 }
1438 buf += ret;
1439 buflen -= ret;
1440
75bab85c
KW
1441 /* Keep unknown header extensions */
1442 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1443 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1444 if (ret < 0) {
1445 goto fail;
1446 }
1447
1448 buf += ret;
1449 buflen -= ret;
1450 }
1451
e24e49e6
KW
1452 /* End of header extensions */
1453 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
1454 if (ret < 0) {
1455 goto fail;
1456 }
1457
e24e49e6
KW
1458 buf += ret;
1459 buflen -= ret;
756e6736 1460
e24e49e6
KW
1461 /* Backing file name */
1462 if (*bs->backing_file) {
1463 size_t backing_file_len = strlen(bs->backing_file);
1464
1465 if (buflen < backing_file_len) {
1466 ret = -ENOSPC;
1467 goto fail;
1468 }
1469
00ea1881 1470 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e24e49e6
KW
1471 strncpy(buf, bs->backing_file, buflen);
1472
1473 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1474 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
1475 }
1476
e24e49e6
KW
1477 /* Write the new header */
1478 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
1479 if (ret < 0) {
1480 goto fail;
1481 }
1482
1483 ret = 0;
1484fail:
e24e49e6 1485 qemu_vfree(header);
756e6736
KW
1486 return ret;
1487}
1488
1489static int qcow2_change_backing_file(BlockDriverState *bs,
1490 const char *backing_file, const char *backing_fmt)
1491{
e24e49e6
KW
1492 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1493 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1494
1495 return qcow2_update_header(bs);
756e6736
KW
1496}
1497
a35e1c17
KW
1498static int preallocate(BlockDriverState *bs)
1499{
a35e1c17
KW
1500 uint64_t nb_sectors;
1501 uint64_t offset;
060bee89 1502 uint64_t host_offset = 0;
a35e1c17 1503 int num;
148da7ea 1504 int ret;
f50f88b9 1505 QCowL2Meta *meta;
a35e1c17 1506
7c2bbf4a 1507 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
a35e1c17
KW
1508 offset = 0;
1509
1510 while (nb_sectors) {
7c2bbf4a 1511 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
16f0587e 1512 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
060bee89 1513 &host_offset, &meta);
148da7ea 1514 if (ret < 0) {
19dbcbf7 1515 return ret;
a35e1c17
KW
1516 }
1517
f50f88b9 1518 if (meta != NULL) {
7c2bbf4a
HT
1519 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1520 if (ret < 0) {
1521 qcow2_free_any_clusters(bs, meta->alloc_offset,
1522 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1523 return ret;
1524 }
1525
1526 /* There are no dependent requests, but we need to remove our
1527 * request from the list of in-flight requests */
4e95314e 1528 QLIST_REMOVE(meta, next_in_flight);
f50f88b9 1529 }
f214978a 1530
a35e1c17
KW
1531 /* TODO Preallocate data if requested */
1532
1533 nb_sectors -= num;
7c2bbf4a 1534 offset += num << BDRV_SECTOR_BITS;
a35e1c17
KW
1535 }
1536
1537 /*
1538 * It is expected that the image file is large enough to actually contain
1539 * all of the allocated clusters (otherwise we get failing reads after
1540 * EOF). Extend the image to the last allocated sector.
1541 */
060bee89 1542 if (host_offset != 0) {
7c2bbf4a
HT
1543 uint8_t buf[BDRV_SECTOR_SIZE];
1544 memset(buf, 0, BDRV_SECTOR_SIZE);
1545 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1546 buf, 1);
19dbcbf7
KW
1547 if (ret < 0) {
1548 return ret;
1549 }
a35e1c17
KW
1550 }
1551
1552 return 0;
1553}
1554
7c80ab3f
JS
1555static int qcow2_create2(const char *filename, int64_t total_size,
1556 const char *backing_file, const char *backing_format,
1557 int flags, size_t cluster_size, int prealloc,
3ef6c40a
HR
1558 QEMUOptionParameter *options, int version,
1559 Error **errp)
a9420734 1560{
9b2260cb 1561 /* Calculate cluster_bits */
a9420734
KW
1562 int cluster_bits;
1563 cluster_bits = ffs(cluster_size) - 1;
1564 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1565 (1 << cluster_bits) != cluster_size)
1566 {
3ef6c40a
HR
1567 error_setg(errp, "Cluster size must be a power of two between %d and "
1568 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
a9420734
KW
1569 return -EINVAL;
1570 }
1571
1572 /*
1573 * Open the image file and write a minimal qcow2 header.
1574 *
1575 * We keep things simple and start with a zero-sized image. We also
1576 * do without refcount blocks or a L1 table for now. We'll fix the
1577 * inconsistency later.
1578 *
1579 * We do need a refcount table because growing the refcount table means
1580 * allocating two new refcount blocks - the seconds of which would be at
1581 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1582 * size for any qcow2 image.
1583 */
1584 BlockDriverState* bs;
f8413b3c 1585 QCowHeader *header;
a9420734 1586 uint8_t* refcount_table;
3ef6c40a 1587 Error *local_err = NULL;
a9420734
KW
1588 int ret;
1589
3ef6c40a 1590 ret = bdrv_create_file(filename, options, &local_err);
a9420734 1591 if (ret < 0) {
3ef6c40a 1592 error_propagate(errp, local_err);
a9420734
KW
1593 return ret;
1594 }
1595
2e40134b
HR
1596 bs = NULL;
1597 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1598 NULL, &local_err);
a9420734 1599 if (ret < 0) {
3ef6c40a 1600 error_propagate(errp, local_err);
a9420734
KW
1601 return ret;
1602 }
1603
1604 /* Write the header */
f8413b3c
KW
1605 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1606 header = g_malloc0(cluster_size);
1607 *header = (QCowHeader) {
1608 .magic = cpu_to_be32(QCOW_MAGIC),
1609 .version = cpu_to_be32(version),
1610 .cluster_bits = cpu_to_be32(cluster_bits),
1611 .size = cpu_to_be64(0),
1612 .l1_table_offset = cpu_to_be64(0),
1613 .l1_size = cpu_to_be32(0),
1614 .refcount_table_offset = cpu_to_be64(cluster_size),
1615 .refcount_table_clusters = cpu_to_be32(1),
1616 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1617 .header_length = cpu_to_be32(sizeof(*header)),
1618 };
a9420734
KW
1619
1620 if (flags & BLOCK_FLAG_ENCRYPT) {
f8413b3c 1621 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
a9420734 1622 } else {
f8413b3c 1623 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734
KW
1624 }
1625
bfe8043e 1626 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
f8413b3c 1627 header->compatible_features |=
bfe8043e
SH
1628 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1629 }
1630
f8413b3c
KW
1631 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1632 g_free(header);
a9420734 1633 if (ret < 0) {
3ef6c40a 1634 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
1635 goto out;
1636 }
1637
1638 /* Write an empty refcount table */
7267c094 1639 refcount_table = g_malloc0(cluster_size);
a9420734 1640 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
7267c094 1641 g_free(refcount_table);
a9420734
KW
1642
1643 if (ret < 0) {
3ef6c40a 1644 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
1645 goto out;
1646 }
1647
f67503e5
HR
1648 bdrv_unref(bs);
1649 bs = NULL;
a9420734
KW
1650
1651 /*
1652 * And now open the image and make it consistent first (i.e. increase the
1653 * refcount of the cluster that is occupied by the header and the refcount
1654 * table)
1655 */
1656 BlockDriver* drv = bdrv_find_format("qcow2");
1657 assert(drv != NULL);
ddf5636d 1658 ret = bdrv_open(&bs, filename, NULL, NULL,
3ef6c40a 1659 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
a9420734 1660 if (ret < 0) {
3ef6c40a 1661 error_propagate(errp, local_err);
a9420734
KW
1662 goto out;
1663 }
1664
1665 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1666 if (ret < 0) {
3ef6c40a
HR
1667 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1668 "header and refcount table");
a9420734
KW
1669 goto out;
1670
1671 } else if (ret != 0) {
1672 error_report("Huh, first cluster in empty image is already in use?");
1673 abort();
1674 }
1675
1676 /* Okay, now that we have a valid image, let's give it the right size */
1677 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1678 if (ret < 0) {
3ef6c40a 1679 error_setg_errno(errp, -ret, "Could not resize image");
a9420734
KW
1680 goto out;
1681 }
1682
1683 /* Want a backing file? There you go.*/
1684 if (backing_file) {
1685 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1686 if (ret < 0) {
3ef6c40a
HR
1687 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1688 "with format '%s'", backing_file, backing_format);
a9420734
KW
1689 goto out;
1690 }
1691 }
1692
1693 /* And if we're supposed to preallocate metadata, do that now */
1694 if (prealloc) {
15552c4a
ZYW
1695 BDRVQcowState *s = bs->opaque;
1696 qemu_co_mutex_lock(&s->lock);
a9420734 1697 ret = preallocate(bs);
15552c4a 1698 qemu_co_mutex_unlock(&s->lock);
a9420734 1699 if (ret < 0) {
3ef6c40a 1700 error_setg_errno(errp, -ret, "Could not preallocate metadata");
a9420734
KW
1701 goto out;
1702 }
1703 }
1704
f67503e5
HR
1705 bdrv_unref(bs);
1706 bs = NULL;
ba2ab2f2
HR
1707
1708 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
ddf5636d 1709 ret = bdrv_open(&bs, filename, NULL, NULL,
c9fbb99d
KW
1710 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1711 drv, &local_err);
84d18f06 1712 if (local_err) {
ba2ab2f2
HR
1713 error_propagate(errp, local_err);
1714 goto out;
1715 }
1716
a9420734
KW
1717 ret = 0;
1718out:
f67503e5
HR
1719 if (bs) {
1720 bdrv_unref(bs);
1721 }
a9420734
KW
1722 return ret;
1723}
de5f3f40 1724
d5124c00
HR
1725static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1726 Error **errp)
de5f3f40
KW
1727{
1728 const char *backing_file = NULL;
1729 const char *backing_fmt = NULL;
1730 uint64_t sectors = 0;
1731 int flags = 0;
99cce9fa 1732 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
de5f3f40 1733 int prealloc = 0;
8ad1898c 1734 int version = 3;
3ef6c40a
HR
1735 Error *local_err = NULL;
1736 int ret;
de5f3f40
KW
1737
1738 /* Read out options */
1739 while (options && options->name) {
1740 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1741 sectors = options->value.n / 512;
1742 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1743 backing_file = options->value.s;
1744 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1745 backing_fmt = options->value.s;
1746 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1747 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1748 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1749 if (options->value.n) {
1750 cluster_size = options->value.n;
1751 }
1752 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1753 if (!options->value.s || !strcmp(options->value.s, "off")) {
1754 prealloc = 0;
1755 } else if (!strcmp(options->value.s, "metadata")) {
1756 prealloc = 1;
1757 } else {
3ef6c40a
HR
1758 error_setg(errp, "Invalid preallocation mode: '%s'",
1759 options->value.s);
de5f3f40
KW
1760 return -EINVAL;
1761 }
6744cbab 1762 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
9117b477
KW
1763 if (!options->value.s) {
1764 /* keep the default */
1765 } else if (!strcmp(options->value.s, "0.10")) {
6744cbab
KW
1766 version = 2;
1767 } else if (!strcmp(options->value.s, "1.1")) {
1768 version = 3;
1769 } else {
3ef6c40a
HR
1770 error_setg(errp, "Invalid compatibility level: '%s'",
1771 options->value.s);
6744cbab
KW
1772 return -EINVAL;
1773 }
bfe8043e
SH
1774 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1775 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
de5f3f40
KW
1776 }
1777 options++;
1778 }
1779
1780 if (backing_file && prealloc) {
3ef6c40a
HR
1781 error_setg(errp, "Backing file and preallocation cannot be used at "
1782 "the same time");
de5f3f40
KW
1783 return -EINVAL;
1784 }
1785
bfe8043e 1786 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
3ef6c40a
HR
1787 error_setg(errp, "Lazy refcounts only supported with compatibility "
1788 "level 1.1 and above (use compat=1.1 or greater)");
bfe8043e
SH
1789 return -EINVAL;
1790 }
1791
3ef6c40a
HR
1792 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1793 cluster_size, prealloc, options, version, &local_err);
84d18f06 1794 if (local_err) {
3ef6c40a
HR
1795 error_propagate(errp, local_err);
1796 }
1797 return ret;
de5f3f40
KW
1798}
1799
621f0589 1800static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
aa7bfbff 1801 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
621f0589
KW
1802{
1803 int ret;
1804 BDRVQcowState *s = bs->opaque;
1805
1806 /* Emulate misaligned zero writes */
1807 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1808 return -ENOTSUP;
1809 }
1810
1811 /* Whatever is left can use real zero clusters */
1812 qemu_co_mutex_lock(&s->lock);
1813 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1814 nb_sectors);
1815 qemu_co_mutex_unlock(&s->lock);
1816
1817 return ret;
1818}
1819
6db39ae2
PB
1820static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1821 int64_t sector_num, int nb_sectors)
5ea929e3 1822{
6db39ae2
PB
1823 int ret;
1824 BDRVQcowState *s = bs->opaque;
1825
1826 qemu_co_mutex_lock(&s->lock);
1827 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
670df5e3 1828 nb_sectors, QCOW2_DISCARD_REQUEST);
6db39ae2
PB
1829 qemu_co_mutex_unlock(&s->lock);
1830 return ret;
5ea929e3
KW
1831}
1832
419b19d9
SH
1833static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1834{
1835 BDRVQcowState *s = bs->opaque;
2cf7cfa1
KW
1836 int64_t new_l1_size;
1837 int ret;
419b19d9
SH
1838
1839 if (offset & 511) {
259b2173 1840 error_report("The new size must be a multiple of 512");
419b19d9
SH
1841 return -EINVAL;
1842 }
1843
1844 /* cannot proceed if image has snapshots */
1845 if (s->nb_snapshots) {
259b2173 1846 error_report("Can't resize an image which has snapshots");
419b19d9
SH
1847 return -ENOTSUP;
1848 }
1849
1850 /* shrinking is currently not supported */
1851 if (offset < bs->total_sectors * 512) {
259b2173 1852 error_report("qcow2 doesn't support shrinking images yet");
419b19d9
SH
1853 return -ENOTSUP;
1854 }
1855
1856 new_l1_size = size_to_l1(s, offset);
72893756 1857 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
419b19d9
SH
1858 if (ret < 0) {
1859 return ret;
1860 }
1861
1862 /* write updated header.size */
1863 offset = cpu_to_be64(offset);
8b3b7206
KW
1864 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1865 &offset, sizeof(uint64_t));
419b19d9
SH
1866 if (ret < 0) {
1867 return ret;
1868 }
1869
1870 s->l1_vm_state_index = new_l1_size;
1871 return 0;
1872}
1873
20d97356
BS
1874/* XXX: put compressed sectors first, then all the cluster aligned
1875 tables to avoid losing bytes in alignment */
7c80ab3f
JS
1876static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1877 const uint8_t *buf, int nb_sectors)
20d97356
BS
1878{
1879 BDRVQcowState *s = bs->opaque;
1880 z_stream strm;
1881 int ret, out_len;
1882 uint8_t *out_buf;
1883 uint64_t cluster_offset;
1884
1885 if (nb_sectors == 0) {
1886 /* align end of file to a sector boundary to ease reading with
1887 sector based I/Os */
66f82cee 1888 cluster_offset = bdrv_getlength(bs->file);
20d97356 1889 cluster_offset = (cluster_offset + 511) & ~511;
66f82cee 1890 bdrv_truncate(bs->file, cluster_offset);
20d97356
BS
1891 return 0;
1892 }
1893
f4d38bef
SH
1894 if (nb_sectors != s->cluster_sectors) {
1895 ret = -EINVAL;
1896
1897 /* Zero-pad last write if image size is not cluster aligned */
1898 if (sector_num + nb_sectors == bs->total_sectors &&
1899 nb_sectors < s->cluster_sectors) {
1900 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1901 memset(pad_buf, 0, s->cluster_size);
1902 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1903 ret = qcow2_write_compressed(bs, sector_num,
1904 pad_buf, s->cluster_sectors);
1905 qemu_vfree(pad_buf);
1906 }
1907 return ret;
1908 }
20d97356 1909
7267c094 1910 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
20d97356
BS
1911
1912 /* best compression, small window, no zlib header */
1913 memset(&strm, 0, sizeof(strm));
1914 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1915 Z_DEFLATED, -12,
1916 9, Z_DEFAULT_STRATEGY);
1917 if (ret != 0) {
8f1efd00
KW
1918 ret = -EINVAL;
1919 goto fail;
20d97356
BS
1920 }
1921
1922 strm.avail_in = s->cluster_size;
1923 strm.next_in = (uint8_t *)buf;
1924 strm.avail_out = s->cluster_size;
1925 strm.next_out = out_buf;
1926
1927 ret = deflate(&strm, Z_FINISH);
1928 if (ret != Z_STREAM_END && ret != Z_OK) {
20d97356 1929 deflateEnd(&strm);
8f1efd00
KW
1930 ret = -EINVAL;
1931 goto fail;
20d97356
BS
1932 }
1933 out_len = strm.next_out - out_buf;
1934
1935 deflateEnd(&strm);
1936
1937 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1938 /* could not compress: write normal cluster */
8f1efd00
KW
1939 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1940 if (ret < 0) {
1941 goto fail;
1942 }
20d97356
BS
1943 } else {
1944 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1945 sector_num << 9, out_len);
8f1efd00
KW
1946 if (!cluster_offset) {
1947 ret = -EIO;
1948 goto fail;
1949 }
20d97356 1950 cluster_offset &= s->cluster_offset_mask;
cf93980e 1951
231bb267 1952 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
cf93980e
HR
1953 if (ret < 0) {
1954 goto fail;
1955 }
1956
66f82cee 1957 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
8f1efd00
KW
1958 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1959 if (ret < 0) {
1960 goto fail;
20d97356
BS
1961 }
1962 }
1963
8f1efd00
KW
1964 ret = 0;
1965fail:
7267c094 1966 g_free(out_buf);
8f1efd00 1967 return ret;
20d97356
BS
1968}
1969
a968168c 1970static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 1971{
29c1a730
KW
1972 BDRVQcowState *s = bs->opaque;
1973 int ret;
1974
8b94ff85 1975 qemu_co_mutex_lock(&s->lock);
29c1a730
KW
1976 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1977 if (ret < 0) {
c95de7e2 1978 qemu_co_mutex_unlock(&s->lock);
8b94ff85 1979 return ret;
29c1a730
KW
1980 }
1981
bfe8043e
SH
1982 if (qcow2_need_accurate_refcounts(s)) {
1983 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1984 if (ret < 0) {
1985 qemu_co_mutex_unlock(&s->lock);
1986 return ret;
1987 }
29c1a730 1988 }
8b94ff85 1989 qemu_co_mutex_unlock(&s->lock);
29c1a730 1990
eb489bb1
KW
1991 return 0;
1992}
1993
7c80ab3f 1994static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356
BS
1995{
1996 BDRVQcowState *s = bs->opaque;
95de6d70
PB
1997 bdi->unallocated_blocks_are_zero = true;
1998 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
20d97356 1999 bdi->cluster_size = s->cluster_size;
7c80ab3f 2000 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
2001 return 0;
2002}
2003
37764dfb
HR
2004static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2005{
2006 BDRVQcowState *s = bs->opaque;
2007 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2008
2009 *spec_info = (ImageInfoSpecific){
2010 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2011 {
2012 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2013 },
2014 };
2015 if (s->qcow_version == 2) {
2016 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2017 .compat = g_strdup("0.10"),
2018 };
2019 } else if (s->qcow_version == 3) {
2020 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2021 .compat = g_strdup("1.1"),
2022 .lazy_refcounts = s->compatible_features &
2023 QCOW2_COMPAT_LAZY_REFCOUNTS,
2024 .has_lazy_refcounts = true,
2025 };
2026 }
2027
2028 return spec_info;
2029}
2030
20d97356
BS
2031#if 0
2032static void dump_refcounts(BlockDriverState *bs)
2033{
2034 BDRVQcowState *s = bs->opaque;
2035 int64_t nb_clusters, k, k1, size;
2036 int refcount;
2037
66f82cee 2038 size = bdrv_getlength(bs->file);
20d97356
BS
2039 nb_clusters = size_to_clusters(s, size);
2040 for(k = 0; k < nb_clusters;) {
2041 k1 = k;
2042 refcount = get_refcount(bs, k);
2043 k++;
2044 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2045 k++;
0bfcd599
BS
2046 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2047 k - k1);
20d97356
BS
2048 }
2049}
2050#endif
2051
cf8074b3
KW
2052static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2053 int64_t pos)
20d97356
BS
2054{
2055 BDRVQcowState *s = bs->opaque;
eedff66f 2056 int64_t total_sectors = bs->total_sectors;
20d97356 2057 int growable = bs->growable;
6e13610a 2058 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2059 int ret;
2060
66f82cee 2061 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
20d97356 2062 bs->growable = 1;
6e13610a 2063 bs->zero_beyond_eof = false;
8d3b1a2d 2064 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
20d97356 2065 bs->growable = growable;
6e13610a 2066 bs->zero_beyond_eof = zero_beyond_eof;
20d97356 2067
eedff66f
HR
2068 /* bdrv_co_do_writev will have increased the total_sectors value to include
2069 * the VM state - the VM state is however not an actual part of the block
2070 * device, therefore, we need to restore the old value. */
2071 bs->total_sectors = total_sectors;
2072
20d97356
BS
2073 return ret;
2074}
2075
7c80ab3f
JS
2076static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2077 int64_t pos, int size)
20d97356
BS
2078{
2079 BDRVQcowState *s = bs->opaque;
2080 int growable = bs->growable;
0d51b4de 2081 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
2082 int ret;
2083
66f82cee 2084 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
20d97356 2085 bs->growable = 1;
0d51b4de 2086 bs->zero_beyond_eof = false;
7c80ab3f 2087 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
20d97356 2088 bs->growable = growable;
0d51b4de 2089 bs->zero_beyond_eof = zero_beyond_eof;
20d97356
BS
2090
2091 return ret;
2092}
2093
9296b3ed
HR
2094/*
2095 * Downgrades an image's version. To achieve this, any incompatible features
2096 * have to be removed.
2097 */
2098static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2099{
2100 BDRVQcowState *s = bs->opaque;
2101 int current_version = s->qcow_version;
2102 int ret;
2103
2104 if (target_version == current_version) {
2105 return 0;
2106 } else if (target_version > current_version) {
2107 return -EINVAL;
2108 } else if (target_version != 2) {
2109 return -EINVAL;
2110 }
2111
2112 if (s->refcount_order != 4) {
2113 /* we would have to convert the image to a refcount_order == 4 image
2114 * here; however, since qemu (at the time of writing this) does not
2115 * support anything different than 4 anyway, there is no point in doing
2116 * so right now; however, we should error out (if qemu supports this in
2117 * the future and this code has not been adapted) */
9e3f0892 2118 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
9296b3ed
HR
2119 "currently not supported.");
2120 return -ENOTSUP;
2121 }
2122
2123 /* clear incompatible features */
2124 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2125 ret = qcow2_mark_clean(bs);
2126 if (ret < 0) {
2127 return ret;
2128 }
2129 }
2130
2131 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2132 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2133 * best thing to do anyway */
2134
2135 if (s->incompatible_features) {
2136 return -ENOTSUP;
2137 }
2138
2139 /* since we can ignore compatible features, we can set them to 0 as well */
2140 s->compatible_features = 0;
2141 /* if lazy refcounts have been used, they have already been fixed through
2142 * clearing the dirty flag */
2143
2144 /* clearing autoclear features is trivial */
2145 s->autoclear_features = 0;
2146
2147 ret = qcow2_expand_zero_clusters(bs);
2148 if (ret < 0) {
2149 return ret;
2150 }
2151
2152 s->qcow_version = target_version;
2153 ret = qcow2_update_header(bs);
2154 if (ret < 0) {
2155 s->qcow_version = current_version;
2156 return ret;
2157 }
2158 return 0;
2159}
2160
2161static int qcow2_amend_options(BlockDriverState *bs,
2162 QEMUOptionParameter *options)
2163{
2164 BDRVQcowState *s = bs->opaque;
2165 int old_version = s->qcow_version, new_version = old_version;
2166 uint64_t new_size = 0;
2167 const char *backing_file = NULL, *backing_format = NULL;
2168 bool lazy_refcounts = s->use_lazy_refcounts;
2169 int ret;
2170 int i;
2171
2172 for (i = 0; options[i].name; i++)
2173 {
2174 if (!options[i].assigned) {
2175 /* only change explicitly defined options */
2176 continue;
2177 }
2178
2179 if (!strcmp(options[i].name, "compat")) {
2180 if (!options[i].value.s) {
2181 /* preserve default */
2182 } else if (!strcmp(options[i].value.s, "0.10")) {
2183 new_version = 2;
2184 } else if (!strcmp(options[i].value.s, "1.1")) {
2185 new_version = 3;
2186 } else {
2187 fprintf(stderr, "Unknown compatibility level %s.\n",
2188 options[i].value.s);
2189 return -EINVAL;
2190 }
2191 } else if (!strcmp(options[i].name, "preallocation")) {
2192 fprintf(stderr, "Cannot change preallocation mode.\n");
2193 return -ENOTSUP;
2194 } else if (!strcmp(options[i].name, "size")) {
2195 new_size = options[i].value.n;
2196 } else if (!strcmp(options[i].name, "backing_file")) {
2197 backing_file = options[i].value.s;
2198 } else if (!strcmp(options[i].name, "backing_fmt")) {
2199 backing_format = options[i].value.s;
2200 } else if (!strcmp(options[i].name, "encryption")) {
2201 if ((options[i].value.n != !!s->crypt_method)) {
2202 fprintf(stderr, "Changing the encryption flag is not "
2203 "supported.\n");
2204 return -ENOTSUP;
2205 }
2206 } else if (!strcmp(options[i].name, "cluster_size")) {
2207 if (options[i].value.n != s->cluster_size) {
2208 fprintf(stderr, "Changing the cluster size is not "
2209 "supported.\n");
2210 return -ENOTSUP;
2211 }
2212 } else if (!strcmp(options[i].name, "lazy_refcounts")) {
2213 lazy_refcounts = options[i].value.n;
2214 } else {
2215 /* if this assertion fails, this probably means a new option was
2216 * added without having it covered here */
2217 assert(false);
2218 }
2219 }
2220
2221 if (new_version != old_version) {
2222 if (new_version > old_version) {
2223 /* Upgrade */
2224 s->qcow_version = new_version;
2225 ret = qcow2_update_header(bs);
2226 if (ret < 0) {
2227 s->qcow_version = old_version;
2228 return ret;
2229 }
2230 } else {
2231 ret = qcow2_downgrade(bs, new_version);
2232 if (ret < 0) {
2233 return ret;
2234 }
2235 }
2236 }
2237
2238 if (backing_file || backing_format) {
2239 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2240 backing_format ?: bs->backing_format);
2241 if (ret < 0) {
2242 return ret;
2243 }
2244 }
2245
2246 if (s->use_lazy_refcounts != lazy_refcounts) {
2247 if (lazy_refcounts) {
2248 if (s->qcow_version < 3) {
2249 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2250 "level 1.1 and above (use compat=1.1 or greater)\n");
2251 return -EINVAL;
2252 }
2253 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2254 ret = qcow2_update_header(bs);
2255 if (ret < 0) {
2256 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2257 return ret;
2258 }
2259 s->use_lazy_refcounts = true;
2260 } else {
2261 /* make image clean first */
2262 ret = qcow2_mark_clean(bs);
2263 if (ret < 0) {
2264 return ret;
2265 }
2266 /* now disallow lazy refcounts */
2267 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2268 ret = qcow2_update_header(bs);
2269 if (ret < 0) {
2270 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2271 return ret;
2272 }
2273 s->use_lazy_refcounts = false;
2274 }
2275 }
2276
2277 if (new_size) {
2278 ret = bdrv_truncate(bs, new_size);
2279 if (ret < 0) {
2280 return ret;
2281 }
2282 }
2283
2284 return 0;
2285}
2286
7c80ab3f 2287static QEMUOptionParameter qcow2_create_options[] = {
20d97356
BS
2288 {
2289 .name = BLOCK_OPT_SIZE,
2290 .type = OPT_SIZE,
2291 .help = "Virtual disk size"
2292 },
6744cbab
KW
2293 {
2294 .name = BLOCK_OPT_COMPAT_LEVEL,
2295 .type = OPT_STRING,
2296 .help = "Compatibility level (0.10 or 1.1)"
2297 },
20d97356
BS
2298 {
2299 .name = BLOCK_OPT_BACKING_FILE,
2300 .type = OPT_STRING,
2301 .help = "File name of a base image"
2302 },
2303 {
2304 .name = BLOCK_OPT_BACKING_FMT,
2305 .type = OPT_STRING,
2306 .help = "Image format of the base image"
2307 },
2308 {
2309 .name = BLOCK_OPT_ENCRYPT,
2310 .type = OPT_FLAG,
2311 .help = "Encrypt the image"
2312 },
2313 {
2314 .name = BLOCK_OPT_CLUSTER_SIZE,
2315 .type = OPT_SIZE,
99cce9fa
KW
2316 .help = "qcow2 cluster size",
2317 .value = { .n = DEFAULT_CLUSTER_SIZE },
20d97356
BS
2318 },
2319 {
2320 .name = BLOCK_OPT_PREALLOC,
2321 .type = OPT_STRING,
2322 .help = "Preallocation mode (allowed values: off, metadata)"
2323 },
bfe8043e
SH
2324 {
2325 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2326 .type = OPT_FLAG,
2327 .help = "Postpone refcount updates",
2328 },
20d97356
BS
2329 { NULL }
2330};
2331
2332static BlockDriver bdrv_qcow2 = {
7c80ab3f
JS
2333 .format_name = "qcow2",
2334 .instance_size = sizeof(BDRVQcowState),
2335 .bdrv_probe = qcow2_probe,
2336 .bdrv_open = qcow2_open,
2337 .bdrv_close = qcow2_close,
21d82ac9 2338 .bdrv_reopen_prepare = qcow2_reopen_prepare,
7c80ab3f 2339 .bdrv_create = qcow2_create,
3ac21627 2340 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 2341 .bdrv_co_get_block_status = qcow2_co_get_block_status,
7c80ab3f 2342 .bdrv_set_key = qcow2_set_key,
7c80ab3f 2343
c68b89ac
KW
2344 .bdrv_co_readv = qcow2_co_readv,
2345 .bdrv_co_writev = qcow2_co_writev,
eb489bb1 2346 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 2347
621f0589 2348 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
6db39ae2 2349 .bdrv_co_discard = qcow2_co_discard,
419b19d9 2350 .bdrv_truncate = qcow2_truncate,
7c80ab3f 2351 .bdrv_write_compressed = qcow2_write_compressed,
20d97356
BS
2352
2353 .bdrv_snapshot_create = qcow2_snapshot_create,
2354 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2355 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2356 .bdrv_snapshot_list = qcow2_snapshot_list,
51ef6727 2357 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
7c80ab3f 2358 .bdrv_get_info = qcow2_get_info,
37764dfb 2359 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 2360
7c80ab3f
JS
2361 .bdrv_save_vmstate = qcow2_save_vmstate,
2362 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356
BS
2363
2364 .bdrv_change_backing_file = qcow2_change_backing_file,
2365
d34682cd 2366 .bdrv_refresh_limits = qcow2_refresh_limits,
06d9260f
AL
2367 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2368
7c80ab3f
JS
2369 .create_options = qcow2_create_options,
2370 .bdrv_check = qcow2_check,
9296b3ed 2371 .bdrv_amend_options = qcow2_amend_options,
20d97356
BS
2372};
2373
5efa9d5a
AL
2374static void bdrv_qcow2_init(void)
2375{
2376 bdrv_register(&bdrv_qcow2);
2377}
2378
2379block_init(bdrv_qcow2_init);