]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
qcow2: Save refcount order in BDRVQcowState
[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;
55} 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,
cfcc4c62 82 uint64_t end_offset, void **p_feature_table)
9b80ddf3 83{
75bab85c 84 BDRVQcowState *s = bs->opaque;
9b80ddf3
AL
85 QCowExtension ext;
86 uint64_t offset;
75bab85c 87 int ret;
9b80ddf3
AL
88
89#ifdef DEBUG_EXT
7c80ab3f 90 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
9b80ddf3
AL
91#endif
92 offset = start_offset;
93 while (offset < end_offset) {
94
95#ifdef DEBUG_EXT
96 /* Sanity check */
97 if (offset > s->cluster_size)
7c80ab3f 98 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
9b80ddf3 99
9b2260cb 100 printf("attempting to read extended header in offset %lu\n", offset);
9b80ddf3
AL
101#endif
102
66f82cee 103 if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
7c80ab3f 104 fprintf(stderr, "qcow2_read_extension: ERROR: "
0bfcd599
BS
105 "pread fail from offset %" PRIu64 "\n",
106 offset);
9b80ddf3
AL
107 return 1;
108 }
109 be32_to_cpus(&ext.magic);
110 be32_to_cpus(&ext.len);
111 offset += sizeof(ext);
112#ifdef DEBUG_EXT
113 printf("ext.magic = 0x%x\n", ext.magic);
114#endif
64ca6aee
KW
115 if (ext.len > end_offset - offset) {
116 error_report("Header extension too large");
117 return -EINVAL;
118 }
119
9b80ddf3 120 switch (ext.magic) {
7c80ab3f 121 case QCOW2_EXT_MAGIC_END:
9b80ddf3 122 return 0;
f965509c 123
7c80ab3f 124 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
f965509c
AL
125 if (ext.len >= sizeof(bs->backing_format)) {
126 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
4c978075 127 " (>=%zu)\n",
f965509c
AL
128 ext.len, sizeof(bs->backing_format));
129 return 2;
130 }
66f82cee 131 if (bdrv_pread(bs->file, offset , bs->backing_format,
f965509c
AL
132 ext.len) != ext.len)
133 return 3;
134 bs->backing_format[ext.len] = '\0';
135#ifdef DEBUG_EXT
136 printf("Qcow2: Got format extension %s\n", bs->backing_format);
137#endif
f965509c
AL
138 break;
139
cfcc4c62
KW
140 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
141 if (p_feature_table != NULL) {
142 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
143 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
144 if (ret < 0) {
145 return ret;
146 }
147
148 *p_feature_table = feature_table;
149 }
150 break;
151
9b80ddf3 152 default:
75bab85c
KW
153 /* unknown magic - save it in case we need to rewrite the header */
154 {
155 Qcow2UnknownHeaderExtension *uext;
156
157 uext = g_malloc0(sizeof(*uext) + ext.len);
158 uext->magic = ext.magic;
159 uext->len = ext.len;
160 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
161
162 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
163 if (ret < 0) {
164 return ret;
165 }
75bab85c 166 }
9b80ddf3
AL
167 break;
168 }
fd29b4bb
KW
169
170 offset += ((ext.len + 7) & ~7);
9b80ddf3
AL
171 }
172
173 return 0;
174}
175
75bab85c
KW
176static void cleanup_unknown_header_ext(BlockDriverState *bs)
177{
178 BDRVQcowState *s = bs->opaque;
179 Qcow2UnknownHeaderExtension *uext, *next;
180
181 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
182 QLIST_REMOVE(uext, next);
183 g_free(uext);
184 }
185}
9b80ddf3 186
b9531b6e
SW
187static void GCC_FMT_ATTR(2, 3) report_unsupported(BlockDriverState *bs,
188 const char *fmt, ...)
6744cbab
KW
189{
190 char msg[64];
191 va_list ap;
192
193 va_start(ap, fmt);
194 vsnprintf(msg, sizeof(msg), fmt, ap);
195 va_end(ap);
196
197 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
198 bs->device_name, "qcow2", msg);
199}
200
cfcc4c62
KW
201static void report_unsupported_feature(BlockDriverState *bs,
202 Qcow2Feature *table, uint64_t mask)
203{
204 while (table && table->name[0] != '\0') {
205 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
206 if (mask & (1 << table->bit)) {
207 report_unsupported(bs, "%.46s",table->name);
208 mask &= ~(1 << table->bit);
209 }
210 }
211 table++;
212 }
213
214 if (mask) {
215 report_unsupported(bs, "Unknown incompatible feature: %" PRIx64, mask);
216 }
217}
218
bfe8043e
SH
219/*
220 * Sets the dirty bit and flushes afterwards if necessary.
221 *
222 * The incompatible_features bit is only set if the image file header was
223 * updated successfully. Therefore it is not required to check the return
224 * value of this function.
225 */
280d3735 226int qcow2_mark_dirty(BlockDriverState *bs)
bfe8043e
SH
227{
228 BDRVQcowState *s = bs->opaque;
229 uint64_t val;
230 int ret;
231
232 assert(s->qcow_version >= 3);
233
234 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
235 return 0; /* already dirty */
236 }
237
238 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
239 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
240 &val, sizeof(val));
241 if (ret < 0) {
242 return ret;
243 }
244 ret = bdrv_flush(bs->file);
245 if (ret < 0) {
246 return ret;
247 }
248
249 /* Only treat image as dirty if the header was updated successfully */
250 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
251 return 0;
252}
253
c61d0004
SH
254/*
255 * Clears the dirty bit and flushes before if necessary. Only call this
256 * function when there are no pending requests, it does not guard against
257 * concurrent requests dirtying the image.
258 */
259static int qcow2_mark_clean(BlockDriverState *bs)
260{
261 BDRVQcowState *s = bs->opaque;
262
263 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
264 int ret = bdrv_flush(bs);
265 if (ret < 0) {
266 return ret;
267 }
268
269 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
270 return qcow2_update_header(bs);
271 }
272 return 0;
273}
274
69c98726
HR
275/*
276 * Marks the image as corrupt.
277 */
278int qcow2_mark_corrupt(BlockDriverState *bs)
279{
280 BDRVQcowState *s = bs->opaque;
281
282 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
283 return qcow2_update_header(bs);
284}
285
286/*
287 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
288 * before if necessary.
289 */
290int qcow2_mark_consistent(BlockDriverState *bs)
291{
292 BDRVQcowState *s = bs->opaque;
293
294 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
295 int ret = bdrv_flush(bs);
296 if (ret < 0) {
297 return ret;
298 }
299
300 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
301 return qcow2_update_header(bs);
302 }
303 return 0;
304}
305
acbe5982
SH
306static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
307 BdrvCheckMode fix)
308{
309 int ret = qcow2_check_refcounts(bs, result, fix);
310 if (ret < 0) {
311 return ret;
312 }
313
314 if (fix && result->check_errors == 0 && result->corruptions == 0) {
24530f3e
HR
315 ret = qcow2_mark_clean(bs);
316 if (ret < 0) {
317 return ret;
318 }
319 return qcow2_mark_consistent(bs);
acbe5982
SH
320 }
321 return ret;
322}
323
74c4510a
KW
324static QemuOptsList qcow2_runtime_opts = {
325 .name = "qcow2",
326 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
327 .desc = {
328 {
64aa99d3 329 .name = QCOW2_OPT_LAZY_REFCOUNTS,
74c4510a
KW
330 .type = QEMU_OPT_BOOL,
331 .help = "Postpone refcount updates",
332 },
67af674e
KW
333 {
334 .name = QCOW2_OPT_DISCARD_REQUEST,
335 .type = QEMU_OPT_BOOL,
336 .help = "Pass guest discard requests to the layer below",
337 },
338 {
339 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
340 .type = QEMU_OPT_BOOL,
341 .help = "Generate discard requests when snapshot related space "
342 "is freed",
343 },
344 {
345 .name = QCOW2_OPT_DISCARD_OTHER,
346 .type = QEMU_OPT_BOOL,
347 .help = "Generate discard requests when other clusters are freed",
348 },
74c4510a
KW
349 { /* end of list */ }
350 },
351};
352
1a86938f 353static int qcow2_open(BlockDriverState *bs, QDict *options, int flags)
585f8587
FB
354{
355 BDRVQcowState *s = bs->opaque;
6d85a57e 356 int len, i, ret = 0;
585f8587 357 QCowHeader header;
74c4510a
KW
358 QemuOpts *opts;
359 Error *local_err = NULL;
9b80ddf3 360 uint64_t ext_end;
2cf7cfa1 361 uint64_t l1_vm_state_index;
585f8587 362
6d85a57e
JS
363 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
364 if (ret < 0) {
585f8587 365 goto fail;
6d85a57e 366 }
585f8587
FB
367 be32_to_cpus(&header.magic);
368 be32_to_cpus(&header.version);
369 be64_to_cpus(&header.backing_file_offset);
370 be32_to_cpus(&header.backing_file_size);
371 be64_to_cpus(&header.size);
372 be32_to_cpus(&header.cluster_bits);
373 be32_to_cpus(&header.crypt_method);
374 be64_to_cpus(&header.l1_table_offset);
375 be32_to_cpus(&header.l1_size);
376 be64_to_cpus(&header.refcount_table_offset);
377 be32_to_cpus(&header.refcount_table_clusters);
378 be64_to_cpus(&header.snapshots_offset);
379 be32_to_cpus(&header.nb_snapshots);
3b46e624 380
e8cdcec1 381 if (header.magic != QCOW_MAGIC) {
15bac0d5 382 ret = -EMEDIUMTYPE;
585f8587 383 goto fail;
6d85a57e 384 }
6744cbab
KW
385 if (header.version < 2 || header.version > 3) {
386 report_unsupported(bs, "QCOW version %d", header.version);
387 ret = -ENOTSUP;
388 goto fail;
389 }
390
391 s->qcow_version = header.version;
392
393 /* Initialise version 3 header fields */
394 if (header.version == 2) {
395 header.incompatible_features = 0;
396 header.compatible_features = 0;
397 header.autoclear_features = 0;
398 header.refcount_order = 4;
399 header.header_length = 72;
400 } else {
401 be64_to_cpus(&header.incompatible_features);
402 be64_to_cpus(&header.compatible_features);
403 be64_to_cpus(&header.autoclear_features);
404 be32_to_cpus(&header.refcount_order);
405 be32_to_cpus(&header.header_length);
406 }
407
408 if (header.header_length > sizeof(header)) {
409 s->unknown_header_fields_size = header.header_length - sizeof(header);
410 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
411 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
412 s->unknown_header_fields_size);
413 if (ret < 0) {
414 goto fail;
415 }
416 }
417
cfcc4c62
KW
418 if (header.backing_file_offset) {
419 ext_end = header.backing_file_offset;
420 } else {
421 ext_end = 1 << header.cluster_bits;
422 }
423
6744cbab
KW
424 /* Handle feature bits */
425 s->incompatible_features = header.incompatible_features;
426 s->compatible_features = header.compatible_features;
427 s->autoclear_features = header.autoclear_features;
428
c61d0004 429 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
cfcc4c62
KW
430 void *feature_table = NULL;
431 qcow2_read_extensions(bs, header.header_length, ext_end,
432 &feature_table);
433 report_unsupported_feature(bs, feature_table,
c61d0004
SH
434 s->incompatible_features &
435 ~QCOW2_INCOMPAT_MASK);
6744cbab
KW
436 ret = -ENOTSUP;
437 goto fail;
438 }
439
69c98726
HR
440 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
441 /* Corrupt images may not be written to unless they are being repaired
442 */
443 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
444 error_report("qcow2: Image is corrupt; cannot be opened "
445 "read/write.");
446 ret = -EACCES;
447 goto fail;
448 }
449 }
450
6744cbab
KW
451 /* Check support for various header values */
452 if (header.refcount_order != 4) {
453 report_unsupported(bs, "%d bit reference counts",
454 1 << header.refcount_order);
e8cdcec1
KW
455 ret = -ENOTSUP;
456 goto fail;
457 }
b6481f37 458 s->refcount_order = header.refcount_order;
6744cbab 459
d191d12d 460 if (header.cluster_bits < MIN_CLUSTER_BITS ||
6d85a57e
JS
461 header.cluster_bits > MAX_CLUSTER_BITS) {
462 ret = -EINVAL;
585f8587 463 goto fail;
6d85a57e
JS
464 }
465 if (header.crypt_method > QCOW_CRYPT_AES) {
466 ret = -EINVAL;
585f8587 467 goto fail;
6d85a57e 468 }
585f8587 469 s->crypt_method_header = header.crypt_method;
6d85a57e 470 if (s->crypt_method_header) {
585f8587 471 bs->encrypted = 1;
6d85a57e 472 }
585f8587
FB
473 s->cluster_bits = header.cluster_bits;
474 s->cluster_size = 1 << s->cluster_bits;
475 s->cluster_sectors = 1 << (s->cluster_bits - 9);
476 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
477 s->l2_size = 1 << s->l2_bits;
478 bs->total_sectors = header.size / 512;
479 s->csize_shift = (62 - (s->cluster_bits - 8));
480 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
481 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
482 s->refcount_table_offset = header.refcount_table_offset;
5fafdf24 483 s->refcount_table_size =
585f8587
FB
484 header.refcount_table_clusters << (s->cluster_bits - 3);
485
486 s->snapshots_offset = header.snapshots_offset;
487 s->nb_snapshots = header.nb_snapshots;
488
489 /* read the level 1 table */
490 s->l1_size = header.l1_size;
2cf7cfa1
KW
491
492 l1_vm_state_index = size_to_l1(s, header.size);
493 if (l1_vm_state_index > INT_MAX) {
494 ret = -EFBIG;
495 goto fail;
496 }
497 s->l1_vm_state_index = l1_vm_state_index;
498
585f8587
FB
499 /* the L1 table must contain at least enough entries to put
500 header.size bytes */
6d85a57e
JS
501 if (s->l1_size < s->l1_vm_state_index) {
502 ret = -EINVAL;
585f8587 503 goto fail;
6d85a57e 504 }
585f8587 505 s->l1_table_offset = header.l1_table_offset;
d191d12d 506 if (s->l1_size > 0) {
7267c094 507 s->l1_table = g_malloc0(
d191d12d 508 align_offset(s->l1_size * sizeof(uint64_t), 512));
6d85a57e
JS
509 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
510 s->l1_size * sizeof(uint64_t));
511 if (ret < 0) {
d191d12d 512 goto fail;
6d85a57e 513 }
d191d12d
SW
514 for(i = 0;i < s->l1_size; i++) {
515 be64_to_cpus(&s->l1_table[i]);
516 }
585f8587 517 }
29c1a730
KW
518
519 /* alloc L2 table/refcount block cache */
6af4e9ea
PB
520 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
521 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
29c1a730 522
7267c094 523 s->cluster_cache = g_malloc(s->cluster_size);
585f8587 524 /* one more sector for decompressed data alignment */
dea43a65 525 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
095a9c58 526 + 512);
585f8587 527 s->cluster_cache_offset = -1;
06d9260f 528 s->flags = flags;
3b46e624 529
6d85a57e
JS
530 ret = qcow2_refcount_init(bs);
531 if (ret != 0) {
585f8587 532 goto fail;
6d85a57e 533 }
585f8587 534
72cf2d4f 535 QLIST_INIT(&s->cluster_allocs);
0b919fae 536 QTAILQ_INIT(&s->discards);
f214978a 537
9b80ddf3 538 /* read qcow2 extensions */
cfcc4c62 539 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {
6d85a57e 540 ret = -EINVAL;
9b80ddf3 541 goto fail;
6d85a57e 542 }
9b80ddf3 543
585f8587
FB
544 /* read the backing file name */
545 if (header.backing_file_offset != 0) {
546 len = header.backing_file_size;
6d85a57e 547 if (len > 1023) {
585f8587 548 len = 1023;
6d85a57e
JS
549 }
550 ret = bdrv_pread(bs->file, header.backing_file_offset,
551 bs->backing_file, len);
552 if (ret < 0) {
585f8587 553 goto fail;
6d85a57e 554 }
585f8587
FB
555 bs->backing_file[len] = '\0';
556 }
42deb29f
KW
557
558 ret = qcow2_read_snapshots(bs);
559 if (ret < 0) {
585f8587 560 goto fail;
6d85a57e 561 }
585f8587 562
af7b708d
SH
563 /* Clear unknown autoclear feature bits */
564 if (!bs->read_only && s->autoclear_features != 0) {
565 s->autoclear_features = 0;
566 ret = qcow2_update_header(bs);
567 if (ret < 0) {
568 goto fail;
569 }
570 }
571
68d100e9
KW
572 /* Initialise locks */
573 qemu_co_mutex_init(&s->lock);
574
c61d0004 575 /* Repair image if dirty */
058f8f16
SH
576 if (!(flags & BDRV_O_CHECK) && !bs->read_only &&
577 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
c61d0004
SH
578 BdrvCheckResult result = {0};
579
acbe5982 580 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
c61d0004
SH
581 if (ret < 0) {
582 goto fail;
583 }
584 }
585
74c4510a
KW
586 /* Enable lazy_refcounts according to image and command line options */
587 opts = qemu_opts_create_nofail(&qcow2_runtime_opts);
588 qemu_opts_absorb_qdict(opts, options, &local_err);
589 if (error_is_set(&local_err)) {
590 qerror_report_err(local_err);
591 error_free(local_err);
592 ret = -EINVAL;
593 goto fail;
594 }
595
acdfb480 596 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
74c4510a
KW
597 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
598
67af674e
KW
599 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
600 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
601 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
602 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
603 flags & BDRV_O_UNMAP);
604 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
605 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
606 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
607 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
608
74c4510a
KW
609 qemu_opts_del(opts);
610
611 if (s->use_lazy_refcounts && s->qcow_version < 3) {
612 qerror_report(ERROR_CLASS_GENERIC_ERROR, "Lazy refcounts require "
613 "a qcow2 image with at least qemu 1.1 compatibility level");
614 ret = -EINVAL;
615 goto fail;
616 }
617
585f8587 618#ifdef DEBUG_ALLOC
6cbc3031
PH
619 {
620 BdrvCheckResult result = {0};
b35278f7 621 qcow2_check_refcounts(bs, &result, 0);
6cbc3031 622 }
585f8587 623#endif
6d85a57e 624 return ret;
585f8587
FB
625
626 fail:
6744cbab 627 g_free(s->unknown_header_fields);
75bab85c 628 cleanup_unknown_header_ext(bs);
ed6ccf0f
KW
629 qcow2_free_snapshots(bs);
630 qcow2_refcount_close(bs);
7267c094 631 g_free(s->l1_table);
cf93980e
HR
632 /* else pre-write overlap checks in cache_destroy may crash */
633 s->l1_table = NULL;
29c1a730
KW
634 if (s->l2_table_cache) {
635 qcow2_cache_destroy(bs, s->l2_table_cache);
636 }
7267c094 637 g_free(s->cluster_cache);
dea43a65 638 qemu_vfree(s->cluster_data);
6d85a57e 639 return ret;
585f8587
FB
640}
641
7c80ab3f 642static int qcow2_set_key(BlockDriverState *bs, const char *key)
585f8587
FB
643{
644 BDRVQcowState *s = bs->opaque;
645 uint8_t keybuf[16];
646 int len, i;
3b46e624 647
585f8587
FB
648 memset(keybuf, 0, 16);
649 len = strlen(key);
650 if (len > 16)
651 len = 16;
652 /* XXX: we could compress the chars to 7 bits to increase
653 entropy */
654 for(i = 0;i < len;i++) {
655 keybuf[i] = key[i];
656 }
657 s->crypt_method = s->crypt_method_header;
658
659 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
660 return -1;
661 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
662 return -1;
663#if 0
664 /* test */
665 {
666 uint8_t in[16];
667 uint8_t out[16];
668 uint8_t tmp[16];
669 for(i=0;i<16;i++)
670 in[i] = i;
671 AES_encrypt(in, tmp, &s->aes_encrypt_key);
672 AES_decrypt(tmp, out, &s->aes_decrypt_key);
673 for(i = 0; i < 16; i++)
674 printf(" %02x", tmp[i]);
675 printf("\n");
676 for(i = 0; i < 16; i++)
677 printf(" %02x", out[i]);
678 printf("\n");
679 }
680#endif
681 return 0;
682}
683
21d82ac9
JC
684/* We have nothing to do for QCOW2 reopen, stubs just return
685 * success */
686static int qcow2_reopen_prepare(BDRVReopenState *state,
687 BlockReopenQueue *queue, Error **errp)
688{
689 return 0;
690}
691
b6b8a333 692static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
f8a2e5e3 693 int64_t sector_num, int nb_sectors, int *pnum)
585f8587 694{
f8a2e5e3 695 BDRVQcowState *s = bs->opaque;
585f8587 696 uint64_t cluster_offset;
4bc74be9
PB
697 int index_in_cluster, ret;
698 int64_t status = 0;
585f8587 699
095a9c58 700 *pnum = nb_sectors;
f8a2e5e3 701 qemu_co_mutex_lock(&s->lock);
1c46efaa 702 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
f8a2e5e3 703 qemu_co_mutex_unlock(&s->lock);
1c46efaa 704 if (ret < 0) {
d663640c 705 return ret;
1c46efaa 706 }
095a9c58 707
4bc74be9
PB
708 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
709 !s->crypt_method) {
710 index_in_cluster = sector_num & (s->cluster_sectors - 1);
711 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
712 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
713 }
714 if (ret == QCOW2_CLUSTER_ZERO) {
715 status |= BDRV_BLOCK_ZERO;
716 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
717 status |= BDRV_BLOCK_DATA;
718 }
719 return status;
585f8587
FB
720}
721
a9465922 722/* handle reading after the end of the backing file */
bd28f835
KW
723int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
724 int64_t sector_num, int nb_sectors)
a9465922
FB
725{
726 int n1;
727 if ((sector_num + nb_sectors) <= bs->total_sectors)
728 return nb_sectors;
729 if (sector_num >= bs->total_sectors)
730 n1 = 0;
731 else
732 n1 = bs->total_sectors - sector_num;
bd28f835 733
3d9b4925 734 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
bd28f835 735
a9465922
FB
736 return n1;
737}
738
a968168c 739static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
3fc48d09 740 int remaining_sectors, QEMUIOVector *qiov)
585f8587 741{
585f8587 742 BDRVQcowState *s = bs->opaque;
a9465922 743 int index_in_cluster, n1;
68d100e9 744 int ret;
faf575c1 745 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 746 uint64_t cluster_offset = 0;
3fc48d09
FZ
747 uint64_t bytes_done = 0;
748 QEMUIOVector hd_qiov;
749 uint8_t *cluster_data = NULL;
585f8587 750
3fc48d09
FZ
751 qemu_iovec_init(&hd_qiov, qiov->niov);
752
753 qemu_co_mutex_lock(&s->lock);
754
755 while (remaining_sectors != 0) {
bd28f835 756
5ebaa27e 757 /* prepare next request */
3fc48d09 758 cur_nr_sectors = remaining_sectors;
5ebaa27e
FZ
759 if (s->crypt_method) {
760 cur_nr_sectors = MIN(cur_nr_sectors,
761 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
585f8587 762 }
5ebaa27e 763
3fc48d09 764 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
5ebaa27e 765 &cur_nr_sectors, &cluster_offset);
8af36488 766 if (ret < 0) {
3fc48d09 767 goto fail;
8af36488 768 }
bd28f835 769
3fc48d09 770 index_in_cluster = sector_num & (s->cluster_sectors - 1);
c87c0672 771
3fc48d09 772 qemu_iovec_reset(&hd_qiov);
1b093c48 773 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e
FZ
774 cur_nr_sectors * 512);
775
68d000a3
KW
776 switch (ret) {
777 case QCOW2_CLUSTER_UNALLOCATED:
5ebaa27e
FZ
778
779 if (bs->backing_hd) {
780 /* read from the base image */
3fc48d09
FZ
781 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
782 sector_num, cur_nr_sectors);
5ebaa27e
FZ
783 if (n1 > 0) {
784 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
785 qemu_co_mutex_unlock(&s->lock);
3fc48d09
FZ
786 ret = bdrv_co_readv(bs->backing_hd, sector_num,
787 n1, &hd_qiov);
5ebaa27e
FZ
788 qemu_co_mutex_lock(&s->lock);
789 if (ret < 0) {
3fc48d09 790 goto fail;
5ebaa27e
FZ
791 }
792 }
793 } else {
794 /* Note: in this case, no need to wait */
3d9b4925 795 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
5ebaa27e 796 }
68d000a3
KW
797 break;
798
6377af48 799 case QCOW2_CLUSTER_ZERO:
3d9b4925 800 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
6377af48
KW
801 break;
802
68d000a3 803 case QCOW2_CLUSTER_COMPRESSED:
5ebaa27e
FZ
804 /* add AIO support for compressed blocks ? */
805 ret = qcow2_decompress_cluster(bs, cluster_offset);
806 if (ret < 0) {
3fc48d09 807 goto fail;
bd28f835
KW
808 }
809
03396148 810 qemu_iovec_from_buf(&hd_qiov, 0,
5ebaa27e 811 s->cluster_cache + index_in_cluster * 512,
faf575c1 812 512 * cur_nr_sectors);
68d000a3
KW
813 break;
814
815 case QCOW2_CLUSTER_NORMAL:
5ebaa27e 816 if ((cluster_offset & 511) != 0) {
3fc48d09
FZ
817 ret = -EIO;
818 goto fail;
5ebaa27e 819 }
bd28f835 820
5ebaa27e
FZ
821 if (s->crypt_method) {
822 /*
823 * For encrypted images, read everything into a temporary
824 * contiguous buffer on which the AES functions can work.
825 */
3fc48d09
FZ
826 if (!cluster_data) {
827 cluster_data =
dea43a65 828 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
5ebaa27e
FZ
829 }
830
831 assert(cur_nr_sectors <=
832 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
3fc48d09
FZ
833 qemu_iovec_reset(&hd_qiov);
834 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
835 512 * cur_nr_sectors);
836 }
837
838 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
839 qemu_co_mutex_unlock(&s->lock);
840 ret = bdrv_co_readv(bs->file,
841 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 842 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
843 qemu_co_mutex_lock(&s->lock);
844 if (ret < 0) {
3fc48d09 845 goto fail;
5ebaa27e
FZ
846 }
847 if (s->crypt_method) {
3fc48d09
FZ
848 qcow2_encrypt_sectors(s, sector_num, cluster_data,
849 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
03396148
MT
850 qemu_iovec_from_buf(qiov, bytes_done,
851 cluster_data, 512 * cur_nr_sectors);
5ebaa27e 852 }
68d000a3
KW
853 break;
854
855 default:
856 g_assert_not_reached();
857 ret = -EIO;
858 goto fail;
faf575c1 859 }
f141eafe 860
3fc48d09
FZ
861 remaining_sectors -= cur_nr_sectors;
862 sector_num += cur_nr_sectors;
863 bytes_done += cur_nr_sectors * 512;
5ebaa27e 864 }
3fc48d09 865 ret = 0;
faf575c1 866
3fc48d09 867fail:
68d100e9 868 qemu_co_mutex_unlock(&s->lock);
42496d62 869
3fc48d09 870 qemu_iovec_destroy(&hd_qiov);
dea43a65 871 qemu_vfree(cluster_data);
68d100e9
KW
872
873 return ret;
585f8587
FB
874}
875
a968168c 876static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
3fc48d09
FZ
877 int64_t sector_num,
878 int remaining_sectors,
879 QEMUIOVector *qiov)
585f8587 880{
585f8587 881 BDRVQcowState *s = bs->opaque;
585f8587 882 int index_in_cluster;
095a9c58 883 int n_end;
68d100e9 884 int ret;
faf575c1 885 int cur_nr_sectors; /* number of sectors in current iteration */
c2bdd990 886 uint64_t cluster_offset;
3fc48d09
FZ
887 QEMUIOVector hd_qiov;
888 uint64_t bytes_done = 0;
889 uint8_t *cluster_data = NULL;
8d2497c3 890 QCowL2Meta *l2meta = NULL;
c2271403 891
3cce16f4
KW
892 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
893 remaining_sectors);
894
3fc48d09
FZ
895 qemu_iovec_init(&hd_qiov, qiov->niov);
896
897 s->cluster_cache_offset = -1; /* disable compressed cache */
3b46e624 898
3fc48d09
FZ
899 qemu_co_mutex_lock(&s->lock);
900
901 while (remaining_sectors != 0) {
902
f50f88b9 903 l2meta = NULL;
cf5c1a23 904
3cce16f4 905 trace_qcow2_writev_start_part(qemu_coroutine_self());
3fc48d09
FZ
906 index_in_cluster = sector_num & (s->cluster_sectors - 1);
907 n_end = index_in_cluster + remaining_sectors;
5ebaa27e
FZ
908 if (s->crypt_method &&
909 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
910 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
911 }
095a9c58 912
3fc48d09 913 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
f50f88b9 914 index_in_cluster, n_end, &cur_nr_sectors, &cluster_offset, &l2meta);
5ebaa27e 915 if (ret < 0) {
3fc48d09 916 goto fail;
5ebaa27e 917 }
148da7ea 918
5ebaa27e 919 assert((cluster_offset & 511) == 0);
148da7ea 920
3fc48d09 921 qemu_iovec_reset(&hd_qiov);
1b093c48 922 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
5ebaa27e 923 cur_nr_sectors * 512);
6f5f060b 924
5ebaa27e 925 if (s->crypt_method) {
3fc48d09 926 if (!cluster_data) {
dea43a65 927 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
5ebaa27e
FZ
928 s->cluster_size);
929 }
6f5f060b 930
3fc48d09 931 assert(hd_qiov.size <=
5ebaa27e 932 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
d5e6b161 933 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
6f5f060b 934
3fc48d09
FZ
935 qcow2_encrypt_sectors(s, sector_num, cluster_data,
936 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
6f5f060b 937
3fc48d09
FZ
938 qemu_iovec_reset(&hd_qiov);
939 qemu_iovec_add(&hd_qiov, cluster_data,
5ebaa27e
FZ
940 cur_nr_sectors * 512);
941 }
6f5f060b 942
cf93980e
HR
943 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
944 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
945 cur_nr_sectors * BDRV_SECTOR_SIZE);
946 if (ret < 0) {
947 goto fail;
948 }
949
5ebaa27e 950 qemu_co_mutex_unlock(&s->lock);
67a7a0eb 951 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
3cce16f4
KW
952 trace_qcow2_writev_data(qemu_coroutine_self(),
953 (cluster_offset >> 9) + index_in_cluster);
5ebaa27e
FZ
954 ret = bdrv_co_writev(bs->file,
955 (cluster_offset >> 9) + index_in_cluster,
3fc48d09 956 cur_nr_sectors, &hd_qiov);
5ebaa27e
FZ
957 qemu_co_mutex_lock(&s->lock);
958 if (ret < 0) {
3fc48d09 959 goto fail;
5ebaa27e 960 }
f141eafe 961
88c6588c
KW
962 while (l2meta != NULL) {
963 QCowL2Meta *next;
964
f50f88b9
KW
965 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
966 if (ret < 0) {
967 goto fail;
968 }
faf575c1 969
4e95314e
KW
970 /* Take the request off the list of running requests */
971 if (l2meta->nb_clusters != 0) {
972 QLIST_REMOVE(l2meta, next_in_flight);
973 }
974
4e95314e 975 qemu_co_queue_restart_all(&l2meta->dependent_requests);
4e95314e 976
88c6588c 977 next = l2meta->next;
f50f88b9 978 g_free(l2meta);
88c6588c 979 l2meta = next;
f50f88b9 980 }
0fa9131a 981
3fc48d09
FZ
982 remaining_sectors -= cur_nr_sectors;
983 sector_num += cur_nr_sectors;
984 bytes_done += cur_nr_sectors * 512;
3cce16f4 985 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
5ebaa27e 986 }
3fc48d09 987 ret = 0;
faf575c1 988
3fc48d09 989fail:
4e95314e
KW
990 qemu_co_mutex_unlock(&s->lock);
991
88c6588c
KW
992 while (l2meta != NULL) {
993 QCowL2Meta *next;
994
4e95314e
KW
995 if (l2meta->nb_clusters != 0) {
996 QLIST_REMOVE(l2meta, next_in_flight);
997 }
998 qemu_co_queue_restart_all(&l2meta->dependent_requests);
88c6588c
KW
999
1000 next = l2meta->next;
cf5c1a23 1001 g_free(l2meta);
88c6588c 1002 l2meta = next;
cf5c1a23 1003 }
0fa9131a 1004
3fc48d09 1005 qemu_iovec_destroy(&hd_qiov);
dea43a65 1006 qemu_vfree(cluster_data);
3cce16f4 1007 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 1008
68d100e9 1009 return ret;
585f8587
FB
1010}
1011
7c80ab3f 1012static void qcow2_close(BlockDriverState *bs)
585f8587
FB
1013{
1014 BDRVQcowState *s = bs->opaque;
7267c094 1015 g_free(s->l1_table);
cf93980e
HR
1016 /* else pre-write overlap checks in cache_destroy may crash */
1017 s->l1_table = NULL;
29c1a730
KW
1018
1019 qcow2_cache_flush(bs, s->l2_table_cache);
1020 qcow2_cache_flush(bs, s->refcount_block_cache);
1021
c61d0004
SH
1022 qcow2_mark_clean(bs);
1023
29c1a730
KW
1024 qcow2_cache_destroy(bs, s->l2_table_cache);
1025 qcow2_cache_destroy(bs, s->refcount_block_cache);
1026
6744cbab 1027 g_free(s->unknown_header_fields);
75bab85c 1028 cleanup_unknown_header_ext(bs);
6744cbab 1029
7267c094 1030 g_free(s->cluster_cache);
dea43a65 1031 qemu_vfree(s->cluster_data);
ed6ccf0f 1032 qcow2_refcount_close(bs);
28c1202b 1033 qcow2_free_snapshots(bs);
585f8587
FB
1034}
1035
06d9260f
AL
1036static void qcow2_invalidate_cache(BlockDriverState *bs)
1037{
1038 BDRVQcowState *s = bs->opaque;
1039 int flags = s->flags;
1040 AES_KEY aes_encrypt_key;
1041 AES_KEY aes_decrypt_key;
1042 uint32_t crypt_method = 0;
acdfb480 1043 QDict *options;
06d9260f
AL
1044
1045 /*
1046 * Backing files are read-only which makes all of their metadata immutable,
1047 * that means we don't have to worry about reopening them here.
1048 */
1049
1050 if (s->crypt_method) {
1051 crypt_method = s->crypt_method;
1052 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1053 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1054 }
1055
1056 qcow2_close(bs);
1057
acdfb480
KW
1058 options = qdict_new();
1059 qdict_put(options, QCOW2_OPT_LAZY_REFCOUNTS,
1060 qbool_from_int(s->use_lazy_refcounts));
1061
06d9260f 1062 memset(s, 0, sizeof(BDRVQcowState));
acdfb480
KW
1063 qcow2_open(bs, options, flags);
1064
1065 QDECREF(options);
06d9260f
AL
1066
1067 if (crypt_method) {
1068 s->crypt_method = crypt_method;
1069 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1070 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1071 }
1072}
1073
e24e49e6
KW
1074static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1075 size_t len, size_t buflen)
1076{
1077 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1078 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1079
1080 if (buflen < ext_len) {
1081 return -ENOSPC;
1082 }
1083
1084 *ext_backing_fmt = (QCowExtension) {
1085 .magic = cpu_to_be32(magic),
1086 .len = cpu_to_be32(len),
1087 };
1088 memcpy(buf + sizeof(QCowExtension), s, len);
1089
1090 return ext_len;
1091}
1092
756e6736 1093/*
e24e49e6
KW
1094 * Updates the qcow2 header, including the variable length parts of it, i.e.
1095 * the backing file name and all extensions. qcow2 was not designed to allow
1096 * such changes, so if we run out of space (we can only use the first cluster)
1097 * this function may fail.
756e6736
KW
1098 *
1099 * Returns 0 on success, -errno in error cases.
1100 */
e24e49e6 1101int qcow2_update_header(BlockDriverState *bs)
756e6736 1102{
756e6736 1103 BDRVQcowState *s = bs->opaque;
e24e49e6
KW
1104 QCowHeader *header;
1105 char *buf;
1106 size_t buflen = s->cluster_size;
756e6736 1107 int ret;
e24e49e6
KW
1108 uint64_t total_size;
1109 uint32_t refcount_table_clusters;
6744cbab 1110 size_t header_length;
75bab85c 1111 Qcow2UnknownHeaderExtension *uext;
756e6736 1112
e24e49e6 1113 buf = qemu_blockalign(bs, buflen);
756e6736 1114
e24e49e6
KW
1115 /* Header structure */
1116 header = (QCowHeader*) buf;
756e6736 1117
e24e49e6
KW
1118 if (buflen < sizeof(*header)) {
1119 ret = -ENOSPC;
1120 goto fail;
756e6736
KW
1121 }
1122
6744cbab 1123 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
1124 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1125 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1126
1127 *header = (QCowHeader) {
6744cbab 1128 /* Version 2 fields */
e24e49e6 1129 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 1130 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
1131 .backing_file_offset = 0,
1132 .backing_file_size = 0,
1133 .cluster_bits = cpu_to_be32(s->cluster_bits),
1134 .size = cpu_to_be64(total_size),
1135 .crypt_method = cpu_to_be32(s->crypt_method_header),
1136 .l1_size = cpu_to_be32(s->l1_size),
1137 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1138 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1139 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1140 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1141 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
1142
1143 /* Version 3 fields */
1144 .incompatible_features = cpu_to_be64(s->incompatible_features),
1145 .compatible_features = cpu_to_be64(s->compatible_features),
1146 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 1147 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 1148 .header_length = cpu_to_be32(header_length),
e24e49e6 1149 };
756e6736 1150
6744cbab
KW
1151 /* For older versions, write a shorter header */
1152 switch (s->qcow_version) {
1153 case 2:
1154 ret = offsetof(QCowHeader, incompatible_features);
1155 break;
1156 case 3:
1157 ret = sizeof(*header);
1158 break;
1159 default:
b6c14762
JM
1160 ret = -EINVAL;
1161 goto fail;
6744cbab
KW
1162 }
1163
1164 buf += ret;
1165 buflen -= ret;
1166 memset(buf, 0, buflen);
1167
1168 /* Preserve any unknown field in the header */
1169 if (s->unknown_header_fields_size) {
1170 if (buflen < s->unknown_header_fields_size) {
1171 ret = -ENOSPC;
1172 goto fail;
1173 }
1174
1175 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1176 buf += s->unknown_header_fields_size;
1177 buflen -= s->unknown_header_fields_size;
1178 }
756e6736 1179
e24e49e6
KW
1180 /* Backing file format header extension */
1181 if (*bs->backing_format) {
1182 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1183 bs->backing_format, strlen(bs->backing_format),
1184 buflen);
1185 if (ret < 0) {
1186 goto fail;
756e6736
KW
1187 }
1188
e24e49e6
KW
1189 buf += ret;
1190 buflen -= ret;
756e6736
KW
1191 }
1192
cfcc4c62
KW
1193 /* Feature table */
1194 Qcow2Feature features[] = {
c61d0004
SH
1195 {
1196 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1197 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1198 .name = "dirty bit",
1199 },
69c98726
HR
1200 {
1201 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1202 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1203 .name = "corrupt bit",
1204 },
bfe8043e
SH
1205 {
1206 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1207 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1208 .name = "lazy refcounts",
1209 },
cfcc4c62
KW
1210 };
1211
1212 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1213 features, sizeof(features), buflen);
1214 if (ret < 0) {
1215 goto fail;
1216 }
1217 buf += ret;
1218 buflen -= ret;
1219
75bab85c
KW
1220 /* Keep unknown header extensions */
1221 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1222 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1223 if (ret < 0) {
1224 goto fail;
1225 }
1226
1227 buf += ret;
1228 buflen -= ret;
1229 }
1230
e24e49e6
KW
1231 /* End of header extensions */
1232 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
1233 if (ret < 0) {
1234 goto fail;
1235 }
1236
e24e49e6
KW
1237 buf += ret;
1238 buflen -= ret;
756e6736 1239
e24e49e6
KW
1240 /* Backing file name */
1241 if (*bs->backing_file) {
1242 size_t backing_file_len = strlen(bs->backing_file);
1243
1244 if (buflen < backing_file_len) {
1245 ret = -ENOSPC;
1246 goto fail;
1247 }
1248
00ea1881 1249 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e24e49e6
KW
1250 strncpy(buf, bs->backing_file, buflen);
1251
1252 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1253 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
1254 }
1255
e24e49e6
KW
1256 /* Write the new header */
1257 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
1258 if (ret < 0) {
1259 goto fail;
1260 }
1261
1262 ret = 0;
1263fail:
e24e49e6 1264 qemu_vfree(header);
756e6736
KW
1265 return ret;
1266}
1267
1268static int qcow2_change_backing_file(BlockDriverState *bs,
1269 const char *backing_file, const char *backing_fmt)
1270{
e24e49e6
KW
1271 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1272 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1273
1274 return qcow2_update_header(bs);
756e6736
KW
1275}
1276
a35e1c17
KW
1277static int preallocate(BlockDriverState *bs)
1278{
a35e1c17
KW
1279 uint64_t nb_sectors;
1280 uint64_t offset;
060bee89 1281 uint64_t host_offset = 0;
a35e1c17 1282 int num;
148da7ea 1283 int ret;
f50f88b9 1284 QCowL2Meta *meta;
a35e1c17
KW
1285
1286 nb_sectors = bdrv_getlength(bs) >> 9;
1287 offset = 0;
1288
1289 while (nb_sectors) {
1290 num = MIN(nb_sectors, INT_MAX >> 9);
060bee89
KW
1291 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num,
1292 &host_offset, &meta);
148da7ea 1293 if (ret < 0) {
19dbcbf7 1294 return ret;
a35e1c17
KW
1295 }
1296
f50f88b9 1297 ret = qcow2_alloc_cluster_link_l2(bs, meta);
19dbcbf7 1298 if (ret < 0) {
6cfcb9b8
KW
1299 qcow2_free_any_clusters(bs, meta->alloc_offset, meta->nb_clusters,
1300 QCOW2_DISCARD_NEVER);
19dbcbf7 1301 return ret;
a35e1c17
KW
1302 }
1303
f214978a
KW
1304 /* There are no dependent requests, but we need to remove our request
1305 * from the list of in-flight requests */
f50f88b9 1306 if (meta != NULL) {
4e95314e 1307 QLIST_REMOVE(meta, next_in_flight);
f50f88b9 1308 }
f214978a 1309
a35e1c17
KW
1310 /* TODO Preallocate data if requested */
1311
1312 nb_sectors -= num;
1313 offset += num << 9;
1314 }
1315
1316 /*
1317 * It is expected that the image file is large enough to actually contain
1318 * all of the allocated clusters (otherwise we get failing reads after
1319 * EOF). Extend the image to the last allocated sector.
1320 */
060bee89 1321 if (host_offset != 0) {
ea80b906
KW
1322 uint8_t buf[512];
1323 memset(buf, 0, 512);
060bee89 1324 ret = bdrv_write(bs->file, (host_offset >> 9) + num - 1, buf, 1);
19dbcbf7
KW
1325 if (ret < 0) {
1326 return ret;
1327 }
a35e1c17
KW
1328 }
1329
1330 return 0;
1331}
1332
7c80ab3f
JS
1333static int qcow2_create2(const char *filename, int64_t total_size,
1334 const char *backing_file, const char *backing_format,
1335 int flags, size_t cluster_size, int prealloc,
6744cbab 1336 QEMUOptionParameter *options, int version)
a9420734 1337{
9b2260cb 1338 /* Calculate cluster_bits */
a9420734
KW
1339 int cluster_bits;
1340 cluster_bits = ffs(cluster_size) - 1;
1341 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1342 (1 << cluster_bits) != cluster_size)
1343 {
1344 error_report(
6daf194d 1345 "Cluster size must be a power of two between %d and %dk",
a9420734
KW
1346 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1347 return -EINVAL;
1348 }
1349
1350 /*
1351 * Open the image file and write a minimal qcow2 header.
1352 *
1353 * We keep things simple and start with a zero-sized image. We also
1354 * do without refcount blocks or a L1 table for now. We'll fix the
1355 * inconsistency later.
1356 *
1357 * We do need a refcount table because growing the refcount table means
1358 * allocating two new refcount blocks - the seconds of which would be at
1359 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1360 * size for any qcow2 image.
1361 */
1362 BlockDriverState* bs;
1363 QCowHeader header;
1364 uint8_t* refcount_table;
1365 int ret;
1366
1367 ret = bdrv_create_file(filename, options);
1368 if (ret < 0) {
1369 return ret;
1370 }
1371
787e4a85 1372 ret = bdrv_file_open(&bs, filename, NULL, BDRV_O_RDWR);
a9420734
KW
1373 if (ret < 0) {
1374 return ret;
1375 }
1376
1377 /* Write the header */
1378 memset(&header, 0, sizeof(header));
1379 header.magic = cpu_to_be32(QCOW_MAGIC);
6744cbab 1380 header.version = cpu_to_be32(version);
a9420734
KW
1381 header.cluster_bits = cpu_to_be32(cluster_bits);
1382 header.size = cpu_to_be64(0);
1383 header.l1_table_offset = cpu_to_be64(0);
1384 header.l1_size = cpu_to_be32(0);
1385 header.refcount_table_offset = cpu_to_be64(cluster_size);
1386 header.refcount_table_clusters = cpu_to_be32(1);
6744cbab
KW
1387 header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT);
1388 header.header_length = cpu_to_be32(sizeof(header));
a9420734
KW
1389
1390 if (flags & BLOCK_FLAG_ENCRYPT) {
1391 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1392 } else {
1393 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1394 }
1395
bfe8043e
SH
1396 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1397 header.compatible_features |=
1398 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1399 }
1400
a9420734
KW
1401 ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
1402 if (ret < 0) {
1403 goto out;
1404 }
1405
1406 /* Write an empty refcount table */
7267c094 1407 refcount_table = g_malloc0(cluster_size);
a9420734 1408 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
7267c094 1409 g_free(refcount_table);
a9420734
KW
1410
1411 if (ret < 0) {
1412 goto out;
1413 }
1414
1415 bdrv_close(bs);
1416
1417 /*
1418 * And now open the image and make it consistent first (i.e. increase the
1419 * refcount of the cluster that is occupied by the header and the refcount
1420 * table)
1421 */
1422 BlockDriver* drv = bdrv_find_format("qcow2");
1423 assert(drv != NULL);
de9c0cec 1424 ret = bdrv_open(bs, filename, NULL,
e1a7107f 1425 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv);
a9420734
KW
1426 if (ret < 0) {
1427 goto out;
1428 }
1429
1430 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1431 if (ret < 0) {
1432 goto out;
1433
1434 } else if (ret != 0) {
1435 error_report("Huh, first cluster in empty image is already in use?");
1436 abort();
1437 }
1438
1439 /* Okay, now that we have a valid image, let's give it the right size */
1440 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1441 if (ret < 0) {
1442 goto out;
1443 }
1444
1445 /* Want a backing file? There you go.*/
1446 if (backing_file) {
1447 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1448 if (ret < 0) {
1449 goto out;
1450 }
1451 }
1452
1453 /* And if we're supposed to preallocate metadata, do that now */
1454 if (prealloc) {
15552c4a
ZYW
1455 BDRVQcowState *s = bs->opaque;
1456 qemu_co_mutex_lock(&s->lock);
a9420734 1457 ret = preallocate(bs);
15552c4a 1458 qemu_co_mutex_unlock(&s->lock);
a9420734
KW
1459 if (ret < 0) {
1460 goto out;
1461 }
1462 }
1463
1464 ret = 0;
1465out:
4f6fd349 1466 bdrv_unref(bs);
a9420734
KW
1467 return ret;
1468}
de5f3f40 1469
7c80ab3f 1470static int qcow2_create(const char *filename, QEMUOptionParameter *options)
de5f3f40
KW
1471{
1472 const char *backing_file = NULL;
1473 const char *backing_fmt = NULL;
1474 uint64_t sectors = 0;
1475 int flags = 0;
99cce9fa 1476 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
de5f3f40 1477 int prealloc = 0;
8ad1898c 1478 int version = 3;
de5f3f40
KW
1479
1480 /* Read out options */
1481 while (options && options->name) {
1482 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1483 sectors = options->value.n / 512;
1484 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1485 backing_file = options->value.s;
1486 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1487 backing_fmt = options->value.s;
1488 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1489 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1490 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1491 if (options->value.n) {
1492 cluster_size = options->value.n;
1493 }
1494 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1495 if (!options->value.s || !strcmp(options->value.s, "off")) {
1496 prealloc = 0;
1497 } else if (!strcmp(options->value.s, "metadata")) {
1498 prealloc = 1;
1499 } else {
1500 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1501 options->value.s);
1502 return -EINVAL;
1503 }
6744cbab 1504 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
9117b477
KW
1505 if (!options->value.s) {
1506 /* keep the default */
1507 } else if (!strcmp(options->value.s, "0.10")) {
6744cbab
KW
1508 version = 2;
1509 } else if (!strcmp(options->value.s, "1.1")) {
1510 version = 3;
1511 } else {
1512 fprintf(stderr, "Invalid compatibility level: '%s'\n",
1513 options->value.s);
1514 return -EINVAL;
1515 }
bfe8043e
SH
1516 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1517 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
de5f3f40
KW
1518 }
1519 options++;
1520 }
1521
1522 if (backing_file && prealloc) {
1523 fprintf(stderr, "Backing file and preallocation cannot be used at "
1524 "the same time\n");
1525 return -EINVAL;
1526 }
1527
bfe8043e
SH
1528 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1529 fprintf(stderr, "Lazy refcounts only supported with compatibility "
1530 "level 1.1 and above (use compat=1.1 or greater)\n");
1531 return -EINVAL;
1532 }
1533
7c80ab3f 1534 return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
6744cbab 1535 cluster_size, prealloc, options, version);
de5f3f40
KW
1536}
1537
7c80ab3f 1538static int qcow2_make_empty(BlockDriverState *bs)
20d97356
BS
1539{
1540#if 0
1541 /* XXX: not correct */
1542 BDRVQcowState *s = bs->opaque;
1543 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1544 int ret;
1545
1546 memset(s->l1_table, 0, l1_length);
66f82cee 1547 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
20d97356 1548 return -1;
66f82cee 1549 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
20d97356
BS
1550 if (ret < 0)
1551 return ret;
1552
1553 l2_cache_reset(bs);
1554#endif
1555 return 0;
1556}
1557
621f0589
KW
1558static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1559 int64_t sector_num, int nb_sectors)
1560{
1561 int ret;
1562 BDRVQcowState *s = bs->opaque;
1563
1564 /* Emulate misaligned zero writes */
1565 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1566 return -ENOTSUP;
1567 }
1568
1569 /* Whatever is left can use real zero clusters */
1570 qemu_co_mutex_lock(&s->lock);
1571 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1572 nb_sectors);
1573 qemu_co_mutex_unlock(&s->lock);
1574
1575 return ret;
1576}
1577
6db39ae2
PB
1578static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1579 int64_t sector_num, int nb_sectors)
5ea929e3 1580{
6db39ae2
PB
1581 int ret;
1582 BDRVQcowState *s = bs->opaque;
1583
1584 qemu_co_mutex_lock(&s->lock);
1585 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
670df5e3 1586 nb_sectors, QCOW2_DISCARD_REQUEST);
6db39ae2
PB
1587 qemu_co_mutex_unlock(&s->lock);
1588 return ret;
5ea929e3
KW
1589}
1590
419b19d9
SH
1591static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1592{
1593 BDRVQcowState *s = bs->opaque;
2cf7cfa1
KW
1594 int64_t new_l1_size;
1595 int ret;
419b19d9
SH
1596
1597 if (offset & 511) {
259b2173 1598 error_report("The new size must be a multiple of 512");
419b19d9
SH
1599 return -EINVAL;
1600 }
1601
1602 /* cannot proceed if image has snapshots */
1603 if (s->nb_snapshots) {
259b2173 1604 error_report("Can't resize an image which has snapshots");
419b19d9
SH
1605 return -ENOTSUP;
1606 }
1607
1608 /* shrinking is currently not supported */
1609 if (offset < bs->total_sectors * 512) {
259b2173 1610 error_report("qcow2 doesn't support shrinking images yet");
419b19d9
SH
1611 return -ENOTSUP;
1612 }
1613
1614 new_l1_size = size_to_l1(s, offset);
72893756 1615 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
419b19d9
SH
1616 if (ret < 0) {
1617 return ret;
1618 }
1619
1620 /* write updated header.size */
1621 offset = cpu_to_be64(offset);
8b3b7206
KW
1622 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1623 &offset, sizeof(uint64_t));
419b19d9
SH
1624 if (ret < 0) {
1625 return ret;
1626 }
1627
1628 s->l1_vm_state_index = new_l1_size;
1629 return 0;
1630}
1631
20d97356
BS
1632/* XXX: put compressed sectors first, then all the cluster aligned
1633 tables to avoid losing bytes in alignment */
7c80ab3f
JS
1634static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1635 const uint8_t *buf, int nb_sectors)
20d97356
BS
1636{
1637 BDRVQcowState *s = bs->opaque;
1638 z_stream strm;
1639 int ret, out_len;
1640 uint8_t *out_buf;
1641 uint64_t cluster_offset;
1642
1643 if (nb_sectors == 0) {
1644 /* align end of file to a sector boundary to ease reading with
1645 sector based I/Os */
66f82cee 1646 cluster_offset = bdrv_getlength(bs->file);
20d97356 1647 cluster_offset = (cluster_offset + 511) & ~511;
66f82cee 1648 bdrv_truncate(bs->file, cluster_offset);
20d97356
BS
1649 return 0;
1650 }
1651
f4d38bef
SH
1652 if (nb_sectors != s->cluster_sectors) {
1653 ret = -EINVAL;
1654
1655 /* Zero-pad last write if image size is not cluster aligned */
1656 if (sector_num + nb_sectors == bs->total_sectors &&
1657 nb_sectors < s->cluster_sectors) {
1658 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1659 memset(pad_buf, 0, s->cluster_size);
1660 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1661 ret = qcow2_write_compressed(bs, sector_num,
1662 pad_buf, s->cluster_sectors);
1663 qemu_vfree(pad_buf);
1664 }
1665 return ret;
1666 }
20d97356 1667
7267c094 1668 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
20d97356
BS
1669
1670 /* best compression, small window, no zlib header */
1671 memset(&strm, 0, sizeof(strm));
1672 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1673 Z_DEFLATED, -12,
1674 9, Z_DEFAULT_STRATEGY);
1675 if (ret != 0) {
8f1efd00
KW
1676 ret = -EINVAL;
1677 goto fail;
20d97356
BS
1678 }
1679
1680 strm.avail_in = s->cluster_size;
1681 strm.next_in = (uint8_t *)buf;
1682 strm.avail_out = s->cluster_size;
1683 strm.next_out = out_buf;
1684
1685 ret = deflate(&strm, Z_FINISH);
1686 if (ret != Z_STREAM_END && ret != Z_OK) {
20d97356 1687 deflateEnd(&strm);
8f1efd00
KW
1688 ret = -EINVAL;
1689 goto fail;
20d97356
BS
1690 }
1691 out_len = strm.next_out - out_buf;
1692
1693 deflateEnd(&strm);
1694
1695 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1696 /* could not compress: write normal cluster */
cf93980e
HR
1697
1698 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
1699 sector_num * BDRV_SECTOR_SIZE,
1700 s->cluster_sectors * BDRV_SECTOR_SIZE);
1701 if (ret < 0) {
1702 goto fail;
1703 }
1704
8f1efd00
KW
1705 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1706 if (ret < 0) {
1707 goto fail;
1708 }
20d97356
BS
1709 } else {
1710 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1711 sector_num << 9, out_len);
8f1efd00
KW
1712 if (!cluster_offset) {
1713 ret = -EIO;
1714 goto fail;
1715 }
20d97356 1716 cluster_offset &= s->cluster_offset_mask;
cf93980e
HR
1717
1718 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
1719 cluster_offset, out_len);
1720 if (ret < 0) {
1721 goto fail;
1722 }
1723
66f82cee 1724 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
8f1efd00
KW
1725 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1726 if (ret < 0) {
1727 goto fail;
20d97356
BS
1728 }
1729 }
1730
8f1efd00
KW
1731 ret = 0;
1732fail:
7267c094 1733 g_free(out_buf);
8f1efd00 1734 return ret;
20d97356
BS
1735}
1736
a968168c 1737static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 1738{
29c1a730
KW
1739 BDRVQcowState *s = bs->opaque;
1740 int ret;
1741
8b94ff85 1742 qemu_co_mutex_lock(&s->lock);
29c1a730
KW
1743 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1744 if (ret < 0) {
c95de7e2 1745 qemu_co_mutex_unlock(&s->lock);
8b94ff85 1746 return ret;
29c1a730
KW
1747 }
1748
bfe8043e
SH
1749 if (qcow2_need_accurate_refcounts(s)) {
1750 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1751 if (ret < 0) {
1752 qemu_co_mutex_unlock(&s->lock);
1753 return ret;
1754 }
29c1a730 1755 }
8b94ff85 1756 qemu_co_mutex_unlock(&s->lock);
29c1a730 1757
eb489bb1
KW
1758 return 0;
1759}
1760
7c80ab3f 1761static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356
BS
1762{
1763 BDRVQcowState *s = bs->opaque;
1764 bdi->cluster_size = s->cluster_size;
7c80ab3f 1765 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
1766 return 0;
1767}
1768
20d97356
BS
1769#if 0
1770static void dump_refcounts(BlockDriverState *bs)
1771{
1772 BDRVQcowState *s = bs->opaque;
1773 int64_t nb_clusters, k, k1, size;
1774 int refcount;
1775
66f82cee 1776 size = bdrv_getlength(bs->file);
20d97356
BS
1777 nb_clusters = size_to_clusters(s, size);
1778 for(k = 0; k < nb_clusters;) {
1779 k1 = k;
1780 refcount = get_refcount(bs, k);
1781 k++;
1782 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1783 k++;
0bfcd599
BS
1784 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1785 k - k1);
20d97356
BS
1786 }
1787}
1788#endif
1789
cf8074b3
KW
1790static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
1791 int64_t pos)
20d97356
BS
1792{
1793 BDRVQcowState *s = bs->opaque;
1794 int growable = bs->growable;
1795 int ret;
1796
66f82cee 1797 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
20d97356 1798 bs->growable = 1;
8d3b1a2d 1799 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
20d97356
BS
1800 bs->growable = growable;
1801
1802 return ret;
1803}
1804
7c80ab3f
JS
1805static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1806 int64_t pos, int size)
20d97356
BS
1807{
1808 BDRVQcowState *s = bs->opaque;
1809 int growable = bs->growable;
0d51b4de 1810 bool zero_beyond_eof = bs->zero_beyond_eof;
20d97356
BS
1811 int ret;
1812
66f82cee 1813 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
20d97356 1814 bs->growable = 1;
0d51b4de 1815 bs->zero_beyond_eof = false;
7c80ab3f 1816 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
20d97356 1817 bs->growable = growable;
0d51b4de 1818 bs->zero_beyond_eof = zero_beyond_eof;
20d97356
BS
1819
1820 return ret;
1821}
1822
7c80ab3f 1823static QEMUOptionParameter qcow2_create_options[] = {
20d97356
BS
1824 {
1825 .name = BLOCK_OPT_SIZE,
1826 .type = OPT_SIZE,
1827 .help = "Virtual disk size"
1828 },
6744cbab
KW
1829 {
1830 .name = BLOCK_OPT_COMPAT_LEVEL,
1831 .type = OPT_STRING,
1832 .help = "Compatibility level (0.10 or 1.1)"
1833 },
20d97356
BS
1834 {
1835 .name = BLOCK_OPT_BACKING_FILE,
1836 .type = OPT_STRING,
1837 .help = "File name of a base image"
1838 },
1839 {
1840 .name = BLOCK_OPT_BACKING_FMT,
1841 .type = OPT_STRING,
1842 .help = "Image format of the base image"
1843 },
1844 {
1845 .name = BLOCK_OPT_ENCRYPT,
1846 .type = OPT_FLAG,
1847 .help = "Encrypt the image"
1848 },
1849 {
1850 .name = BLOCK_OPT_CLUSTER_SIZE,
1851 .type = OPT_SIZE,
99cce9fa
KW
1852 .help = "qcow2 cluster size",
1853 .value = { .n = DEFAULT_CLUSTER_SIZE },
20d97356
BS
1854 },
1855 {
1856 .name = BLOCK_OPT_PREALLOC,
1857 .type = OPT_STRING,
1858 .help = "Preallocation mode (allowed values: off, metadata)"
1859 },
bfe8043e
SH
1860 {
1861 .name = BLOCK_OPT_LAZY_REFCOUNTS,
1862 .type = OPT_FLAG,
1863 .help = "Postpone refcount updates",
1864 },
20d97356
BS
1865 { NULL }
1866};
1867
1868static BlockDriver bdrv_qcow2 = {
7c80ab3f
JS
1869 .format_name = "qcow2",
1870 .instance_size = sizeof(BDRVQcowState),
1871 .bdrv_probe = qcow2_probe,
1872 .bdrv_open = qcow2_open,
1873 .bdrv_close = qcow2_close,
21d82ac9 1874 .bdrv_reopen_prepare = qcow2_reopen_prepare,
7c80ab3f 1875 .bdrv_create = qcow2_create,
3ac21627 1876 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 1877 .bdrv_co_get_block_status = qcow2_co_get_block_status,
7c80ab3f
JS
1878 .bdrv_set_key = qcow2_set_key,
1879 .bdrv_make_empty = qcow2_make_empty,
1880
c68b89ac
KW
1881 .bdrv_co_readv = qcow2_co_readv,
1882 .bdrv_co_writev = qcow2_co_writev,
eb489bb1 1883 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 1884
621f0589 1885 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
6db39ae2 1886 .bdrv_co_discard = qcow2_co_discard,
419b19d9 1887 .bdrv_truncate = qcow2_truncate,
7c80ab3f 1888 .bdrv_write_compressed = qcow2_write_compressed,
20d97356
BS
1889
1890 .bdrv_snapshot_create = qcow2_snapshot_create,
1891 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1892 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1893 .bdrv_snapshot_list = qcow2_snapshot_list,
51ef6727 1894 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
7c80ab3f 1895 .bdrv_get_info = qcow2_get_info,
20d97356 1896
7c80ab3f
JS
1897 .bdrv_save_vmstate = qcow2_save_vmstate,
1898 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356
BS
1899
1900 .bdrv_change_backing_file = qcow2_change_backing_file,
1901
06d9260f
AL
1902 .bdrv_invalidate_cache = qcow2_invalidate_cache,
1903
7c80ab3f
JS
1904 .create_options = qcow2_create_options,
1905 .bdrv_check = qcow2_check,
20d97356
BS
1906};
1907
5efa9d5a
AL
1908static void bdrv_qcow2_init(void)
1909{
1910 bdrv_register(&bdrv_qcow2);
1911}
1912
1913block_init(bdrv_qcow2_init);