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