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