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