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