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