]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2-refcount.c
qcow2: Do not perform potentially damaging repairs
[mirror_qemu.git] / block / qcow2-refcount.c
CommitLineData
f7d0fe02
KW
1/*
2 * Block driver for the QCOW version 2 format
3 *
4 * Copyright (c) 2004-2006 Fabrice Bellard
5 *
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 */
24
25#include "qemu-common.h"
737e150e 26#include "block/block_int.h"
f7d0fe02 27#include "block/qcow2.h"
a40f1c2a 28#include "qemu/range.h"
f7d0fe02 29
bb572aef 30static int64_t alloc_clusters_noref(BlockDriverState *bs, uint64_t size);
92dcb59f 31static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
f7d0fe02 32 int64_t offset, int64_t length,
6cfcb9b8 33 int addend, enum qcow2_discard_type type);
f7d0fe02 34
3b88e52b 35
f7d0fe02
KW
36/*********************************************************/
37/* refcount handling */
38
ed6ccf0f 39int qcow2_refcount_init(BlockDriverState *bs)
f7d0fe02
KW
40{
41 BDRVQcowState *s = bs->opaque;
5dab2fad
KW
42 unsigned int refcount_table_size2, i;
43 int ret;
f7d0fe02 44
5dab2fad 45 assert(s->refcount_table_size <= INT_MAX / sizeof(uint64_t));
f7d0fe02 46 refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
de82815d
KW
47 s->refcount_table = g_try_malloc(refcount_table_size2);
48
f7d0fe02 49 if (s->refcount_table_size > 0) {
de82815d 50 if (s->refcount_table == NULL) {
8fcffa98 51 ret = -ENOMEM;
de82815d
KW
52 goto fail;
53 }
66f82cee
KW
54 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_LOAD);
55 ret = bdrv_pread(bs->file, s->refcount_table_offset,
f7d0fe02 56 s->refcount_table, refcount_table_size2);
8fcffa98 57 if (ret < 0) {
f7d0fe02 58 goto fail;
8fcffa98 59 }
f7d0fe02
KW
60 for(i = 0; i < s->refcount_table_size; i++)
61 be64_to_cpus(&s->refcount_table[i]);
62 }
63 return 0;
64 fail:
8fcffa98 65 return ret;
f7d0fe02
KW
66}
67
ed6ccf0f 68void qcow2_refcount_close(BlockDriverState *bs)
f7d0fe02
KW
69{
70 BDRVQcowState *s = bs->opaque;
7267c094 71 g_free(s->refcount_table);
f7d0fe02
KW
72}
73
74
75static int load_refcount_block(BlockDriverState *bs,
29c1a730
KW
76 int64_t refcount_block_offset,
77 void **refcount_block)
f7d0fe02
KW
78{
79 BDRVQcowState *s = bs->opaque;
80 int ret;
3b88e52b 81
66f82cee 82 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_LOAD);
29c1a730
KW
83 ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
84 refcount_block);
e14e8ba5 85
29c1a730 86 return ret;
f7d0fe02
KW
87}
88
018faafd
KW
89/*
90 * Returns the refcount of the cluster given by its index. Any non-negative
91 * return value is the refcount of the cluster, negative values are -errno
92 * and indicate an error.
93 */
f7d0fe02
KW
94static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
95{
96 BDRVQcowState *s = bs->opaque;
db8a31d1 97 uint64_t refcount_table_index, block_index;
f7d0fe02 98 int64_t refcount_block_offset;
018faafd 99 int ret;
29c1a730
KW
100 uint16_t *refcount_block;
101 uint16_t refcount;
f7d0fe02
KW
102
103 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
104 if (refcount_table_index >= s->refcount_table_size)
105 return 0;
26d49c46
HR
106 refcount_block_offset =
107 s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
f7d0fe02
KW
108 if (!refcount_block_offset)
109 return 0;
29c1a730 110
a97c67ee
HR
111 if (offset_into_cluster(s, refcount_block_offset)) {
112 qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#" PRIx64
113 " unaligned (reftable index: %#" PRIx64 ")",
114 refcount_block_offset, refcount_table_index);
115 return -EIO;
116 }
117
29c1a730
KW
118 ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
119 (void**) &refcount_block);
120 if (ret < 0) {
121 return ret;
f7d0fe02 122 }
29c1a730 123
f7d0fe02
KW
124 block_index = cluster_index &
125 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
29c1a730
KW
126 refcount = be16_to_cpu(refcount_block[block_index]);
127
128 ret = qcow2_cache_put(bs, s->refcount_block_cache,
129 (void**) &refcount_block);
130 if (ret < 0) {
131 return ret;
132 }
133
134 return refcount;
f7d0fe02
KW
135}
136
05121aed
KW
137/*
138 * Rounds the refcount table size up to avoid growing the table for each single
139 * refcount block that is allocated.
140 */
141static unsigned int next_refcount_table_size(BDRVQcowState *s,
142 unsigned int min_size)
143{
144 unsigned int min_clusters = (min_size >> (s->cluster_bits - 3)) + 1;
145 unsigned int refcount_table_clusters =
146 MAX(1, s->refcount_table_size >> (s->cluster_bits - 3));
147
148 while (min_clusters > refcount_table_clusters) {
149 refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
150 }
151
152 return refcount_table_clusters << (s->cluster_bits - 3);
153}
154
92dcb59f
KW
155
156/* Checks if two offsets are described by the same refcount block */
157static int in_same_refcount_block(BDRVQcowState *s, uint64_t offset_a,
158 uint64_t offset_b)
159{
160 uint64_t block_a = offset_a >> (2 * s->cluster_bits - REFCOUNT_SHIFT);
161 uint64_t block_b = offset_b >> (2 * s->cluster_bits - REFCOUNT_SHIFT);
162
163 return (block_a == block_b);
164}
165
166/*
167 * Loads a refcount block. If it doesn't exist yet, it is allocated first
168 * (including growing the refcount table if needed).
169 *
29c1a730 170 * Returns 0 on success or -errno in error case
92dcb59f 171 */
29c1a730
KW
172static int alloc_refcount_block(BlockDriverState *bs,
173 int64_t cluster_index, uint16_t **refcount_block)
f7d0fe02
KW
174{
175 BDRVQcowState *s = bs->opaque;
92dcb59f
KW
176 unsigned int refcount_table_index;
177 int ret;
178
66f82cee 179 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
8252278a 180
92dcb59f
KW
181 /* Find the refcount block for the given cluster */
182 refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
183
184 if (refcount_table_index < s->refcount_table_size) {
185
186 uint64_t refcount_block_offset =
76dc9e0c 187 s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
92dcb59f
KW
188
189 /* If it's already there, we're done */
190 if (refcount_block_offset) {
a97c67ee
HR
191 if (offset_into_cluster(s, refcount_block_offset)) {
192 qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#"
193 PRIx64 " unaligned (reftable index: "
194 "%#x)", refcount_block_offset,
195 refcount_table_index);
196 return -EIO;
197 }
198
29c1a730
KW
199 return load_refcount_block(bs, refcount_block_offset,
200 (void**) refcount_block);
92dcb59f
KW
201 }
202 }
203
204 /*
205 * If we came here, we need to allocate something. Something is at least
206 * a cluster for the new refcount block. It may also include a new refcount
207 * table if the old refcount table is too small.
208 *
209 * Note that allocating clusters here needs some special care:
210 *
211 * - We can't use the normal qcow2_alloc_clusters(), it would try to
212 * increase the refcount and very likely we would end up with an endless
213 * recursion. Instead we must place the refcount blocks in a way that
214 * they can describe them themselves.
215 *
216 * - We need to consider that at this point we are inside update_refcounts
b106ad91
KW
217 * and potentially doing an initial refcount increase. This means that
218 * some clusters have already been allocated by the caller, but their
219 * refcount isn't accurate yet. If we allocate clusters for metadata, we
220 * need to return -EAGAIN to signal the caller that it needs to restart
221 * the search for free clusters.
92dcb59f
KW
222 *
223 * - alloc_clusters_noref and qcow2_free_clusters may load a different
224 * refcount block into the cache
225 */
226
29c1a730
KW
227 *refcount_block = NULL;
228
229 /* We write to the refcount table, so we might depend on L2 tables */
9991923b
SH
230 ret = qcow2_cache_flush(bs, s->l2_table_cache);
231 if (ret < 0) {
232 return ret;
233 }
92dcb59f
KW
234
235 /* Allocate the refcount block itself and mark it as used */
2eaa8f63
KW
236 int64_t new_block = alloc_clusters_noref(bs, s->cluster_size);
237 if (new_block < 0) {
238 return new_block;
239 }
f7d0fe02 240
f7d0fe02 241#ifdef DEBUG_ALLOC2
92dcb59f
KW
242 fprintf(stderr, "qcow2: Allocate refcount block %d for %" PRIx64
243 " at %" PRIx64 "\n",
244 refcount_table_index, cluster_index << s->cluster_bits, new_block);
f7d0fe02 245#endif
92dcb59f
KW
246
247 if (in_same_refcount_block(s, new_block, cluster_index << s->cluster_bits)) {
25408c09 248 /* Zero the new refcount block before updating it */
29c1a730
KW
249 ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
250 (void**) refcount_block);
251 if (ret < 0) {
252 goto fail_block;
253 }
254
255 memset(*refcount_block, 0, s->cluster_size);
25408c09 256
92dcb59f
KW
257 /* The block describes itself, need to update the cache */
258 int block_index = (new_block >> s->cluster_bits) &
259 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
29c1a730 260 (*refcount_block)[block_index] = cpu_to_be16(1);
92dcb59f
KW
261 } else {
262 /* Described somewhere else. This can recurse at most twice before we
263 * arrive at a block that describes itself. */
6cfcb9b8
KW
264 ret = update_refcount(bs, new_block, s->cluster_size, 1,
265 QCOW2_DISCARD_NEVER);
92dcb59f
KW
266 if (ret < 0) {
267 goto fail_block;
268 }
25408c09 269
9991923b
SH
270 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
271 if (ret < 0) {
272 goto fail_block;
273 }
1c4c2814 274
25408c09
KW
275 /* Initialize the new refcount block only after updating its refcount,
276 * update_refcount uses the refcount cache itself */
29c1a730
KW
277 ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
278 (void**) refcount_block);
279 if (ret < 0) {
280 goto fail_block;
281 }
282
283 memset(*refcount_block, 0, s->cluster_size);
92dcb59f
KW
284 }
285
286 /* Now the new refcount block needs to be written to disk */
66f82cee 287 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE);
29c1a730
KW
288 qcow2_cache_entry_mark_dirty(s->refcount_block_cache, *refcount_block);
289 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
92dcb59f
KW
290 if (ret < 0) {
291 goto fail_block;
292 }
293
294 /* If the refcount table is big enough, just hook the block up there */
295 if (refcount_table_index < s->refcount_table_size) {
296 uint64_t data64 = cpu_to_be64(new_block);
66f82cee 297 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_HOOKUP);
8b3b7206 298 ret = bdrv_pwrite_sync(bs->file,
92dcb59f
KW
299 s->refcount_table_offset + refcount_table_index * sizeof(uint64_t),
300 &data64, sizeof(data64));
301 if (ret < 0) {
302 goto fail_block;
303 }
304
305 s->refcount_table[refcount_table_index] = new_block;
b106ad91
KW
306
307 /* The new refcount block may be where the caller intended to put its
308 * data, so let it restart the search. */
309 return -EAGAIN;
29c1a730
KW
310 }
311
312 ret = qcow2_cache_put(bs, s->refcount_block_cache, (void**) refcount_block);
313 if (ret < 0) {
314 goto fail_block;
92dcb59f
KW
315 }
316
317 /*
318 * If we come here, we need to grow the refcount table. Again, a new
319 * refcount table needs some space and we can't simply allocate to avoid
320 * endless recursion.
321 *
322 * Therefore let's grab new refcount blocks at the end of the image, which
323 * will describe themselves and the new refcount table. This way we can
324 * reference them only in the new table and do the switch to the new
325 * refcount table at once without producing an inconsistent state in
326 * between.
327 */
66f82cee 328 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_GROW);
8252278a 329
92dcb59f
KW
330 /* Calculate the number of refcount blocks needed so far */
331 uint64_t refcount_block_clusters = 1 << (s->cluster_bits - REFCOUNT_SHIFT);
b106ad91 332 uint64_t blocks_used = DIV_ROUND_UP(cluster_index, refcount_block_clusters);
92dcb59f 333
2b5d5953
KW
334 if (blocks_used > QCOW_MAX_REFTABLE_SIZE / sizeof(uint64_t)) {
335 return -EFBIG;
336 }
337
92dcb59f
KW
338 /* And now we need at least one block more for the new metadata */
339 uint64_t table_size = next_refcount_table_size(s, blocks_used + 1);
340 uint64_t last_table_size;
341 uint64_t blocks_clusters;
342 do {
a3548077
KW
343 uint64_t table_clusters =
344 size_to_clusters(s, table_size * sizeof(uint64_t));
92dcb59f
KW
345 blocks_clusters = 1 +
346 ((table_clusters + refcount_block_clusters - 1)
347 / refcount_block_clusters);
348 uint64_t meta_clusters = table_clusters + blocks_clusters;
349
350 last_table_size = table_size;
351 table_size = next_refcount_table_size(s, blocks_used +
352 ((meta_clusters + refcount_block_clusters - 1)
353 / refcount_block_clusters));
354
355 } while (last_table_size != table_size);
356
357#ifdef DEBUG_ALLOC2
358 fprintf(stderr, "qcow2: Grow refcount table %" PRId32 " => %" PRId64 "\n",
359 s->refcount_table_size, table_size);
360#endif
361
362 /* Create the new refcount table and blocks */
363 uint64_t meta_offset = (blocks_used * refcount_block_clusters) *
364 s->cluster_size;
365 uint64_t table_offset = meta_offset + blocks_clusters * s->cluster_size;
5839e53b 366 uint64_t *new_table = g_try_new0(uint64_t, table_size);
de82815d
KW
367 uint16_t *new_blocks = g_try_malloc0(blocks_clusters * s->cluster_size);
368
369 assert(table_size > 0 && blocks_clusters > 0);
370 if (new_table == NULL || new_blocks == NULL) {
371 ret = -ENOMEM;
372 goto fail_table;
373 }
92dcb59f 374
92dcb59f 375 /* Fill the new refcount table */
f7d0fe02 376 memcpy(new_table, s->refcount_table,
92dcb59f
KW
377 s->refcount_table_size * sizeof(uint64_t));
378 new_table[refcount_table_index] = new_block;
379
380 int i;
381 for (i = 0; i < blocks_clusters; i++) {
382 new_table[blocks_used + i] = meta_offset + (i * s->cluster_size);
383 }
384
385 /* Fill the refcount blocks */
386 uint64_t table_clusters = size_to_clusters(s, table_size * sizeof(uint64_t));
387 int block = 0;
388 for (i = 0; i < table_clusters + blocks_clusters; i++) {
389 new_blocks[block++] = cpu_to_be16(1);
390 }
391
392 /* Write refcount blocks to disk */
66f82cee 393 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS);
8b3b7206 394 ret = bdrv_pwrite_sync(bs->file, meta_offset, new_blocks,
92dcb59f 395 blocks_clusters * s->cluster_size);
7267c094 396 g_free(new_blocks);
39ba3bf6 397 new_blocks = NULL;
92dcb59f
KW
398 if (ret < 0) {
399 goto fail_table;
400 }
401
402 /* Write refcount table to disk */
403 for(i = 0; i < table_size; i++) {
404 cpu_to_be64s(&new_table[i]);
405 }
406
66f82cee 407 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE);
8b3b7206 408 ret = bdrv_pwrite_sync(bs->file, table_offset, new_table,
92dcb59f
KW
409 table_size * sizeof(uint64_t));
410 if (ret < 0) {
411 goto fail_table;
412 }
413
414 for(i = 0; i < table_size; i++) {
87267753 415 be64_to_cpus(&new_table[i]);
92dcb59f 416 }
f7d0fe02 417
92dcb59f
KW
418 /* Hook up the new refcount table in the qcow2 header */
419 uint8_t data[12];
f7d0fe02 420 cpu_to_be64w((uint64_t*)data, table_offset);
92dcb59f 421 cpu_to_be32w((uint32_t*)(data + 8), table_clusters);
66f82cee 422 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE);
8b3b7206 423 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, refcount_table_offset),
92dcb59f
KW
424 data, sizeof(data));
425 if (ret < 0) {
426 goto fail_table;
f2b7c8b3
KW
427 }
428
92dcb59f
KW
429 /* And switch it in memory */
430 uint64_t old_table_offset = s->refcount_table_offset;
431 uint64_t old_table_size = s->refcount_table_size;
432
7267c094 433 g_free(s->refcount_table);
f7d0fe02 434 s->refcount_table = new_table;
92dcb59f 435 s->refcount_table_size = table_size;
f7d0fe02
KW
436 s->refcount_table_offset = table_offset;
437
b106ad91 438 /* Free old table. */
6cfcb9b8
KW
439 qcow2_free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t),
440 QCOW2_DISCARD_OTHER);
f7d0fe02 441
29c1a730 442 ret = load_refcount_block(bs, new_block, (void**) refcount_block);
92dcb59f 443 if (ret < 0) {
29c1a730 444 return ret;
f7d0fe02
KW
445 }
446
b106ad91
KW
447 /* If we were trying to do the initial refcount update for some cluster
448 * allocation, we might have used the same clusters to store newly
449 * allocated metadata. Make the caller search some new space. */
450 return -EAGAIN;
f7d0fe02 451
92dcb59f 452fail_table:
de82815d 453 g_free(new_blocks);
7267c094 454 g_free(new_table);
92dcb59f 455fail_block:
29c1a730
KW
456 if (*refcount_block != NULL) {
457 qcow2_cache_put(bs, s->refcount_block_cache, (void**) refcount_block);
3b88e52b 458 }
29c1a730 459 return ret;
9923e05e
KW
460}
461
0b919fae
KW
462void qcow2_process_discards(BlockDriverState *bs, int ret)
463{
464 BDRVQcowState *s = bs->opaque;
465 Qcow2DiscardRegion *d, *next;
466
467 QTAILQ_FOREACH_SAFE(d, &s->discards, next, next) {
468 QTAILQ_REMOVE(&s->discards, d, next);
469
470 /* Discard is optional, ignore the return value */
471 if (ret >= 0) {
472 bdrv_discard(bs->file,
473 d->offset >> BDRV_SECTOR_BITS,
474 d->bytes >> BDRV_SECTOR_BITS);
475 }
476
477 g_free(d);
478 }
479}
480
481static void update_refcount_discard(BlockDriverState *bs,
482 uint64_t offset, uint64_t length)
483{
484 BDRVQcowState *s = bs->opaque;
485 Qcow2DiscardRegion *d, *p, *next;
486
487 QTAILQ_FOREACH(d, &s->discards, next) {
488 uint64_t new_start = MIN(offset, d->offset);
489 uint64_t new_end = MAX(offset + length, d->offset + d->bytes);
490
491 if (new_end - new_start <= length + d->bytes) {
492 /* There can't be any overlap, areas ending up here have no
493 * references any more and therefore shouldn't get freed another
494 * time. */
495 assert(d->bytes + length == new_end - new_start);
496 d->offset = new_start;
497 d->bytes = new_end - new_start;
498 goto found;
499 }
500 }
501
502 d = g_malloc(sizeof(*d));
503 *d = (Qcow2DiscardRegion) {
504 .bs = bs,
505 .offset = offset,
506 .bytes = length,
507 };
508 QTAILQ_INSERT_TAIL(&s->discards, d, next);
509
510found:
511 /* Merge discard requests if they are adjacent now */
512 QTAILQ_FOREACH_SAFE(p, &s->discards, next, next) {
513 if (p == d
514 || p->offset > d->offset + d->bytes
515 || d->offset > p->offset + p->bytes)
516 {
517 continue;
518 }
519
520 /* Still no overlap possible */
521 assert(p->offset == d->offset + d->bytes
522 || d->offset == p->offset + p->bytes);
523
524 QTAILQ_REMOVE(&s->discards, p, next);
525 d->offset = MIN(d->offset, p->offset);
526 d->bytes += p->bytes;
d8bb71b6 527 g_free(p);
0b919fae
KW
528 }
529}
530
f7d0fe02 531/* XXX: cache several refcount block clusters ? */
db3a964f 532static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
6cfcb9b8 533 int64_t offset, int64_t length, int addend, enum qcow2_discard_type type)
f7d0fe02
KW
534{
535 BDRVQcowState *s = bs->opaque;
536 int64_t start, last, cluster_offset;
29c1a730
KW
537 uint16_t *refcount_block = NULL;
538 int64_t old_table_index = -1;
09508d13 539 int ret;
f7d0fe02
KW
540
541#ifdef DEBUG_ALLOC2
35ee5e39 542 fprintf(stderr, "update_refcount: offset=%" PRId64 " size=%" PRId64 " addend=%d\n",
f7d0fe02
KW
543 offset, length, addend);
544#endif
7322afe7 545 if (length < 0) {
f7d0fe02 546 return -EINVAL;
7322afe7
KW
547 } else if (length == 0) {
548 return 0;
549 }
550
29c1a730
KW
551 if (addend < 0) {
552 qcow2_cache_set_dependency(bs, s->refcount_block_cache,
553 s->l2_table_cache);
554 }
555
ac95acdb
HT
556 start = start_of_cluster(s, offset);
557 last = start_of_cluster(s, offset + length - 1);
f7d0fe02
KW
558 for(cluster_offset = start; cluster_offset <= last;
559 cluster_offset += s->cluster_size)
560 {
561 int block_index, refcount;
562 int64_t cluster_index = cluster_offset >> s->cluster_bits;
29c1a730
KW
563 int64_t table_index =
564 cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
f7d0fe02 565
29c1a730
KW
566 /* Load the refcount block and allocate it if needed */
567 if (table_index != old_table_index) {
568 if (refcount_block) {
569 ret = qcow2_cache_put(bs, s->refcount_block_cache,
570 (void**) &refcount_block);
571 if (ret < 0) {
572 goto fail;
573 }
574 }
9923e05e 575
29c1a730 576 ret = alloc_refcount_block(bs, cluster_index, &refcount_block);
ed0df867 577 if (ret < 0) {
29c1a730 578 goto fail;
f7d0fe02 579 }
f7d0fe02 580 }
29c1a730 581 old_table_index = table_index;
f7d0fe02 582
29c1a730 583 qcow2_cache_entry_mark_dirty(s->refcount_block_cache, refcount_block);
f7d0fe02
KW
584
585 /* we can update the count and save it */
586 block_index = cluster_index &
587 ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
f7d0fe02 588
29c1a730 589 refcount = be16_to_cpu(refcount_block[block_index]);
f7d0fe02 590 refcount += addend;
09508d13
KW
591 if (refcount < 0 || refcount > 0xffff) {
592 ret = -EINVAL;
593 goto fail;
594 }
f7d0fe02
KW
595 if (refcount == 0 && cluster_index < s->free_cluster_index) {
596 s->free_cluster_index = cluster_index;
597 }
29c1a730 598 refcount_block[block_index] = cpu_to_be16(refcount);
0b919fae 599
67af674e 600 if (refcount == 0 && s->discard_passthrough[type]) {
0b919fae 601 update_refcount_discard(bs, cluster_offset, s->cluster_size);
67af674e 602 }
f7d0fe02
KW
603 }
604
09508d13
KW
605 ret = 0;
606fail:
0b919fae
KW
607 if (!s->cache_discards) {
608 qcow2_process_discards(bs, ret);
609 }
610
f7d0fe02 611 /* Write last changed block to disk */
29c1a730 612 if (refcount_block) {
ed0df867 613 int wret;
29c1a730
KW
614 wret = qcow2_cache_put(bs, s->refcount_block_cache,
615 (void**) &refcount_block);
ed0df867
KW
616 if (wret < 0) {
617 return ret < 0 ? ret : wret;
f7d0fe02
KW
618 }
619 }
620
09508d13
KW
621 /*
622 * Try do undo any updates if an error is returned (This may succeed in
623 * some cases like ENOSPC for allocating a new refcount block)
624 */
625 if (ret < 0) {
626 int dummy;
6cfcb9b8
KW
627 dummy = update_refcount(bs, offset, cluster_offset - offset, -addend,
628 QCOW2_DISCARD_NEVER);
83e3f76c 629 (void)dummy;
09508d13
KW
630 }
631
632 return ret;
f7d0fe02
KW
633}
634
018faafd
KW
635/*
636 * Increases or decreases the refcount of a given cluster by one.
637 * addend must be 1 or -1.
638 *
639 * If the return value is non-negative, it is the new refcount of the cluster.
640 * If it is negative, it is -errno and indicates an error.
641 */
32b6444d
HR
642int qcow2_update_cluster_refcount(BlockDriverState *bs,
643 int64_t cluster_index,
644 int addend,
645 enum qcow2_discard_type type)
f7d0fe02
KW
646{
647 BDRVQcowState *s = bs->opaque;
648 int ret;
649
6cfcb9b8
KW
650 ret = update_refcount(bs, cluster_index << s->cluster_bits, 1, addend,
651 type);
f7d0fe02
KW
652 if (ret < 0) {
653 return ret;
654 }
655
656 return get_refcount(bs, cluster_index);
657}
658
659
660
661/*********************************************************/
662/* cluster allocation functions */
663
664
665
666/* return < 0 if error */
bb572aef 667static int64_t alloc_clusters_noref(BlockDriverState *bs, uint64_t size)
f7d0fe02
KW
668{
669 BDRVQcowState *s = bs->opaque;
bb572aef
KW
670 uint64_t i, nb_clusters;
671 int refcount;
f7d0fe02
KW
672
673 nb_clusters = size_to_clusters(s, size);
674retry:
675 for(i = 0; i < nb_clusters; i++) {
bb572aef 676 uint64_t next_cluster_index = s->free_cluster_index++;
2eaa8f63
KW
677 refcount = get_refcount(bs, next_cluster_index);
678
679 if (refcount < 0) {
680 return refcount;
681 } else if (refcount != 0) {
f7d0fe02 682 goto retry;
2eaa8f63 683 }
f7d0fe02 684 }
91f827dc
HR
685
686 /* Make sure that all offsets in the "allocated" range are representable
687 * in an int64_t */
65f33bc0
HR
688 if (s->free_cluster_index > 0 &&
689 s->free_cluster_index - 1 > (INT64_MAX >> s->cluster_bits))
690 {
91f827dc
HR
691 return -EFBIG;
692 }
693
f7d0fe02 694#ifdef DEBUG_ALLOC2
35ee5e39 695 fprintf(stderr, "alloc_clusters: size=%" PRId64 " -> %" PRId64 "\n",
f7d0fe02
KW
696 size,
697 (s->free_cluster_index - nb_clusters) << s->cluster_bits);
698#endif
699 return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
700}
701
bb572aef 702int64_t qcow2_alloc_clusters(BlockDriverState *bs, uint64_t size)
f7d0fe02
KW
703{
704 int64_t offset;
db3a964f 705 int ret;
f7d0fe02 706
66f82cee 707 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);
b106ad91
KW
708 do {
709 offset = alloc_clusters_noref(bs, size);
710 if (offset < 0) {
711 return offset;
712 }
713
714 ret = update_refcount(bs, offset, size, 1, QCOW2_DISCARD_NEVER);
715 } while (ret == -EAGAIN);
2eaa8f63 716
db3a964f
KW
717 if (ret < 0) {
718 return ret;
719 }
1c4c2814 720
f7d0fe02
KW
721 return offset;
722}
723
256900b1
KW
724int qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset,
725 int nb_clusters)
726{
727 BDRVQcowState *s = bs->opaque;
728 uint64_t cluster_index;
33304ec9
HT
729 uint64_t i;
730 int refcount, ret;
731
732 assert(nb_clusters >= 0);
733 if (nb_clusters == 0) {
734 return 0;
735 }
256900b1 736
b106ad91
KW
737 do {
738 /* Check how many clusters there are free */
739 cluster_index = offset >> s->cluster_bits;
740 for(i = 0; i < nb_clusters; i++) {
741 refcount = get_refcount(bs, cluster_index++);
742
743 if (refcount < 0) {
744 return refcount;
745 } else if (refcount != 0) {
746 break;
747 }
256900b1 748 }
256900b1 749
b106ad91
KW
750 /* And then allocate them */
751 ret = update_refcount(bs, offset, i << s->cluster_bits, 1,
752 QCOW2_DISCARD_NEVER);
753 } while (ret == -EAGAIN);
f24423bd 754
256900b1
KW
755 if (ret < 0) {
756 return ret;
757 }
758
759 return i;
760}
761
f7d0fe02
KW
762/* only used to allocate compressed sectors. We try to allocate
763 contiguous sectors. size must be <= cluster_size */
ed6ccf0f 764int64_t qcow2_alloc_bytes(BlockDriverState *bs, int size)
f7d0fe02
KW
765{
766 BDRVQcowState *s = bs->opaque;
767 int64_t offset, cluster_offset;
768 int free_in_cluster;
769
66f82cee 770 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_BYTES);
f7d0fe02
KW
771 assert(size > 0 && size <= s->cluster_size);
772 if (s->free_byte_offset == 0) {
206e6d85
SH
773 offset = qcow2_alloc_clusters(bs, s->cluster_size);
774 if (offset < 0) {
775 return offset;
5d757b56 776 }
206e6d85 777 s->free_byte_offset = offset;
f7d0fe02
KW
778 }
779 redo:
780 free_in_cluster = s->cluster_size -
ac95acdb 781 offset_into_cluster(s, s->free_byte_offset);
f7d0fe02
KW
782 if (size <= free_in_cluster) {
783 /* enough space in current cluster */
784 offset = s->free_byte_offset;
785 s->free_byte_offset += size;
786 free_in_cluster -= size;
787 if (free_in_cluster == 0)
788 s->free_byte_offset = 0;
ac95acdb 789 if (offset_into_cluster(s, offset) != 0)
32b6444d
HR
790 qcow2_update_cluster_refcount(bs, offset >> s->cluster_bits, 1,
791 QCOW2_DISCARD_NEVER);
f7d0fe02 792 } else {
ed6ccf0f 793 offset = qcow2_alloc_clusters(bs, s->cluster_size);
5d757b56
KW
794 if (offset < 0) {
795 return offset;
796 }
ac95acdb 797 cluster_offset = start_of_cluster(s, s->free_byte_offset);
f7d0fe02
KW
798 if ((cluster_offset + s->cluster_size) == offset) {
799 /* we are lucky: contiguous data */
800 offset = s->free_byte_offset;
32b6444d
HR
801 qcow2_update_cluster_refcount(bs, offset >> s->cluster_bits, 1,
802 QCOW2_DISCARD_NEVER);
f7d0fe02
KW
803 s->free_byte_offset += size;
804 } else {
805 s->free_byte_offset = offset;
806 goto redo;
807 }
808 }
29216ed1 809
c1f5bafd 810 /* The cluster refcount was incremented, either by qcow2_alloc_clusters()
32b6444d
HR
811 * or explicitly by qcow2_update_cluster_refcount(). Refcount blocks must
812 * be flushed before the caller's L2 table updates.
c1f5bafd
SH
813 */
814 qcow2_cache_set_dependency(bs, s->l2_table_cache, s->refcount_block_cache);
f7d0fe02
KW
815 return offset;
816}
817
ed6ccf0f 818void qcow2_free_clusters(BlockDriverState *bs,
6cfcb9b8
KW
819 int64_t offset, int64_t size,
820 enum qcow2_discard_type type)
f7d0fe02 821{
db3a964f
KW
822 int ret;
823
66f82cee 824 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_FREE);
6cfcb9b8 825 ret = update_refcount(bs, offset, size, -1, type);
db3a964f
KW
826 if (ret < 0) {
827 fprintf(stderr, "qcow2_free_clusters failed: %s\n", strerror(-ret));
003fad6e 828 /* TODO Remember the clusters to free them later and avoid leaking */
db3a964f 829 }
f7d0fe02
KW
830}
831
45aba42f 832/*
c7a4c37a
KW
833 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
834 * normal cluster, compressed cluster, etc.)
45aba42f 835 */
6cfcb9b8
KW
836void qcow2_free_any_clusters(BlockDriverState *bs, uint64_t l2_entry,
837 int nb_clusters, enum qcow2_discard_type type)
45aba42f
KW
838{
839 BDRVQcowState *s = bs->opaque;
840
c7a4c37a
KW
841 switch (qcow2_get_cluster_type(l2_entry)) {
842 case QCOW2_CLUSTER_COMPRESSED:
843 {
844 int nb_csectors;
845 nb_csectors = ((l2_entry >> s->csize_shift) &
846 s->csize_mask) + 1;
847 qcow2_free_clusters(bs,
848 (l2_entry & s->cluster_offset_mask) & ~511,
6cfcb9b8 849 nb_csectors * 512, type);
c7a4c37a
KW
850 }
851 break;
852 case QCOW2_CLUSTER_NORMAL:
8f730dd2
HR
853 case QCOW2_CLUSTER_ZERO:
854 if (l2_entry & L2E_OFFSET_MASK) {
a97c67ee
HR
855 if (offset_into_cluster(s, l2_entry & L2E_OFFSET_MASK)) {
856 qcow2_signal_corruption(bs, false, -1, -1,
857 "Cannot free unaligned cluster %#llx",
858 l2_entry & L2E_OFFSET_MASK);
859 } else {
860 qcow2_free_clusters(bs, l2_entry & L2E_OFFSET_MASK,
861 nb_clusters << s->cluster_bits, type);
862 }
8f730dd2 863 }
c7a4c37a
KW
864 break;
865 case QCOW2_CLUSTER_UNALLOCATED:
866 break;
867 default:
868 abort();
45aba42f 869 }
45aba42f
KW
870}
871
f7d0fe02
KW
872
873
874/*********************************************************/
875/* snapshots and image creation */
876
877
878
f7d0fe02 879/* update the refcounts of snapshots and the copied flag */
ed6ccf0f
KW
880int qcow2_update_snapshot_refcount(BlockDriverState *bs,
881 int64_t l1_table_offset, int l1_size, int addend)
f7d0fe02
KW
882{
883 BDRVQcowState *s = bs->opaque;
de82815d
KW
884 uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2;
885 bool l1_allocated = false;
f7d0fe02 886 int64_t old_offset, old_l2_offset;
93913dfd 887 int i, j, l1_modified = 0, nb_csectors, refcount;
29c1a730 888 int ret;
f7d0fe02
KW
889
890 l2_table = NULL;
891 l1_table = NULL;
892 l1_size2 = l1_size * sizeof(uint64_t);
43a0cac4 893
0b919fae
KW
894 s->cache_discards = true;
895
43a0cac4
KW
896 /* WARNING: qcow2_snapshot_goto relies on this function not using the
897 * l1_table_offset when it is the current s->l1_table_offset! Be careful
898 * when changing this! */
f7d0fe02 899 if (l1_table_offset != s->l1_table_offset) {
de82815d
KW
900 l1_table = g_try_malloc0(align_offset(l1_size2, 512));
901 if (l1_size2 && l1_table == NULL) {
902 ret = -ENOMEM;
903 goto fail;
904 }
905 l1_allocated = true;
c2bc78b6
KW
906
907 ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);
908 if (ret < 0) {
f7d0fe02 909 goto fail;
93913dfd
KW
910 }
911
f7d0fe02
KW
912 for(i = 0;i < l1_size; i++)
913 be64_to_cpus(&l1_table[i]);
914 } else {
915 assert(l1_size == s->l1_size);
916 l1_table = s->l1_table;
de82815d 917 l1_allocated = false;
f7d0fe02
KW
918 }
919
f7d0fe02
KW
920 for(i = 0; i < l1_size; i++) {
921 l2_offset = l1_table[i];
922 if (l2_offset) {
923 old_l2_offset = l2_offset;
8e37f681 924 l2_offset &= L1E_OFFSET_MASK;
29c1a730 925
a97c67ee
HR
926 if (offset_into_cluster(s, l2_offset)) {
927 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
928 PRIx64 " unaligned (L1 index: %#x)",
929 l2_offset, i);
930 ret = -EIO;
931 goto fail;
932 }
933
29c1a730
KW
934 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
935 (void**) &l2_table);
936 if (ret < 0) {
f7d0fe02 937 goto fail;
29c1a730
KW
938 }
939
f7d0fe02 940 for(j = 0; j < s->l2_size; j++) {
8b81a7b6
HR
941 uint64_t cluster_index;
942
f7d0fe02 943 offset = be64_to_cpu(l2_table[j]);
8b81a7b6
HR
944 old_offset = offset;
945 offset &= ~QCOW_OFLAG_COPIED;
946
947 switch (qcow2_get_cluster_type(offset)) {
948 case QCOW2_CLUSTER_COMPRESSED:
f7d0fe02
KW
949 nb_csectors = ((offset >> s->csize_shift) &
950 s->csize_mask) + 1;
db3a964f 951 if (addend != 0) {
db3a964f
KW
952 ret = update_refcount(bs,
953 (offset & s->cluster_offset_mask) & ~511,
6cfcb9b8
KW
954 nb_csectors * 512, addend,
955 QCOW2_DISCARD_SNAPSHOT);
db3a964f
KW
956 if (ret < 0) {
957 goto fail;
958 }
959 }
f7d0fe02
KW
960 /* compressed clusters are never modified */
961 refcount = 2;
8b81a7b6
HR
962 break;
963
964 case QCOW2_CLUSTER_NORMAL:
965 case QCOW2_CLUSTER_ZERO:
a97c67ee
HR
966 if (offset_into_cluster(s, offset & L2E_OFFSET_MASK)) {
967 qcow2_signal_corruption(bs, true, -1, -1, "Data "
968 "cluster offset %#llx "
969 "unaligned (L2 offset: %#"
970 PRIx64 ", L2 index: %#x)",
971 offset & L2E_OFFSET_MASK,
972 l2_offset, j);
973 ret = -EIO;
974 goto fail;
975 }
976
8b81a7b6
HR
977 cluster_index = (offset & L2E_OFFSET_MASK) >> s->cluster_bits;
978 if (!cluster_index) {
979 /* unallocated */
980 refcount = 0;
981 break;
982 }
f7d0fe02 983 if (addend != 0) {
32b6444d
HR
984 refcount = qcow2_update_cluster_refcount(bs,
985 cluster_index, addend,
986 QCOW2_DISCARD_SNAPSHOT);
f7d0fe02 987 } else {
8e37f681 988 refcount = get_refcount(bs, cluster_index);
f7d0fe02 989 }
018faafd
KW
990
991 if (refcount < 0) {
c2bc78b6 992 ret = refcount;
018faafd
KW
993 goto fail;
994 }
8b81a7b6 995 break;
f7d0fe02 996
8b81a7b6
HR
997 case QCOW2_CLUSTER_UNALLOCATED:
998 refcount = 0;
999 break;
1000
1001 default:
1002 abort();
1003 }
1004
1005 if (refcount == 1) {
1006 offset |= QCOW_OFLAG_COPIED;
1007 }
1008 if (offset != old_offset) {
1009 if (addend > 0) {
1010 qcow2_cache_set_dependency(bs, s->l2_table_cache,
1011 s->refcount_block_cache);
f7d0fe02 1012 }
8b81a7b6
HR
1013 l2_table[j] = cpu_to_be64(offset);
1014 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
f7d0fe02
KW
1015 }
1016 }
29c1a730
KW
1017
1018 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1019 if (ret < 0) {
1020 goto fail;
f7d0fe02
KW
1021 }
1022
29c1a730 1023
f7d0fe02 1024 if (addend != 0) {
32b6444d
HR
1025 refcount = qcow2_update_cluster_refcount(bs, l2_offset >>
1026 s->cluster_bits, addend, QCOW2_DISCARD_SNAPSHOT);
f7d0fe02
KW
1027 } else {
1028 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1029 }
018faafd 1030 if (refcount < 0) {
c2bc78b6 1031 ret = refcount;
018faafd
KW
1032 goto fail;
1033 } else if (refcount == 1) {
f7d0fe02
KW
1034 l2_offset |= QCOW_OFLAG_COPIED;
1035 }
1036 if (l2_offset != old_l2_offset) {
1037 l1_table[i] = l2_offset;
1038 l1_modified = 1;
1039 }
1040 }
1041 }
93913dfd 1042
2154f24e 1043 ret = bdrv_flush(bs);
93913dfd
KW
1044fail:
1045 if (l2_table) {
1046 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1047 }
1048
0b919fae
KW
1049 s->cache_discards = false;
1050 qcow2_process_discards(bs, ret);
1051
43a0cac4 1052 /* Update L1 only if it isn't deleted anyway (addend = -1) */
c2b6ff51
KW
1053 if (ret == 0 && addend >= 0 && l1_modified) {
1054 for (i = 0; i < l1_size; i++) {
f7d0fe02 1055 cpu_to_be64s(&l1_table[i]);
c2b6ff51
KW
1056 }
1057
1058 ret = bdrv_pwrite_sync(bs->file, l1_table_offset, l1_table, l1_size2);
1059
1060 for (i = 0; i < l1_size; i++) {
f7d0fe02 1061 be64_to_cpus(&l1_table[i]);
c2b6ff51 1062 }
f7d0fe02
KW
1063 }
1064 if (l1_allocated)
7267c094 1065 g_free(l1_table);
93913dfd 1066 return ret;
f7d0fe02
KW
1067}
1068
1069
1070
1071
1072/*********************************************************/
1073/* refcount checking functions */
1074
1075
1076
1077/*
1078 * Increases the refcount for a range of clusters in a given refcount table.
1079 * This is used to construct a temporary refcount table out of L1 and L2 tables
1080 * which can be compared the the refcount table saved in the image.
1081 *
9ac228e0 1082 * Modifies the number of errors in res.
f7d0fe02 1083 */
fef4d3d5
HR
1084static int inc_refcounts(BlockDriverState *bs,
1085 BdrvCheckResult *res,
641bb63c
HR
1086 uint16_t **refcount_table,
1087 int64_t *refcount_table_size,
fef4d3d5 1088 int64_t offset, int64_t size)
f7d0fe02
KW
1089{
1090 BDRVQcowState *s = bs->opaque;
0abe740f 1091 uint64_t start, last, cluster_offset, k;
f7d0fe02 1092
fef4d3d5
HR
1093 if (size <= 0) {
1094 return 0;
1095 }
f7d0fe02 1096
ac95acdb
HT
1097 start = start_of_cluster(s, offset);
1098 last = start_of_cluster(s, offset + size - 1);
f7d0fe02
KW
1099 for(cluster_offset = start; cluster_offset <= last;
1100 cluster_offset += s->cluster_size) {
1101 k = cluster_offset >> s->cluster_bits;
641bb63c
HR
1102 if (k >= *refcount_table_size) {
1103 int64_t old_refcount_table_size = *refcount_table_size;
1104 uint16_t *new_refcount_table;
1105
1106 *refcount_table_size = k + 1;
1107 new_refcount_table = g_try_realloc(*refcount_table,
1108 *refcount_table_size *
1109 sizeof(**refcount_table));
1110 if (!new_refcount_table) {
1111 *refcount_table_size = old_refcount_table_size;
1112 res->check_errors++;
1113 return -ENOMEM;
f7d0fe02 1114 }
641bb63c
HR
1115 *refcount_table = new_refcount_table;
1116
1117 memset(*refcount_table + old_refcount_table_size, 0,
1118 (*refcount_table_size - old_refcount_table_size) *
1119 sizeof(**refcount_table));
1120 }
1121
1122 if (++(*refcount_table)[k] == 0) {
1123 fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64
1124 "\n", cluster_offset);
1125 res->corruptions++;
f7d0fe02
KW
1126 }
1127 }
fef4d3d5
HR
1128
1129 return 0;
f7d0fe02
KW
1130}
1131
801f7044
SH
1132/* Flags for check_refcounts_l1() and check_refcounts_l2() */
1133enum {
fba31bae 1134 CHECK_FRAG_INFO = 0x2, /* update BlockFragInfo counters */
801f7044
SH
1135};
1136
f7d0fe02
KW
1137/*
1138 * Increases the refcount in the given refcount table for the all clusters
1139 * referenced in the L2 table. While doing so, performs some checks on L2
1140 * entries.
1141 *
1142 * Returns the number of errors found by the checks or -errno if an internal
1143 * error occurred.
1144 */
9ac228e0 1145static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res,
641bb63c 1146 uint16_t **refcount_table, int64_t *refcount_table_size, int64_t l2_offset,
801f7044 1147 int flags)
f7d0fe02
KW
1148{
1149 BDRVQcowState *s = bs->opaque;
afdf0abe 1150 uint64_t *l2_table, l2_entry;
fba31bae 1151 uint64_t next_contiguous_offset = 0;
ad27390c 1152 int i, l2_size, nb_csectors, ret;
f7d0fe02
KW
1153
1154 /* Read L2 table from disk */
1155 l2_size = s->l2_size * sizeof(uint64_t);
7267c094 1156 l2_table = g_malloc(l2_size);
f7d0fe02 1157
ad27390c
HR
1158 ret = bdrv_pread(bs->file, l2_offset, l2_table, l2_size);
1159 if (ret < 0) {
1160 fprintf(stderr, "ERROR: I/O error in check_refcounts_l2\n");
1161 res->check_errors++;
f7d0fe02 1162 goto fail;
ad27390c 1163 }
f7d0fe02
KW
1164
1165 /* Do the actual checks */
1166 for(i = 0; i < s->l2_size; i++) {
afdf0abe
KW
1167 l2_entry = be64_to_cpu(l2_table[i]);
1168
1169 switch (qcow2_get_cluster_type(l2_entry)) {
1170 case QCOW2_CLUSTER_COMPRESSED:
1171 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1172 if (l2_entry & QCOW_OFLAG_COPIED) {
1173 fprintf(stderr, "ERROR: cluster %" PRId64 ": "
1174 "copied flag must never be set for compressed "
1175 "clusters\n", l2_entry >> s->cluster_bits);
1176 l2_entry &= ~QCOW_OFLAG_COPIED;
1177 res->corruptions++;
1178 }
f7d0fe02 1179
afdf0abe
KW
1180 /* Mark cluster as used */
1181 nb_csectors = ((l2_entry >> s->csize_shift) &
1182 s->csize_mask) + 1;
1183 l2_entry &= s->cluster_offset_mask;
fef4d3d5
HR
1184 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1185 l2_entry & ~511, nb_csectors * 512);
1186 if (ret < 0) {
1187 goto fail;
1188 }
fba31bae
SH
1189
1190 if (flags & CHECK_FRAG_INFO) {
1191 res->bfi.allocated_clusters++;
4db35162 1192 res->bfi.compressed_clusters++;
fba31bae
SH
1193
1194 /* Compressed clusters are fragmented by nature. Since they
1195 * take up sub-sector space but we only have sector granularity
1196 * I/O we need to re-read the same sectors even for adjacent
1197 * compressed clusters.
1198 */
1199 res->bfi.fragmented_clusters++;
1200 }
afdf0abe 1201 break;
f7d0fe02 1202
6377af48
KW
1203 case QCOW2_CLUSTER_ZERO:
1204 if ((l2_entry & L2E_OFFSET_MASK) == 0) {
1205 break;
1206 }
1207 /* fall through */
1208
afdf0abe
KW
1209 case QCOW2_CLUSTER_NORMAL:
1210 {
afdf0abe 1211 uint64_t offset = l2_entry & L2E_OFFSET_MASK;
f7d0fe02 1212
fba31bae
SH
1213 if (flags & CHECK_FRAG_INFO) {
1214 res->bfi.allocated_clusters++;
1215 if (next_contiguous_offset &&
1216 offset != next_contiguous_offset) {
1217 res->bfi.fragmented_clusters++;
1218 }
1219 next_contiguous_offset = offset + s->cluster_size;
1220 }
1221
afdf0abe 1222 /* Mark cluster as used */
fef4d3d5
HR
1223 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1224 offset, s->cluster_size);
1225 if (ret < 0) {
1226 goto fail;
1227 }
afdf0abe
KW
1228
1229 /* Correct offsets are cluster aligned */
ac95acdb 1230 if (offset_into_cluster(s, offset)) {
afdf0abe
KW
1231 fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "
1232 "properly aligned; L2 entry corrupted.\n", offset);
1233 res->corruptions++;
1234 }
1235 break;
1236 }
1237
1238 case QCOW2_CLUSTER_UNALLOCATED:
1239 break;
1240
1241 default:
1242 abort();
f7d0fe02
KW
1243 }
1244 }
1245
7267c094 1246 g_free(l2_table);
9ac228e0 1247 return 0;
f7d0fe02
KW
1248
1249fail:
7267c094 1250 g_free(l2_table);
ad27390c 1251 return ret;
f7d0fe02
KW
1252}
1253
1254/*
1255 * Increases the refcount for the L1 table, its L2 tables and all referenced
1256 * clusters in the given refcount table. While doing so, performs some checks
1257 * on L1 and L2 entries.
1258 *
1259 * Returns the number of errors found by the checks or -errno if an internal
1260 * error occurred.
1261 */
1262static int check_refcounts_l1(BlockDriverState *bs,
9ac228e0 1263 BdrvCheckResult *res,
641bb63c
HR
1264 uint16_t **refcount_table,
1265 int64_t *refcount_table_size,
f7d0fe02 1266 int64_t l1_table_offset, int l1_size,
801f7044 1267 int flags)
f7d0fe02
KW
1268{
1269 BDRVQcowState *s = bs->opaque;
fef4d3d5 1270 uint64_t *l1_table = NULL, l2_offset, l1_size2;
4f6ed88c 1271 int i, ret;
f7d0fe02
KW
1272
1273 l1_size2 = l1_size * sizeof(uint64_t);
1274
1275 /* Mark L1 table as used */
fef4d3d5
HR
1276 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1277 l1_table_offset, l1_size2);
1278 if (ret < 0) {
1279 goto fail;
1280 }
f7d0fe02
KW
1281
1282 /* Read L1 table entries from disk */
fef4d3d5 1283 if (l1_size2 > 0) {
de82815d
KW
1284 l1_table = g_try_malloc(l1_size2);
1285 if (l1_table == NULL) {
1286 ret = -ENOMEM;
ad27390c 1287 res->check_errors++;
de82815d
KW
1288 goto fail;
1289 }
ad27390c
HR
1290 ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);
1291 if (ret < 0) {
1292 fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
1293 res->check_errors++;
702ef63f 1294 goto fail;
ad27390c 1295 }
702ef63f
KW
1296 for(i = 0;i < l1_size; i++)
1297 be64_to_cpus(&l1_table[i]);
1298 }
f7d0fe02
KW
1299
1300 /* Do the actual checks */
1301 for(i = 0; i < l1_size; i++) {
1302 l2_offset = l1_table[i];
1303 if (l2_offset) {
f7d0fe02 1304 /* Mark L2 table as used */
afdf0abe 1305 l2_offset &= L1E_OFFSET_MASK;
fef4d3d5
HR
1306 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1307 l2_offset, s->cluster_size);
1308 if (ret < 0) {
1309 goto fail;
1310 }
f7d0fe02
KW
1311
1312 /* L2 tables are cluster aligned */
ac95acdb 1313 if (offset_into_cluster(s, l2_offset)) {
f7d0fe02
KW
1314 fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "
1315 "cluster aligned; L1 entry corrupted\n", l2_offset);
9ac228e0 1316 res->corruptions++;
f7d0fe02
KW
1317 }
1318
1319 /* Process and check L2 entries */
9ac228e0 1320 ret = check_refcounts_l2(bs, res, refcount_table,
801f7044 1321 refcount_table_size, l2_offset, flags);
f7d0fe02
KW
1322 if (ret < 0) {
1323 goto fail;
1324 }
f7d0fe02
KW
1325 }
1326 }
7267c094 1327 g_free(l1_table);
9ac228e0 1328 return 0;
f7d0fe02
KW
1329
1330fail:
7267c094 1331 g_free(l1_table);
ad27390c 1332 return ret;
f7d0fe02
KW
1333}
1334
4f6ed88c
HR
1335/*
1336 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1337 *
1338 * This function does not print an error message nor does it increment
1339 * check_errors if get_refcount fails (this is because such an error will have
1340 * been already detected and sufficiently signaled by the calling function
1341 * (qcow2_check_refcounts) by the time this function is called).
1342 */
e23e400e
HR
1343static int check_oflag_copied(BlockDriverState *bs, BdrvCheckResult *res,
1344 BdrvCheckMode fix)
4f6ed88c
HR
1345{
1346 BDRVQcowState *s = bs->opaque;
1347 uint64_t *l2_table = qemu_blockalign(bs, s->cluster_size);
1348 int ret;
1349 int refcount;
1350 int i, j;
1351
1352 for (i = 0; i < s->l1_size; i++) {
1353 uint64_t l1_entry = s->l1_table[i];
1354 uint64_t l2_offset = l1_entry & L1E_OFFSET_MASK;
e23e400e 1355 bool l2_dirty = false;
4f6ed88c
HR
1356
1357 if (!l2_offset) {
1358 continue;
1359 }
1360
1361 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1362 if (refcount < 0) {
1363 /* don't print message nor increment check_errors */
1364 continue;
1365 }
1366 if ((refcount == 1) != ((l1_entry & QCOW_OFLAG_COPIED) != 0)) {
e23e400e 1367 fprintf(stderr, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
4f6ed88c 1368 "l1_entry=%" PRIx64 " refcount=%d\n",
e23e400e
HR
1369 fix & BDRV_FIX_ERRORS ? "Repairing" :
1370 "ERROR",
4f6ed88c 1371 i, l1_entry, refcount);
e23e400e
HR
1372 if (fix & BDRV_FIX_ERRORS) {
1373 s->l1_table[i] = refcount == 1
1374 ? l1_entry | QCOW_OFLAG_COPIED
1375 : l1_entry & ~QCOW_OFLAG_COPIED;
1376 ret = qcow2_write_l1_entry(bs, i);
1377 if (ret < 0) {
1378 res->check_errors++;
1379 goto fail;
1380 }
1381 res->corruptions_fixed++;
1382 } else {
1383 res->corruptions++;
1384 }
4f6ed88c
HR
1385 }
1386
1387 ret = bdrv_pread(bs->file, l2_offset, l2_table,
1388 s->l2_size * sizeof(uint64_t));
1389 if (ret < 0) {
1390 fprintf(stderr, "ERROR: Could not read L2 table: %s\n",
1391 strerror(-ret));
1392 res->check_errors++;
1393 goto fail;
1394 }
1395
1396 for (j = 0; j < s->l2_size; j++) {
1397 uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1398 uint64_t data_offset = l2_entry & L2E_OFFSET_MASK;
1399 int cluster_type = qcow2_get_cluster_type(l2_entry);
1400
1401 if ((cluster_type == QCOW2_CLUSTER_NORMAL) ||
1402 ((cluster_type == QCOW2_CLUSTER_ZERO) && (data_offset != 0))) {
1403 refcount = get_refcount(bs, data_offset >> s->cluster_bits);
1404 if (refcount < 0) {
1405 /* don't print message nor increment check_errors */
1406 continue;
1407 }
1408 if ((refcount == 1) != ((l2_entry & QCOW_OFLAG_COPIED) != 0)) {
e23e400e 1409 fprintf(stderr, "%s OFLAG_COPIED data cluster: "
4f6ed88c 1410 "l2_entry=%" PRIx64 " refcount=%d\n",
e23e400e
HR
1411 fix & BDRV_FIX_ERRORS ? "Repairing" :
1412 "ERROR",
4f6ed88c 1413 l2_entry, refcount);
e23e400e
HR
1414 if (fix & BDRV_FIX_ERRORS) {
1415 l2_table[j] = cpu_to_be64(refcount == 1
1416 ? l2_entry | QCOW_OFLAG_COPIED
1417 : l2_entry & ~QCOW_OFLAG_COPIED);
1418 l2_dirty = true;
1419 res->corruptions_fixed++;
1420 } else {
1421 res->corruptions++;
1422 }
4f6ed88c
HR
1423 }
1424 }
1425 }
e23e400e
HR
1426
1427 if (l2_dirty) {
231bb267
HR
1428 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L2,
1429 l2_offset, s->cluster_size);
e23e400e
HR
1430 if (ret < 0) {
1431 fprintf(stderr, "ERROR: Could not write L2 table; metadata "
1432 "overlap check failed: %s\n", strerror(-ret));
1433 res->check_errors++;
1434 goto fail;
1435 }
1436
1437 ret = bdrv_pwrite(bs->file, l2_offset, l2_table, s->cluster_size);
1438 if (ret < 0) {
1439 fprintf(stderr, "ERROR: Could not write L2 table: %s\n",
1440 strerror(-ret));
1441 res->check_errors++;
1442 goto fail;
1443 }
1444 }
4f6ed88c
HR
1445 }
1446
1447 ret = 0;
1448
1449fail:
1450 qemu_vfree(l2_table);
1451 return ret;
1452}
1453
6ca56bf5
HR
1454/*
1455 * Checks consistency of refblocks and accounts for each refblock in
1456 * *refcount_table.
1457 */
1458static int check_refblocks(BlockDriverState *bs, BdrvCheckResult *res,
f307b255
HR
1459 BdrvCheckMode fix, bool *rebuild,
1460 uint16_t **refcount_table, int64_t *nb_clusters)
6ca56bf5
HR
1461{
1462 BDRVQcowState *s = bs->opaque;
001c158d 1463 int64_t i, size;
fef4d3d5 1464 int ret;
6ca56bf5 1465
f7d0fe02 1466 for(i = 0; i < s->refcount_table_size; i++) {
6882c8fa 1467 uint64_t offset, cluster;
f7d0fe02 1468 offset = s->refcount_table[i];
6882c8fa 1469 cluster = offset >> s->cluster_bits;
746c3cb5
KW
1470
1471 /* Refcount blocks are cluster aligned */
ac95acdb 1472 if (offset_into_cluster(s, offset)) {
166acf54 1473 fprintf(stderr, "ERROR refcount block %" PRId64 " is not "
746c3cb5 1474 "cluster aligned; refcount table entry corrupted\n", i);
9ac228e0 1475 res->corruptions++;
f307b255 1476 *rebuild = true;
6882c8fa
KW
1477 continue;
1478 }
1479
6ca56bf5 1480 if (cluster >= *nb_clusters) {
001c158d
HR
1481 fprintf(stderr, "%s refcount block %" PRId64 " is outside image\n",
1482 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
1483
1484 if (fix & BDRV_FIX_ERRORS) {
1485 int64_t old_nb_clusters = *nb_clusters;
1486 uint16_t *new_refcount_table;
1487
1488 if (offset > INT64_MAX - s->cluster_size) {
1489 ret = -EINVAL;
1490 goto resize_fail;
1491 }
1492
1493 ret = bdrv_truncate(bs->file, offset + s->cluster_size);
1494 if (ret < 0) {
1495 goto resize_fail;
1496 }
1497 size = bdrv_getlength(bs->file);
1498 if (size < 0) {
1499 ret = size;
1500 goto resize_fail;
1501 }
1502
1503 *nb_clusters = size_to_clusters(s, size);
1504 assert(*nb_clusters >= old_nb_clusters);
1505
1506 new_refcount_table = g_try_realloc(*refcount_table,
1507 *nb_clusters *
1508 sizeof(**refcount_table));
1509 if (!new_refcount_table) {
1510 *nb_clusters = old_nb_clusters;
1511 res->check_errors++;
1512 return -ENOMEM;
1513 }
1514 *refcount_table = new_refcount_table;
1515
1516 memset(*refcount_table + old_nb_clusters, 0,
1517 (*nb_clusters - old_nb_clusters) *
1518 sizeof(**refcount_table));
1519
1520 if (cluster >= *nb_clusters) {
1521 ret = -EINVAL;
1522 goto resize_fail;
1523 }
1524
1525 res->corruptions_fixed++;
1526 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
1527 offset, s->cluster_size);
1528 if (ret < 0) {
1529 return ret;
1530 }
1531 /* No need to check whether the refcount is now greater than 1:
1532 * This area was just allocated and zeroed, so it can only be
1533 * exactly 1 after inc_refcounts() */
1534 continue;
1535
1536resize_fail:
1537 res->corruptions++;
f307b255 1538 *rebuild = true;
001c158d
HR
1539 fprintf(stderr, "ERROR could not resize image: %s\n",
1540 strerror(-ret));
1541 } else {
1542 res->corruptions++;
1543 }
6882c8fa 1544 continue;
746c3cb5
KW
1545 }
1546
f7d0fe02 1547 if (offset != 0) {
641bb63c 1548 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
fef4d3d5
HR
1549 offset, s->cluster_size);
1550 if (ret < 0) {
1551 return ret;
1552 }
6ca56bf5 1553 if ((*refcount_table)[cluster] != 1) {
f307b255
HR
1554 fprintf(stderr, "ERROR refcount block %" PRId64
1555 " refcount=%d\n", i, (*refcount_table)[cluster]);
1556 res->corruptions++;
1557 *rebuild = true;
746c3cb5 1558 }
f7d0fe02
KW
1559 }
1560 }
1561
6ca56bf5
HR
1562 return 0;
1563}
1564
057a3fe5
HR
1565/*
1566 * Calculates an in-memory refcount table.
1567 */
1568static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
f307b255
HR
1569 BdrvCheckMode fix, bool *rebuild,
1570 uint16_t **refcount_table, int64_t *nb_clusters)
057a3fe5
HR
1571{
1572 BDRVQcowState *s = bs->opaque;
1573 int64_t i;
1574 QCowSnapshot *sn;
1575 int ret;
1576
9696df21
HR
1577 if (!*refcount_table) {
1578 *refcount_table = g_try_new0(uint16_t, *nb_clusters);
1579 if (*nb_clusters && *refcount_table == NULL) {
1580 res->check_errors++;
1581 return -ENOMEM;
1582 }
057a3fe5
HR
1583 }
1584
1585 /* header */
641bb63c 1586 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
fef4d3d5
HR
1587 0, s->cluster_size);
1588 if (ret < 0) {
1589 return ret;
1590 }
057a3fe5
HR
1591
1592 /* current L1 table */
641bb63c 1593 ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
057a3fe5
HR
1594 s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);
1595 if (ret < 0) {
1596 return ret;
1597 }
1598
1599 /* snapshots */
1600 for (i = 0; i < s->nb_snapshots; i++) {
1601 sn = s->snapshots + i;
641bb63c 1602 ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
fef4d3d5 1603 sn->l1_table_offset, sn->l1_size, 0);
057a3fe5
HR
1604 if (ret < 0) {
1605 return ret;
1606 }
1607 }
641bb63c 1608 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
fef4d3d5
HR
1609 s->snapshots_offset, s->snapshots_size);
1610 if (ret < 0) {
1611 return ret;
1612 }
057a3fe5
HR
1613
1614 /* refcount data */
641bb63c 1615 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
fef4d3d5
HR
1616 s->refcount_table_offset,
1617 s->refcount_table_size * sizeof(uint64_t));
1618 if (ret < 0) {
1619 return ret;
1620 }
057a3fe5 1621
f307b255 1622 return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);
057a3fe5
HR
1623}
1624
6ca56bf5
HR
1625/*
1626 * Compares the actual reference count for each cluster in the image against the
1627 * refcount as reported by the refcount structures on-disk.
1628 */
1629static void compare_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
f307b255
HR
1630 BdrvCheckMode fix, bool *rebuild,
1631 int64_t *highest_cluster,
6ca56bf5
HR
1632 uint16_t *refcount_table, int64_t nb_clusters)
1633{
1634 BDRVQcowState *s = bs->opaque;
1635 int64_t i;
1636 int refcount1, refcount2, ret;
1637
1638 for (i = 0, *highest_cluster = 0; i < nb_clusters; i++) {
f7d0fe02 1639 refcount1 = get_refcount(bs, i);
018faafd 1640 if (refcount1 < 0) {
166acf54 1641 fprintf(stderr, "Can't get refcount for cluster %" PRId64 ": %s\n",
018faafd 1642 i, strerror(-refcount1));
9ac228e0 1643 res->check_errors++;
f74550fd 1644 continue;
018faafd
KW
1645 }
1646
f7d0fe02 1647 refcount2 = refcount_table[i];
c6bb9ad1
FS
1648
1649 if (refcount1 > 0 || refcount2 > 0) {
6ca56bf5 1650 *highest_cluster = i;
c6bb9ad1
FS
1651 }
1652
f7d0fe02 1653 if (refcount1 != refcount2) {
166acf54
KW
1654 /* Check if we're allowed to fix the mismatch */
1655 int *num_fixed = NULL;
f307b255
HR
1656 if (refcount1 == 0) {
1657 *rebuild = true;
1658 } else if (refcount1 > refcount2 && (fix & BDRV_FIX_LEAKS)) {
166acf54
KW
1659 num_fixed = &res->leaks_fixed;
1660 } else if (refcount1 < refcount2 && (fix & BDRV_FIX_ERRORS)) {
1661 num_fixed = &res->corruptions_fixed;
1662 }
1663
1664 fprintf(stderr, "%s cluster %" PRId64 " refcount=%d reference=%d\n",
1665 num_fixed != NULL ? "Repairing" :
1666 refcount1 < refcount2 ? "ERROR" :
1667 "Leaked",
f7d0fe02 1668 i, refcount1, refcount2);
166acf54
KW
1669
1670 if (num_fixed) {
1671 ret = update_refcount(bs, i << s->cluster_bits, 1,
6cfcb9b8
KW
1672 refcount2 - refcount1,
1673 QCOW2_DISCARD_ALWAYS);
166acf54
KW
1674 if (ret >= 0) {
1675 (*num_fixed)++;
1676 continue;
1677 }
1678 }
1679
1680 /* And if we couldn't, print an error */
9ac228e0
KW
1681 if (refcount1 < refcount2) {
1682 res->corruptions++;
1683 } else {
1684 res->leaks++;
1685 }
f7d0fe02
KW
1686 }
1687 }
6ca56bf5
HR
1688}
1689
1690/*
1691 * Checks an image for refcount consistency.
1692 *
1693 * Returns 0 if no errors are found, the number of errors in case the image is
1694 * detected as corrupted, and -errno when an internal error occurred.
1695 */
1696int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
1697 BdrvCheckMode fix)
1698{
1699 BDRVQcowState *s = bs->opaque;
1700 int64_t size, highest_cluster, nb_clusters;
9696df21 1701 uint16_t *refcount_table = NULL;
f307b255 1702 bool rebuild = false;
6ca56bf5
HR
1703 int ret;
1704
1705 size = bdrv_getlength(bs->file);
1706 if (size < 0) {
1707 res->check_errors++;
1708 return size;
1709 }
1710
1711 nb_clusters = size_to_clusters(s, size);
1712 if (nb_clusters > INT_MAX) {
1713 res->check_errors++;
1714 return -EFBIG;
1715 }
1716
1717 res->bfi.total_clusters =
1718 size_to_clusters(s, bs->total_sectors * BDRV_SECTOR_SIZE);
1719
f307b255
HR
1720 ret = calculate_refcounts(bs, res, fix, &rebuild, &refcount_table,
1721 &nb_clusters);
6ca56bf5
HR
1722 if (ret < 0) {
1723 goto fail;
1724 }
1725
f307b255 1726 compare_refcounts(bs, res, fix, &rebuild, &highest_cluster, refcount_table,
6ca56bf5 1727 nb_clusters);
f7d0fe02 1728
f307b255
HR
1729 if (rebuild) {
1730 fprintf(stderr, "ERROR need to rebuild refcount structures\n");
1731 res->check_errors++;
1732 /* Just carry on, the rest does not rely on the on-disk refcount
1733 * structures */
1734 }
1735
4f6ed88c 1736 /* check OFLAG_COPIED */
e23e400e 1737 ret = check_oflag_copied(bs, res, fix);
4f6ed88c
HR
1738 if (ret < 0) {
1739 goto fail;
1740 }
1741
c6bb9ad1 1742 res->image_end_offset = (highest_cluster + 1) * s->cluster_size;
80fa3341
KW
1743 ret = 0;
1744
1745fail:
7267c094 1746 g_free(refcount_table);
f7d0fe02 1747
80fa3341 1748 return ret;
f7d0fe02
KW
1749}
1750
a40f1c2a
HR
1751#define overlaps_with(ofs, sz) \
1752 ranges_overlap(offset, size, ofs, sz)
1753
1754/*
1755 * Checks if the given offset into the image file is actually free to use by
1756 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
1757 * i.e. a sanity check without relying on the refcount tables.
1758 *
231bb267
HR
1759 * The ign parameter specifies what checks not to perform (being a bitmask of
1760 * QCow2MetadataOverlap values), i.e., what sections to ignore.
a40f1c2a
HR
1761 *
1762 * Returns:
1763 * - 0 if writing to this offset will not affect the mentioned metadata
1764 * - a positive QCow2MetadataOverlap value indicating one overlapping section
1765 * - a negative value (-errno) indicating an error while performing a check,
1766 * e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
1767 */
231bb267 1768int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
a40f1c2a
HR
1769 int64_t size)
1770{
1771 BDRVQcowState *s = bs->opaque;
3e355390 1772 int chk = s->overlap_check & ~ign;
a40f1c2a
HR
1773 int i, j;
1774
1775 if (!size) {
1776 return 0;
1777 }
1778
1779 if (chk & QCOW2_OL_MAIN_HEADER) {
1780 if (offset < s->cluster_size) {
1781 return QCOW2_OL_MAIN_HEADER;
1782 }
1783 }
1784
1785 /* align range to test to cluster boundaries */
1786 size = align_offset(offset_into_cluster(s, offset) + size, s->cluster_size);
1787 offset = start_of_cluster(s, offset);
1788
1789 if ((chk & QCOW2_OL_ACTIVE_L1) && s->l1_size) {
1790 if (overlaps_with(s->l1_table_offset, s->l1_size * sizeof(uint64_t))) {
1791 return QCOW2_OL_ACTIVE_L1;
1792 }
1793 }
1794
1795 if ((chk & QCOW2_OL_REFCOUNT_TABLE) && s->refcount_table_size) {
1796 if (overlaps_with(s->refcount_table_offset,
1797 s->refcount_table_size * sizeof(uint64_t))) {
1798 return QCOW2_OL_REFCOUNT_TABLE;
1799 }
1800 }
1801
1802 if ((chk & QCOW2_OL_SNAPSHOT_TABLE) && s->snapshots_size) {
1803 if (overlaps_with(s->snapshots_offset, s->snapshots_size)) {
1804 return QCOW2_OL_SNAPSHOT_TABLE;
1805 }
1806 }
1807
1808 if ((chk & QCOW2_OL_INACTIVE_L1) && s->snapshots) {
1809 for (i = 0; i < s->nb_snapshots; i++) {
1810 if (s->snapshots[i].l1_size &&
1811 overlaps_with(s->snapshots[i].l1_table_offset,
1812 s->snapshots[i].l1_size * sizeof(uint64_t))) {
1813 return QCOW2_OL_INACTIVE_L1;
1814 }
1815 }
1816 }
1817
1818 if ((chk & QCOW2_OL_ACTIVE_L2) && s->l1_table) {
1819 for (i = 0; i < s->l1_size; i++) {
1820 if ((s->l1_table[i] & L1E_OFFSET_MASK) &&
1821 overlaps_with(s->l1_table[i] & L1E_OFFSET_MASK,
1822 s->cluster_size)) {
1823 return QCOW2_OL_ACTIVE_L2;
1824 }
1825 }
1826 }
1827
1828 if ((chk & QCOW2_OL_REFCOUNT_BLOCK) && s->refcount_table) {
1829 for (i = 0; i < s->refcount_table_size; i++) {
1830 if ((s->refcount_table[i] & REFT_OFFSET_MASK) &&
1831 overlaps_with(s->refcount_table[i] & REFT_OFFSET_MASK,
1832 s->cluster_size)) {
1833 return QCOW2_OL_REFCOUNT_BLOCK;
1834 }
1835 }
1836 }
1837
1838 if ((chk & QCOW2_OL_INACTIVE_L2) && s->snapshots) {
1839 for (i = 0; i < s->nb_snapshots; i++) {
1840 uint64_t l1_ofs = s->snapshots[i].l1_table_offset;
1841 uint32_t l1_sz = s->snapshots[i].l1_size;
998b959c 1842 uint64_t l1_sz2 = l1_sz * sizeof(uint64_t);
de82815d 1843 uint64_t *l1 = g_try_malloc(l1_sz2);
a40f1c2a
HR
1844 int ret;
1845
de82815d
KW
1846 if (l1_sz2 && l1 == NULL) {
1847 return -ENOMEM;
1848 }
1849
998b959c 1850 ret = bdrv_pread(bs->file, l1_ofs, l1, l1_sz2);
a40f1c2a
HR
1851 if (ret < 0) {
1852 g_free(l1);
1853 return ret;
1854 }
1855
1856 for (j = 0; j < l1_sz; j++) {
1e242b55
HR
1857 uint64_t l2_ofs = be64_to_cpu(l1[j]) & L1E_OFFSET_MASK;
1858 if (l2_ofs && overlaps_with(l2_ofs, s->cluster_size)) {
a40f1c2a
HR
1859 g_free(l1);
1860 return QCOW2_OL_INACTIVE_L2;
1861 }
1862 }
1863
1864 g_free(l1);
1865 }
1866 }
1867
1868 return 0;
1869}
1870
1871static const char *metadata_ol_names[] = {
1872 [QCOW2_OL_MAIN_HEADER_BITNR] = "qcow2_header",
1873 [QCOW2_OL_ACTIVE_L1_BITNR] = "active L1 table",
1874 [QCOW2_OL_ACTIVE_L2_BITNR] = "active L2 table",
1875 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = "refcount table",
1876 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = "refcount block",
1877 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = "snapshot table",
1878 [QCOW2_OL_INACTIVE_L1_BITNR] = "inactive L1 table",
1879 [QCOW2_OL_INACTIVE_L2_BITNR] = "inactive L2 table",
1880};
1881
1882/*
1883 * First performs a check for metadata overlaps (through
1884 * qcow2_check_metadata_overlap); if that fails with a negative value (error
1885 * while performing a check), that value is returned. If an impending overlap
1886 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
1887 * and -EIO returned.
1888 *
1889 * Returns 0 if there were neither overlaps nor errors while checking for
1890 * overlaps; or a negative value (-errno) on error.
1891 */
231bb267 1892int qcow2_pre_write_overlap_check(BlockDriverState *bs, int ign, int64_t offset,
a40f1c2a
HR
1893 int64_t size)
1894{
231bb267 1895 int ret = qcow2_check_metadata_overlap(bs, ign, offset, size);
a40f1c2a
HR
1896
1897 if (ret < 0) {
1898 return ret;
1899 } else if (ret > 0) {
1900 int metadata_ol_bitnr = ffs(ret) - 1;
a40f1c2a
HR
1901 assert(metadata_ol_bitnr < QCOW2_OL_MAX_BITNR);
1902
adb43552
HR
1903 qcow2_signal_corruption(bs, true, offset, size, "Preventing invalid "
1904 "write on metadata (overlaps with %s)",
1905 metadata_ol_names[metadata_ol_bitnr]);
a40f1c2a
HR
1906 return -EIO;
1907 }
1908
1909 return 0;
1910}