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