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