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