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