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