]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2-refcount.c
qcow2-refcount: check_refcounts_l2(): check l2_bitmap
[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
80c71a24 25#include "qemu/osdep.h"
da34e65c 26#include "qapi/error.h"
0d8c41da 27#include "qcow2.h"
a40f1c2a 28#include "qemu/range.h"
58369e22 29#include "qemu/bswap.h"
46b732cd 30#include "qemu/cutils.h"
1477b6c8 31#include "trace.h"
f7d0fe02 32
77d6a215
EB
33static int64_t alloc_clusters_noref(BlockDriverState *bs, uint64_t size,
34 uint64_t max);
92dcb59f 35static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
0e06528e 36 int64_t offset, int64_t length, uint64_t addend,
2aabe7c7 37 bool decrease, enum qcow2_discard_type type);
f7d0fe02 38
59c0cb78
HR
39static uint64_t get_refcount_ro0(const void *refcount_array, uint64_t index);
40static uint64_t get_refcount_ro1(const void *refcount_array, uint64_t index);
41static uint64_t get_refcount_ro2(const void *refcount_array, uint64_t index);
42static uint64_t get_refcount_ro3(const void *refcount_array, uint64_t index);
7453c96b 43static uint64_t get_refcount_ro4(const void *refcount_array, uint64_t index);
59c0cb78
HR
44static uint64_t get_refcount_ro5(const void *refcount_array, uint64_t index);
45static uint64_t get_refcount_ro6(const void *refcount_array, uint64_t index);
7453c96b 46
59c0cb78
HR
47static void set_refcount_ro0(void *refcount_array, uint64_t index,
48 uint64_t value);
49static void set_refcount_ro1(void *refcount_array, uint64_t index,
50 uint64_t value);
51static void set_refcount_ro2(void *refcount_array, uint64_t index,
52 uint64_t value);
53static void set_refcount_ro3(void *refcount_array, uint64_t index,
54 uint64_t value);
7453c96b
HR
55static void set_refcount_ro4(void *refcount_array, uint64_t index,
56 uint64_t value);
59c0cb78
HR
57static void set_refcount_ro5(void *refcount_array, uint64_t index,
58 uint64_t value);
59static void set_refcount_ro6(void *refcount_array, uint64_t index,
60 uint64_t value);
61
62
63static Qcow2GetRefcountFunc *const get_refcount_funcs[] = {
64 &get_refcount_ro0,
65 &get_refcount_ro1,
66 &get_refcount_ro2,
67 &get_refcount_ro3,
68 &get_refcount_ro4,
69 &get_refcount_ro5,
70 &get_refcount_ro6
71};
72
73static Qcow2SetRefcountFunc *const set_refcount_funcs[] = {
74 &set_refcount_ro0,
75 &set_refcount_ro1,
76 &set_refcount_ro2,
77 &set_refcount_ro3,
78 &set_refcount_ro4,
79 &set_refcount_ro5,
80 &set_refcount_ro6
81};
7453c96b 82
3b88e52b 83
f7d0fe02
KW
84/*********************************************************/
85/* refcount handling */
86
7061a078
AG
87static void update_max_refcount_table_index(BDRVQcow2State *s)
88{
89 unsigned i = s->refcount_table_size - 1;
90 while (i > 0 && (s->refcount_table[i] & REFT_OFFSET_MASK) == 0) {
91 i--;
92 }
93 /* Set s->max_refcount_table_index to the index of the last used entry */
94 s->max_refcount_table_index = i;
95}
96
ed6ccf0f 97int qcow2_refcount_init(BlockDriverState *bs)
f7d0fe02 98{
ff99129a 99 BDRVQcow2State *s = bs->opaque;
5dab2fad
KW
100 unsigned int refcount_table_size2, i;
101 int ret;
f7d0fe02 102
59c0cb78
HR
103 assert(s->refcount_order >= 0 && s->refcount_order <= 6);
104
105 s->get_refcount = get_refcount_funcs[s->refcount_order];
106 s->set_refcount = set_refcount_funcs[s->refcount_order];
7453c96b 107
02b1ecfa
AG
108 assert(s->refcount_table_size <= INT_MAX / REFTABLE_ENTRY_SIZE);
109 refcount_table_size2 = s->refcount_table_size * REFTABLE_ENTRY_SIZE;
de82815d
KW
110 s->refcount_table = g_try_malloc(refcount_table_size2);
111
f7d0fe02 112 if (s->refcount_table_size > 0) {
de82815d 113 if (s->refcount_table == NULL) {
8fcffa98 114 ret = -ENOMEM;
de82815d
KW
115 goto fail;
116 }
66f82cee 117 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_LOAD);
cf2ab8fc 118 ret = bdrv_pread(bs->file, s->refcount_table_offset,
f7d0fe02 119 s->refcount_table, refcount_table_size2);
8fcffa98 120 if (ret < 0) {
f7d0fe02 121 goto fail;
8fcffa98 122 }
f7d0fe02
KW
123 for(i = 0; i < s->refcount_table_size; i++)
124 be64_to_cpus(&s->refcount_table[i]);
7061a078 125 update_max_refcount_table_index(s);
f7d0fe02
KW
126 }
127 return 0;
128 fail:
8fcffa98 129 return ret;
f7d0fe02
KW
130}
131
ed6ccf0f 132void qcow2_refcount_close(BlockDriverState *bs)
f7d0fe02 133{
ff99129a 134 BDRVQcow2State *s = bs->opaque;
7267c094 135 g_free(s->refcount_table);
f7d0fe02
KW
136}
137
138
59c0cb78
HR
139static uint64_t get_refcount_ro0(const void *refcount_array, uint64_t index)
140{
141 return (((const uint8_t *)refcount_array)[index / 8] >> (index % 8)) & 0x1;
142}
143
144static void set_refcount_ro0(void *refcount_array, uint64_t index,
145 uint64_t value)
146{
147 assert(!(value >> 1));
148 ((uint8_t *)refcount_array)[index / 8] &= ~(0x1 << (index % 8));
149 ((uint8_t *)refcount_array)[index / 8] |= value << (index % 8);
150}
151
152static uint64_t get_refcount_ro1(const void *refcount_array, uint64_t index)
153{
154 return (((const uint8_t *)refcount_array)[index / 4] >> (2 * (index % 4)))
155 & 0x3;
156}
157
158static void set_refcount_ro1(void *refcount_array, uint64_t index,
159 uint64_t value)
160{
161 assert(!(value >> 2));
162 ((uint8_t *)refcount_array)[index / 4] &= ~(0x3 << (2 * (index % 4)));
163 ((uint8_t *)refcount_array)[index / 4] |= value << (2 * (index % 4));
164}
165
166static uint64_t get_refcount_ro2(const void *refcount_array, uint64_t index)
167{
168 return (((const uint8_t *)refcount_array)[index / 2] >> (4 * (index % 2)))
169 & 0xf;
170}
171
172static void set_refcount_ro2(void *refcount_array, uint64_t index,
173 uint64_t value)
174{
175 assert(!(value >> 4));
176 ((uint8_t *)refcount_array)[index / 2] &= ~(0xf << (4 * (index % 2)));
177 ((uint8_t *)refcount_array)[index / 2] |= value << (4 * (index % 2));
178}
179
180static uint64_t get_refcount_ro3(const void *refcount_array, uint64_t index)
181{
182 return ((const uint8_t *)refcount_array)[index];
183}
184
185static void set_refcount_ro3(void *refcount_array, uint64_t index,
186 uint64_t value)
187{
188 assert(!(value >> 8));
189 ((uint8_t *)refcount_array)[index] = value;
190}
191
7453c96b
HR
192static uint64_t get_refcount_ro4(const void *refcount_array, uint64_t index)
193{
194 return be16_to_cpu(((const uint16_t *)refcount_array)[index]);
195}
196
197static void set_refcount_ro4(void *refcount_array, uint64_t index,
198 uint64_t value)
199{
200 assert(!(value >> 16));
201 ((uint16_t *)refcount_array)[index] = cpu_to_be16(value);
202}
203
59c0cb78
HR
204static uint64_t get_refcount_ro5(const void *refcount_array, uint64_t index)
205{
206 return be32_to_cpu(((const uint32_t *)refcount_array)[index]);
207}
208
209static void set_refcount_ro5(void *refcount_array, uint64_t index,
210 uint64_t value)
211{
212 assert(!(value >> 32));
213 ((uint32_t *)refcount_array)[index] = cpu_to_be32(value);
214}
215
216static uint64_t get_refcount_ro6(const void *refcount_array, uint64_t index)
217{
218 return be64_to_cpu(((const uint64_t *)refcount_array)[index]);
219}
220
221static void set_refcount_ro6(void *refcount_array, uint64_t index,
222 uint64_t value)
223{
224 ((uint64_t *)refcount_array)[index] = cpu_to_be64(value);
225}
226
7453c96b 227
f7d0fe02 228static int load_refcount_block(BlockDriverState *bs,
29c1a730
KW
229 int64_t refcount_block_offset,
230 void **refcount_block)
f7d0fe02 231{
ff99129a 232 BDRVQcow2State *s = bs->opaque;
3b88e52b 233
66f82cee 234 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_LOAD);
9be38598
EH
235 return qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
236 refcount_block);
f7d0fe02
KW
237}
238
018faafd 239/*
7324c10f
HR
240 * Retrieves the refcount of the cluster given by its index and stores it in
241 * *refcount. Returns 0 on success and -errno on failure.
018faafd 242 */
7324c10f 243int qcow2_get_refcount(BlockDriverState *bs, int64_t cluster_index,
0e06528e 244 uint64_t *refcount)
f7d0fe02 245{
ff99129a 246 BDRVQcow2State *s = bs->opaque;
db8a31d1 247 uint64_t refcount_table_index, block_index;
f7d0fe02 248 int64_t refcount_block_offset;
018faafd 249 int ret;
7453c96b 250 void *refcount_block;
f7d0fe02 251
17bd5f47 252 refcount_table_index = cluster_index >> s->refcount_block_bits;
7324c10f
HR
253 if (refcount_table_index >= s->refcount_table_size) {
254 *refcount = 0;
f7d0fe02 255 return 0;
7324c10f 256 }
26d49c46
HR
257 refcount_block_offset =
258 s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
7324c10f
HR
259 if (!refcount_block_offset) {
260 *refcount = 0;
f7d0fe02 261 return 0;
7324c10f 262 }
29c1a730 263
a97c67ee
HR
264 if (offset_into_cluster(s, refcount_block_offset)) {
265 qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#" PRIx64
266 " unaligned (reftable index: %#" PRIx64 ")",
267 refcount_block_offset, refcount_table_index);
268 return -EIO;
269 }
270
29c1a730 271 ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
7453c96b 272 &refcount_block);
29c1a730
KW
273 if (ret < 0) {
274 return ret;
f7d0fe02 275 }
29c1a730 276
17bd5f47 277 block_index = cluster_index & (s->refcount_block_size - 1);
7453c96b 278 *refcount = s->get_refcount(refcount_block, block_index);
29c1a730 279
2013c3d4 280 qcow2_cache_put(s->refcount_block_cache, &refcount_block);
29c1a730 281
7324c10f 282 return 0;
f7d0fe02
KW
283}
284
92dcb59f 285/* Checks if two offsets are described by the same refcount block */
ff99129a 286static int in_same_refcount_block(BDRVQcow2State *s, uint64_t offset_a,
92dcb59f
KW
287 uint64_t offset_b)
288{
17bd5f47
HR
289 uint64_t block_a = offset_a >> (s->cluster_bits + s->refcount_block_bits);
290 uint64_t block_b = offset_b >> (s->cluster_bits + s->refcount_block_bits);
92dcb59f
KW
291
292 return (block_a == block_b);
293}
294
295/*
296 * Loads a refcount block. If it doesn't exist yet, it is allocated first
297 * (including growing the refcount table if needed).
298 *
29c1a730 299 * Returns 0 on success or -errno in error case
92dcb59f 300 */
29c1a730 301static int alloc_refcount_block(BlockDriverState *bs,
7453c96b 302 int64_t cluster_index, void **refcount_block)
f7d0fe02 303{
ff99129a 304 BDRVQcow2State *s = bs->opaque;
92dcb59f 305 unsigned int refcount_table_index;
12cc30a8 306 int64_t ret;
92dcb59f 307
66f82cee 308 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
8252278a 309
92dcb59f 310 /* Find the refcount block for the given cluster */
17bd5f47 311 refcount_table_index = cluster_index >> s->refcount_block_bits;
92dcb59f
KW
312
313 if (refcount_table_index < s->refcount_table_size) {
314
315 uint64_t refcount_block_offset =
76dc9e0c 316 s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
92dcb59f
KW
317
318 /* If it's already there, we're done */
319 if (refcount_block_offset) {
a97c67ee
HR
320 if (offset_into_cluster(s, refcount_block_offset)) {
321 qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#"
322 PRIx64 " unaligned (reftable index: "
323 "%#x)", refcount_block_offset,
324 refcount_table_index);
325 return -EIO;
326 }
327
29c1a730 328 return load_refcount_block(bs, refcount_block_offset,
7453c96b 329 refcount_block);
92dcb59f
KW
330 }
331 }
332
333 /*
334 * If we came here, we need to allocate something. Something is at least
335 * a cluster for the new refcount block. It may also include a new refcount
336 * table if the old refcount table is too small.
337 *
338 * Note that allocating clusters here needs some special care:
339 *
340 * - We can't use the normal qcow2_alloc_clusters(), it would try to
341 * increase the refcount and very likely we would end up with an endless
342 * recursion. Instead we must place the refcount blocks in a way that
343 * they can describe them themselves.
344 *
345 * - We need to consider that at this point we are inside update_refcounts
b106ad91
KW
346 * and potentially doing an initial refcount increase. This means that
347 * some clusters have already been allocated by the caller, but their
348 * refcount isn't accurate yet. If we allocate clusters for metadata, we
349 * need to return -EAGAIN to signal the caller that it needs to restart
350 * the search for free clusters.
92dcb59f
KW
351 *
352 * - alloc_clusters_noref and qcow2_free_clusters may load a different
353 * refcount block into the cache
354 */
355
29c1a730
KW
356 *refcount_block = NULL;
357
358 /* We write to the refcount table, so we might depend on L2 tables */
9991923b
SH
359 ret = qcow2_cache_flush(bs, s->l2_table_cache);
360 if (ret < 0) {
361 return ret;
362 }
92dcb59f
KW
363
364 /* Allocate the refcount block itself and mark it as used */
77d6a215 365 int64_t new_block = alloc_clusters_noref(bs, s->cluster_size, INT64_MAX);
2eaa8f63
KW
366 if (new_block < 0) {
367 return new_block;
368 }
f7d0fe02 369
cdc674c7
AG
370 /* The offset must fit in the offset field of the refcount table entry */
371 assert((new_block & REFT_OFFSET_MASK) == new_block);
372
6bf45d59
AG
373 /* If we're allocating the block at offset 0 then something is wrong */
374 if (new_block == 0) {
375 qcow2_signal_corruption(bs, true, -1, -1, "Preventing invalid "
376 "allocation of refcount block at offset 0");
377 return -EIO;
378 }
379
f7d0fe02 380#ifdef DEBUG_ALLOC2
92dcb59f
KW
381 fprintf(stderr, "qcow2: Allocate refcount block %d for %" PRIx64
382 " at %" PRIx64 "\n",
383 refcount_table_index, cluster_index << s->cluster_bits, new_block);
f7d0fe02 384#endif
92dcb59f
KW
385
386 if (in_same_refcount_block(s, new_block, cluster_index << s->cluster_bits)) {
25408c09 387 /* Zero the new refcount block before updating it */
29c1a730 388 ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
7453c96b 389 refcount_block);
29c1a730 390 if (ret < 0) {
60c48a29 391 goto fail;
29c1a730
KW
392 }
393
394 memset(*refcount_block, 0, s->cluster_size);
25408c09 395
92dcb59f
KW
396 /* The block describes itself, need to update the cache */
397 int block_index = (new_block >> s->cluster_bits) &
17bd5f47 398 (s->refcount_block_size - 1);
7453c96b 399 s->set_refcount(*refcount_block, block_index, 1);
92dcb59f
KW
400 } else {
401 /* Described somewhere else. This can recurse at most twice before we
402 * arrive at a block that describes itself. */
2aabe7c7 403 ret = update_refcount(bs, new_block, s->cluster_size, 1, false,
6cfcb9b8 404 QCOW2_DISCARD_NEVER);
92dcb59f 405 if (ret < 0) {
60c48a29 406 goto fail;
92dcb59f 407 }
25408c09 408
9991923b
SH
409 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
410 if (ret < 0) {
60c48a29 411 goto fail;
9991923b 412 }
1c4c2814 413
25408c09
KW
414 /* Initialize the new refcount block only after updating its refcount,
415 * update_refcount uses the refcount cache itself */
29c1a730 416 ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
7453c96b 417 refcount_block);
29c1a730 418 if (ret < 0) {
60c48a29 419 goto fail;
29c1a730
KW
420 }
421
422 memset(*refcount_block, 0, s->cluster_size);
92dcb59f
KW
423 }
424
425 /* Now the new refcount block needs to be written to disk */
66f82cee 426 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE);
2d135ee9 427 qcow2_cache_entry_mark_dirty(s->refcount_block_cache, *refcount_block);
29c1a730 428 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
92dcb59f 429 if (ret < 0) {
60c48a29 430 goto fail;
92dcb59f
KW
431 }
432
433 /* If the refcount table is big enough, just hook the block up there */
434 if (refcount_table_index < s->refcount_table_size) {
435 uint64_t data64 = cpu_to_be64(new_block);
66f82cee 436 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_HOOKUP);
02b1ecfa
AG
437 ret = bdrv_pwrite_sync(bs->file, s->refcount_table_offset +
438 refcount_table_index * REFTABLE_ENTRY_SIZE,
92dcb59f
KW
439 &data64, sizeof(data64));
440 if (ret < 0) {
60c48a29 441 goto fail;
92dcb59f
KW
442 }
443
444 s->refcount_table[refcount_table_index] = new_block;
7061a078
AG
445 /* If there's a hole in s->refcount_table then it can happen
446 * that refcount_table_index < s->max_refcount_table_index */
447 s->max_refcount_table_index =
448 MAX(s->max_refcount_table_index, refcount_table_index);
b106ad91
KW
449
450 /* The new refcount block may be where the caller intended to put its
451 * data, so let it restart the search. */
452 return -EAGAIN;
29c1a730
KW
453 }
454
2013c3d4 455 qcow2_cache_put(s->refcount_block_cache, refcount_block);
92dcb59f
KW
456
457 /*
458 * If we come here, we need to grow the refcount table. Again, a new
459 * refcount table needs some space and we can't simply allocate to avoid
460 * endless recursion.
461 *
462 * Therefore let's grab new refcount blocks at the end of the image, which
463 * will describe themselves and the new refcount table. This way we can
464 * reference them only in the new table and do the switch to the new
465 * refcount table at once without producing an inconsistent state in
466 * between.
467 */
66f82cee 468 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_GROW);
8252278a 469
14a58a4e
HR
470 /* Calculate the number of refcount blocks needed so far; this will be the
471 * basis for calculating the index of the first cluster used for the
472 * self-describing refcount structures which we are about to create.
473 *
474 * Because we reached this point, there cannot be any refcount entries for
475 * cluster_index or higher indices yet. However, because new_block has been
476 * allocated to describe that cluster (and it will assume this role later
477 * on), we cannot use that index; also, new_block may actually have a higher
478 * cluster index than cluster_index, so it needs to be taken into account
479 * here (and 1 needs to be added to its value because that cluster is used).
480 */
481 uint64_t blocks_used = DIV_ROUND_UP(MAX(cluster_index + 1,
482 (new_block >> s->cluster_bits) + 1),
483 s->refcount_block_size);
92dcb59f 484
12cc30a8
HR
485 /* Create the new refcount table and blocks */
486 uint64_t meta_offset = (blocks_used * s->refcount_block_size) *
487 s->cluster_size;
488
489 ret = qcow2_refcount_area(bs, meta_offset, 0, false,
490 refcount_table_index, new_block);
491 if (ret < 0) {
492 return ret;
2b5d5953
KW
493 }
494
12cc30a8
HR
495 ret = load_refcount_block(bs, new_block, refcount_block);
496 if (ret < 0) {
497 return ret;
498 }
92dcb59f 499
12cc30a8
HR
500 /* If we were trying to do the initial refcount update for some cluster
501 * allocation, we might have used the same clusters to store newly
502 * allocated metadata. Make the caller search some new space. */
503 return -EAGAIN;
92dcb59f 504
60c48a29 505fail:
12cc30a8 506 if (*refcount_block != NULL) {
2013c3d4 507 qcow2_cache_put(s->refcount_block_cache, refcount_block);
12cc30a8
HR
508 }
509 return ret;
510}
92dcb59f 511
12cc30a8
HR
512/*
513 * Starting at @start_offset, this function creates new self-covering refcount
514 * structures: A new refcount table and refcount blocks which cover all of
515 * themselves, and a number of @additional_clusters beyond their end.
516 * @start_offset must be at the end of the image file, that is, there must be
517 * only empty space beyond it.
518 * If @exact_size is false, the refcount table will have 50 % more entries than
519 * necessary so it will not need to grow again soon.
520 * If @new_refblock_offset is not zero, it contains the offset of a refcount
521 * block that should be entered into the new refcount table at index
522 * @new_refblock_index.
523 *
524 * Returns: The offset after the new refcount structures (i.e. where the
525 * @additional_clusters may be placed) on success, -errno on error.
526 */
772d1f97
HR
527int64_t qcow2_refcount_area(BlockDriverState *bs, uint64_t start_offset,
528 uint64_t additional_clusters, bool exact_size,
529 int new_refblock_index,
530 uint64_t new_refblock_offset)
12cc30a8
HR
531{
532 BDRVQcow2State *s = bs->opaque;
533 uint64_t total_refblock_count_u64, additional_refblock_count;
534 int total_refblock_count, table_size, area_reftable_index, table_clusters;
535 int i;
536 uint64_t table_offset, block_offset, end_offset;
537 int ret;
538 uint64_t *new_table;
92dcb59f 539
12cc30a8 540 assert(!(start_offset % s->cluster_size));
de82815d 541
12cc30a8
HR
542 qcow2_refcount_metadata_size(start_offset / s->cluster_size +
543 additional_clusters,
544 s->cluster_size, s->refcount_order,
545 !exact_size, &total_refblock_count_u64);
546 if (total_refblock_count_u64 > QCOW_MAX_REFTABLE_SIZE) {
547 return -EFBIG;
548 }
549 total_refblock_count = total_refblock_count_u64;
550
551 /* Index in the refcount table of the first refcount block to cover the area
552 * of refcount structures we are about to create; we know that
553 * @total_refblock_count can cover @start_offset, so this will definitely
554 * fit into an int. */
555 area_reftable_index = (start_offset / s->cluster_size) /
556 s->refcount_block_size;
557
558 if (exact_size) {
559 table_size = total_refblock_count;
560 } else {
561 table_size = total_refblock_count +
562 DIV_ROUND_UP(total_refblock_count, 2);
563 }
564 /* The qcow2 file can only store the reftable size in number of clusters */
02b1ecfa
AG
565 table_size = ROUND_UP(table_size, s->cluster_size / REFTABLE_ENTRY_SIZE);
566 table_clusters = (table_size * REFTABLE_ENTRY_SIZE) / s->cluster_size;
12cc30a8
HR
567
568 if (table_size > QCOW_MAX_REFTABLE_SIZE) {
569 return -EFBIG;
570 }
571
572 new_table = g_try_new0(uint64_t, table_size);
573
574 assert(table_size > 0);
575 if (new_table == NULL) {
de82815d 576 ret = -ENOMEM;
12cc30a8 577 goto fail;
de82815d 578 }
92dcb59f 579
92dcb59f 580 /* Fill the new refcount table */
12cc30a8
HR
581 if (table_size > s->max_refcount_table_index) {
582 /* We're actually growing the reftable */
583 memcpy(new_table, s->refcount_table,
02b1ecfa 584 (s->max_refcount_table_index + 1) * REFTABLE_ENTRY_SIZE);
12cc30a8
HR
585 } else {
586 /* Improbable case: We're shrinking the reftable. However, the caller
587 * has assured us that there is only empty space beyond @start_offset,
588 * so we can simply drop all of the refblocks that won't fit into the
589 * new reftable. */
02b1ecfa 590 memcpy(new_table, s->refcount_table, table_size * REFTABLE_ENTRY_SIZE);
12cc30a8 591 }
92dcb59f 592
12cc30a8
HR
593 if (new_refblock_offset) {
594 assert(new_refblock_index < total_refblock_count);
595 new_table[new_refblock_index] = new_refblock_offset;
596 }
597
598 /* Count how many new refblocks we have to create */
599 additional_refblock_count = 0;
600 for (i = area_reftable_index; i < total_refblock_count; i++) {
601 if (!new_table[i]) {
602 additional_refblock_count++;
603 }
92dcb59f
KW
604 }
605
12cc30a8
HR
606 table_offset = start_offset + additional_refblock_count * s->cluster_size;
607 end_offset = table_offset + table_clusters * s->cluster_size;
608
609 /* Fill the refcount blocks, and create new ones, if necessary */
610 block_offset = start_offset;
611 for (i = area_reftable_index; i < total_refblock_count; i++) {
612 void *refblock_data;
613 uint64_t first_offset_covered;
614
615 /* Reuse an existing refblock if possible, create a new one otherwise */
616 if (new_table[i]) {
617 ret = qcow2_cache_get(bs, s->refcount_block_cache, new_table[i],
618 &refblock_data);
619 if (ret < 0) {
620 goto fail;
621 }
622 } else {
623 ret = qcow2_cache_get_empty(bs, s->refcount_block_cache,
624 block_offset, &refblock_data);
625 if (ret < 0) {
626 goto fail;
627 }
628 memset(refblock_data, 0, s->cluster_size);
2d135ee9 629 qcow2_cache_entry_mark_dirty(s->refcount_block_cache,
12cc30a8
HR
630 refblock_data);
631
632 new_table[i] = block_offset;
633 block_offset += s->cluster_size;
634 }
635
636 /* First host offset covered by this refblock */
637 first_offset_covered = (uint64_t)i * s->refcount_block_size *
638 s->cluster_size;
639 if (first_offset_covered < end_offset) {
640 int j, end_index;
641
642 /* Set the refcount of all of the new refcount structures to 1 */
643
644 if (first_offset_covered < start_offset) {
645 assert(i == area_reftable_index);
646 j = (start_offset - first_offset_covered) / s->cluster_size;
647 assert(j < s->refcount_block_size);
648 } else {
649 j = 0;
650 }
651
652 end_index = MIN((end_offset - first_offset_covered) /
653 s->cluster_size,
654 s->refcount_block_size);
655
656 for (; j < end_index; j++) {
657 /* The caller guaranteed us this space would be empty */
658 assert(s->get_refcount(refblock_data, j) == 0);
659 s->set_refcount(refblock_data, j, 1);
660 }
661
2d135ee9 662 qcow2_cache_entry_mark_dirty(s->refcount_block_cache,
12cc30a8
HR
663 refblock_data);
664 }
665
2013c3d4 666 qcow2_cache_put(s->refcount_block_cache, &refblock_data);
92dcb59f
KW
667 }
668
12cc30a8
HR
669 assert(block_offset == table_offset);
670
92dcb59f 671 /* Write refcount blocks to disk */
66f82cee 672 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS);
12cc30a8 673 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
92dcb59f 674 if (ret < 0) {
12cc30a8 675 goto fail;
92dcb59f
KW
676 }
677
678 /* Write refcount table to disk */
12cc30a8 679 for (i = 0; i < total_refblock_count; i++) {
92dcb59f
KW
680 cpu_to_be64s(&new_table[i]);
681 }
682
66f82cee 683 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE);
d9ca2ea2 684 ret = bdrv_pwrite_sync(bs->file, table_offset, new_table,
02b1ecfa 685 table_size * REFTABLE_ENTRY_SIZE);
92dcb59f 686 if (ret < 0) {
12cc30a8 687 goto fail;
92dcb59f
KW
688 }
689
12cc30a8 690 for (i = 0; i < total_refblock_count; i++) {
87267753 691 be64_to_cpus(&new_table[i]);
92dcb59f 692 }
f7d0fe02 693
92dcb59f 694 /* Hook up the new refcount table in the qcow2 header */
95334230
JS
695 struct QEMU_PACKED {
696 uint64_t d64;
697 uint32_t d32;
698 } data;
f1f7a1dd
PM
699 data.d64 = cpu_to_be64(table_offset);
700 data.d32 = cpu_to_be32(table_clusters);
66f82cee 701 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE);
d9ca2ea2 702 ret = bdrv_pwrite_sync(bs->file,
9a4f4c31 703 offsetof(QCowHeader, refcount_table_offset),
95334230 704 &data, sizeof(data));
92dcb59f 705 if (ret < 0) {
12cc30a8 706 goto fail;
f2b7c8b3
KW
707 }
708
92dcb59f
KW
709 /* And switch it in memory */
710 uint64_t old_table_offset = s->refcount_table_offset;
711 uint64_t old_table_size = s->refcount_table_size;
712
7267c094 713 g_free(s->refcount_table);
f7d0fe02 714 s->refcount_table = new_table;
92dcb59f 715 s->refcount_table_size = table_size;
f7d0fe02 716 s->refcount_table_offset = table_offset;
7061a078 717 update_max_refcount_table_index(s);
f7d0fe02 718
b106ad91 719 /* Free old table. */
02b1ecfa
AG
720 qcow2_free_clusters(bs, old_table_offset,
721 old_table_size * REFTABLE_ENTRY_SIZE,
6cfcb9b8 722 QCOW2_DISCARD_OTHER);
f7d0fe02 723
12cc30a8 724 return end_offset;
f7d0fe02 725
12cc30a8 726fail:
7267c094 727 g_free(new_table);
29c1a730 728 return ret;
9923e05e
KW
729}
730
0b919fae
KW
731void qcow2_process_discards(BlockDriverState *bs, int ret)
732{
ff99129a 733 BDRVQcow2State *s = bs->opaque;
0b919fae
KW
734 Qcow2DiscardRegion *d, *next;
735
736 QTAILQ_FOREACH_SAFE(d, &s->discards, next, next) {
737 QTAILQ_REMOVE(&s->discards, d, next);
738
739 /* Discard is optional, ignore the return value */
740 if (ret >= 0) {
1477b6c8
VSO
741 int r2 = bdrv_pdiscard(bs->file, d->offset, d->bytes);
742 if (r2 < 0) {
743 trace_qcow2_process_discards_failed_region(d->offset, d->bytes,
744 r2);
745 }
0b919fae
KW
746 }
747
748 g_free(d);
749 }
750}
751
752static void update_refcount_discard(BlockDriverState *bs,
753 uint64_t offset, uint64_t length)
754{
ff99129a 755 BDRVQcow2State *s = bs->opaque;
0b919fae
KW
756 Qcow2DiscardRegion *d, *p, *next;
757
758 QTAILQ_FOREACH(d, &s->discards, next) {
759 uint64_t new_start = MIN(offset, d->offset);
760 uint64_t new_end = MAX(offset + length, d->offset + d->bytes);
761
762 if (new_end - new_start <= length + d->bytes) {
763 /* There can't be any overlap, areas ending up here have no
764 * references any more and therefore shouldn't get freed another
765 * time. */
766 assert(d->bytes + length == new_end - new_start);
767 d->offset = new_start;
768 d->bytes = new_end - new_start;
769 goto found;
770 }
771 }
772
773 d = g_malloc(sizeof(*d));
774 *d = (Qcow2DiscardRegion) {
775 .bs = bs,
776 .offset = offset,
777 .bytes = length,
778 };
779 QTAILQ_INSERT_TAIL(&s->discards, d, next);
780
781found:
782 /* Merge discard requests if they are adjacent now */
783 QTAILQ_FOREACH_SAFE(p, &s->discards, next, next) {
784 if (p == d
785 || p->offset > d->offset + d->bytes
786 || d->offset > p->offset + p->bytes)
787 {
788 continue;
789 }
790
791 /* Still no overlap possible */
792 assert(p->offset == d->offset + d->bytes
793 || d->offset == p->offset + p->bytes);
794
795 QTAILQ_REMOVE(&s->discards, p, next);
796 d->offset = MIN(d->offset, p->offset);
797 d->bytes += p->bytes;
d8bb71b6 798 g_free(p);
0b919fae
KW
799 }
800}
801
f7d0fe02 802/* XXX: cache several refcount block clusters ? */
2aabe7c7
HR
803/* @addend is the absolute value of the addend; if @decrease is set, @addend
804 * will be subtracted from the current refcount, otherwise it will be added */
db3a964f 805static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
2aabe7c7
HR
806 int64_t offset,
807 int64_t length,
0e06528e 808 uint64_t addend,
2aabe7c7
HR
809 bool decrease,
810 enum qcow2_discard_type type)
f7d0fe02 811{
ff99129a 812 BDRVQcow2State *s = bs->opaque;
f7d0fe02 813 int64_t start, last, cluster_offset;
7453c96b 814 void *refcount_block = NULL;
29c1a730 815 int64_t old_table_index = -1;
09508d13 816 int ret;
f7d0fe02
KW
817
818#ifdef DEBUG_ALLOC2
2aabe7c7 819 fprintf(stderr, "update_refcount: offset=%" PRId64 " size=%" PRId64
0e06528e 820 " addend=%s%" PRIu64 "\n", offset, length, decrease ? "-" : "",
2aabe7c7 821 addend);
f7d0fe02 822#endif
7322afe7 823 if (length < 0) {
f7d0fe02 824 return -EINVAL;
7322afe7
KW
825 } else if (length == 0) {
826 return 0;
827 }
828
2aabe7c7 829 if (decrease) {
29c1a730
KW
830 qcow2_cache_set_dependency(bs, s->refcount_block_cache,
831 s->l2_table_cache);
832 }
833
ac95acdb
HT
834 start = start_of_cluster(s, offset);
835 last = start_of_cluster(s, offset + length - 1);
f7d0fe02
KW
836 for(cluster_offset = start; cluster_offset <= last;
837 cluster_offset += s->cluster_size)
838 {
2aabe7c7 839 int block_index;
0e06528e 840 uint64_t refcount;
f7d0fe02 841 int64_t cluster_index = cluster_offset >> s->cluster_bits;
17bd5f47 842 int64_t table_index = cluster_index >> s->refcount_block_bits;
f7d0fe02 843
29c1a730
KW
844 /* Load the refcount block and allocate it if needed */
845 if (table_index != old_table_index) {
846 if (refcount_block) {
2013c3d4 847 qcow2_cache_put(s->refcount_block_cache, &refcount_block);
29c1a730 848 }
29c1a730 849 ret = alloc_refcount_block(bs, cluster_index, &refcount_block);
abf754fe
AG
850 /* If the caller needs to restart the search for free clusters,
851 * try the same ones first to see if they're still free. */
852 if (ret == -EAGAIN) {
853 if (s->free_cluster_index > (start >> s->cluster_bits)) {
854 s->free_cluster_index = (start >> s->cluster_bits);
855 }
856 }
ed0df867 857 if (ret < 0) {
29c1a730 858 goto fail;
f7d0fe02 859 }
f7d0fe02 860 }
29c1a730 861 old_table_index = table_index;
f7d0fe02 862
2d135ee9 863 qcow2_cache_entry_mark_dirty(s->refcount_block_cache, refcount_block);
f7d0fe02
KW
864
865 /* we can update the count and save it */
17bd5f47 866 block_index = cluster_index & (s->refcount_block_size - 1);
f7d0fe02 867
7453c96b 868 refcount = s->get_refcount(refcount_block, block_index);
0e06528e
HR
869 if (decrease ? (refcount - addend > refcount)
870 : (refcount + addend < refcount ||
871 refcount + addend > s->refcount_max))
2aabe7c7 872 {
09508d13
KW
873 ret = -EINVAL;
874 goto fail;
875 }
2aabe7c7
HR
876 if (decrease) {
877 refcount -= addend;
878 } else {
879 refcount += addend;
880 }
f7d0fe02
KW
881 if (refcount == 0 && cluster_index < s->free_cluster_index) {
882 s->free_cluster_index = cluster_index;
883 }
7453c96b 884 s->set_refcount(refcount_block, block_index, refcount);
0b919fae 885
f71c08ea
PB
886 if (refcount == 0) {
887 void *table;
888
6e6fa760 889 table = qcow2_cache_is_table_offset(s->refcount_block_cache,
f71c08ea
PB
890 offset);
891 if (table != NULL) {
2013c3d4 892 qcow2_cache_put(s->refcount_block_cache, &refcount_block);
dea9052e 893 old_table_index = -1;
77aadd7b 894 qcow2_cache_discard(s->refcount_block_cache, table);
f71c08ea
PB
895 }
896
6e6fa760 897 table = qcow2_cache_is_table_offset(s->l2_table_cache, offset);
f71c08ea 898 if (table != NULL) {
77aadd7b 899 qcow2_cache_discard(s->l2_table_cache, table);
f71c08ea
PB
900 }
901
902 if (s->discard_passthrough[type]) {
903 update_refcount_discard(bs, cluster_offset, s->cluster_size);
904 }
67af674e 905 }
f7d0fe02
KW
906 }
907
09508d13
KW
908 ret = 0;
909fail:
0b919fae
KW
910 if (!s->cache_discards) {
911 qcow2_process_discards(bs, ret);
912 }
913
f7d0fe02 914 /* Write last changed block to disk */
29c1a730 915 if (refcount_block) {
2013c3d4 916 qcow2_cache_put(s->refcount_block_cache, &refcount_block);
f7d0fe02
KW
917 }
918
09508d13
KW
919 /*
920 * Try do undo any updates if an error is returned (This may succeed in
921 * some cases like ENOSPC for allocating a new refcount block)
922 */
923 if (ret < 0) {
924 int dummy;
2aabe7c7
HR
925 dummy = update_refcount(bs, offset, cluster_offset - offset, addend,
926 !decrease, QCOW2_DISCARD_NEVER);
83e3f76c 927 (void)dummy;
09508d13
KW
928 }
929
930 return ret;
f7d0fe02
KW
931}
932
018faafd 933/*
44751917 934 * Increases or decreases the refcount of a given cluster.
018faafd 935 *
2aabe7c7
HR
936 * @addend is the absolute value of the addend; if @decrease is set, @addend
937 * will be subtracted from the current refcount, otherwise it will be added.
938 *
c6e9d8ae 939 * On success 0 is returned; on failure -errno is returned.
018faafd 940 */
32b6444d
HR
941int qcow2_update_cluster_refcount(BlockDriverState *bs,
942 int64_t cluster_index,
0e06528e 943 uint64_t addend, bool decrease,
32b6444d 944 enum qcow2_discard_type type)
f7d0fe02 945{
ff99129a 946 BDRVQcow2State *s = bs->opaque;
f7d0fe02
KW
947 int ret;
948
6cfcb9b8 949 ret = update_refcount(bs, cluster_index << s->cluster_bits, 1, addend,
2aabe7c7 950 decrease, type);
f7d0fe02
KW
951 if (ret < 0) {
952 return ret;
953 }
954
c6e9d8ae 955 return 0;
f7d0fe02
KW
956}
957
958
959
960/*********************************************************/
961/* cluster allocation functions */
962
963
964
965/* return < 0 if error */
77d6a215
EB
966static int64_t alloc_clusters_noref(BlockDriverState *bs, uint64_t size,
967 uint64_t max)
f7d0fe02 968{
ff99129a 969 BDRVQcow2State *s = bs->opaque;
0e06528e 970 uint64_t i, nb_clusters, refcount;
7324c10f 971 int ret;
f7d0fe02 972
ecbda7a2
KW
973 /* We can't allocate clusters if they may still be queued for discard. */
974 if (s->cache_discards) {
975 qcow2_process_discards(bs, 0);
976 }
977
f7d0fe02
KW
978 nb_clusters = size_to_clusters(s, size);
979retry:
980 for(i = 0; i < nb_clusters; i++) {
bb572aef 981 uint64_t next_cluster_index = s->free_cluster_index++;
7324c10f 982 ret = qcow2_get_refcount(bs, next_cluster_index, &refcount);
2eaa8f63 983
7324c10f
HR
984 if (ret < 0) {
985 return ret;
2eaa8f63 986 } else if (refcount != 0) {
f7d0fe02 987 goto retry;
2eaa8f63 988 }
f7d0fe02 989 }
91f827dc
HR
990
991 /* Make sure that all offsets in the "allocated" range are representable
77d6a215 992 * in the requested max */
65f33bc0 993 if (s->free_cluster_index > 0 &&
77d6a215 994 s->free_cluster_index - 1 > (max >> s->cluster_bits))
65f33bc0 995 {
91f827dc
HR
996 return -EFBIG;
997 }
998
f7d0fe02 999#ifdef DEBUG_ALLOC2
35ee5e39 1000 fprintf(stderr, "alloc_clusters: size=%" PRId64 " -> %" PRId64 "\n",
f7d0fe02
KW
1001 size,
1002 (s->free_cluster_index - nb_clusters) << s->cluster_bits);
1003#endif
1004 return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
1005}
1006
bb572aef 1007int64_t qcow2_alloc_clusters(BlockDriverState *bs, uint64_t size)
f7d0fe02
KW
1008{
1009 int64_t offset;
db3a964f 1010 int ret;
f7d0fe02 1011
66f82cee 1012 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);
b106ad91 1013 do {
77d6a215 1014 offset = alloc_clusters_noref(bs, size, QCOW_MAX_CLUSTER_OFFSET);
b106ad91
KW
1015 if (offset < 0) {
1016 return offset;
1017 }
1018
2aabe7c7 1019 ret = update_refcount(bs, offset, size, 1, false, QCOW2_DISCARD_NEVER);
b106ad91 1020 } while (ret == -EAGAIN);
2eaa8f63 1021
db3a964f
KW
1022 if (ret < 0) {
1023 return ret;
1024 }
1c4c2814 1025
f7d0fe02
KW
1026 return offset;
1027}
1028
b6d36def
HR
1029int64_t qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset,
1030 int64_t nb_clusters)
256900b1 1031{
ff99129a 1032 BDRVQcow2State *s = bs->opaque;
0e06528e 1033 uint64_t cluster_index, refcount;
33304ec9 1034 uint64_t i;
7324c10f 1035 int ret;
33304ec9
HT
1036
1037 assert(nb_clusters >= 0);
1038 if (nb_clusters == 0) {
1039 return 0;
1040 }
256900b1 1041
b106ad91
KW
1042 do {
1043 /* Check how many clusters there are free */
1044 cluster_index = offset >> s->cluster_bits;
1045 for(i = 0; i < nb_clusters; i++) {
7324c10f
HR
1046 ret = qcow2_get_refcount(bs, cluster_index++, &refcount);
1047 if (ret < 0) {
1048 return ret;
b106ad91
KW
1049 } else if (refcount != 0) {
1050 break;
1051 }
256900b1 1052 }
256900b1 1053
b106ad91 1054 /* And then allocate them */
2aabe7c7 1055 ret = update_refcount(bs, offset, i << s->cluster_bits, 1, false,
b106ad91
KW
1056 QCOW2_DISCARD_NEVER);
1057 } while (ret == -EAGAIN);
f24423bd 1058
256900b1
KW
1059 if (ret < 0) {
1060 return ret;
1061 }
1062
1063 return i;
1064}
1065
f7d0fe02
KW
1066/* only used to allocate compressed sectors. We try to allocate
1067 contiguous sectors. size must be <= cluster_size */
ed6ccf0f 1068int64_t qcow2_alloc_bytes(BlockDriverState *bs, int size)
f7d0fe02 1069{
ff99129a 1070 BDRVQcow2State *s = bs->opaque;
8c44dfbc
HR
1071 int64_t offset;
1072 size_t free_in_cluster;
1073 int ret;
f7d0fe02 1074
66f82cee 1075 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_BYTES);
f7d0fe02 1076 assert(size > 0 && size <= s->cluster_size);
8c44dfbc
HR
1077 assert(!s->free_byte_offset || offset_into_cluster(s, s->free_byte_offset));
1078
1079 offset = s->free_byte_offset;
1080
1081 if (offset) {
0e06528e 1082 uint64_t refcount;
7324c10f
HR
1083 ret = qcow2_get_refcount(bs, offset >> s->cluster_bits, &refcount);
1084 if (ret < 0) {
1085 return ret;
5d757b56 1086 }
8c44dfbc 1087
346a53df 1088 if (refcount == s->refcount_max) {
8c44dfbc 1089 offset = 0;
5d757b56 1090 }
8c44dfbc
HR
1091 }
1092
1093 free_in_cluster = s->cluster_size - offset_into_cluster(s, offset);
3e5feb62
JM
1094 do {
1095 if (!offset || free_in_cluster < size) {
77d6a215
EB
1096 int64_t new_cluster;
1097
1098 new_cluster = alloc_clusters_noref(bs, s->cluster_size,
1099 MIN(s->cluster_offset_mask,
1100 QCOW_MAX_CLUSTER_OFFSET));
3e5feb62
JM
1101 if (new_cluster < 0) {
1102 return new_cluster;
1103 }
8c44dfbc 1104
8aa34834
AG
1105 if (new_cluster == 0) {
1106 qcow2_signal_corruption(bs, true, -1, -1, "Preventing invalid "
1107 "allocation of compressed cluster "
1108 "at offset 0");
1109 return -EIO;
1110 }
1111
3e5feb62
JM
1112 if (!offset || ROUND_UP(offset, s->cluster_size) != new_cluster) {
1113 offset = new_cluster;
2ac01520
HR
1114 free_in_cluster = s->cluster_size;
1115 } else {
1116 free_in_cluster += s->cluster_size;
3e5feb62 1117 }
f7d0fe02 1118 }
29216ed1 1119
3e5feb62
JM
1120 assert(offset);
1121 ret = update_refcount(bs, offset, size, 1, false, QCOW2_DISCARD_NEVER);
2ac01520
HR
1122 if (ret < 0) {
1123 offset = 0;
1124 }
3e5feb62 1125 } while (ret == -EAGAIN);
8c44dfbc
HR
1126 if (ret < 0) {
1127 return ret;
1128 }
1129
1130 /* The cluster refcount was incremented; refcount blocks must be flushed
1131 * before the caller's L2 table updates. */
c1f5bafd 1132 qcow2_cache_set_dependency(bs, s->l2_table_cache, s->refcount_block_cache);
8c44dfbc
HR
1133
1134 s->free_byte_offset = offset + size;
1135 if (!offset_into_cluster(s, s->free_byte_offset)) {
1136 s->free_byte_offset = 0;
1137 }
1138
f7d0fe02
KW
1139 return offset;
1140}
1141
ed6ccf0f 1142void qcow2_free_clusters(BlockDriverState *bs,
6cfcb9b8
KW
1143 int64_t offset, int64_t size,
1144 enum qcow2_discard_type type)
f7d0fe02 1145{
db3a964f
KW
1146 int ret;
1147
66f82cee 1148 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_FREE);
2aabe7c7 1149 ret = update_refcount(bs, offset, size, 1, true, type);
db3a964f
KW
1150 if (ret < 0) {
1151 fprintf(stderr, "qcow2_free_clusters failed: %s\n", strerror(-ret));
003fad6e 1152 /* TODO Remember the clusters to free them later and avoid leaking */
db3a964f 1153 }
f7d0fe02
KW
1154}
1155
45aba42f 1156/*
c7a4c37a
KW
1157 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
1158 * normal cluster, compressed cluster, etc.)
45aba42f 1159 */
3fec237f
AG
1160void qcow2_free_any_cluster(BlockDriverState *bs, uint64_t l2_entry,
1161 enum qcow2_discard_type type)
45aba42f 1162{
ff99129a 1163 BDRVQcow2State *s = bs->opaque;
966b000f 1164 QCow2ClusterType ctype = qcow2_get_cluster_type(bs, l2_entry);
45aba42f 1165
966b000f
KW
1166 if (has_data_file(bs)) {
1167 if (s->discard_passthrough[type] &&
1168 (ctype == QCOW2_CLUSTER_NORMAL ||
1169 ctype == QCOW2_CLUSTER_ZERO_ALLOC))
1170 {
1171 bdrv_pdiscard(s->data_file, l2_entry & L2E_OFFSET_MASK,
3fec237f 1172 s->cluster_size);
966b000f
KW
1173 }
1174 return;
1175 }
1176
1177 switch (ctype) {
c7a4c37a
KW
1178 case QCOW2_CLUSTER_COMPRESSED:
1179 {
a6e09846
VSO
1180 uint64_t coffset;
1181 int csize;
1182
1183 qcow2_parse_compressed_l2_entry(bs, l2_entry, &coffset, &csize);
1184 qcow2_free_clusters(bs, coffset, csize, type);
c7a4c37a
KW
1185 }
1186 break;
1187 case QCOW2_CLUSTER_NORMAL:
fdfab37d
EB
1188 case QCOW2_CLUSTER_ZERO_ALLOC:
1189 if (offset_into_cluster(s, l2_entry & L2E_OFFSET_MASK)) {
1190 qcow2_signal_corruption(bs, false, -1, -1,
1191 "Cannot free unaligned cluster %#llx",
1192 l2_entry & L2E_OFFSET_MASK);
1193 } else {
1194 qcow2_free_clusters(bs, l2_entry & L2E_OFFSET_MASK,
3fec237f 1195 s->cluster_size, type);
8f730dd2 1196 }
c7a4c37a 1197 break;
fdfab37d 1198 case QCOW2_CLUSTER_ZERO_PLAIN:
c7a4c37a
KW
1199 case QCOW2_CLUSTER_UNALLOCATED:
1200 break;
1201 default:
1202 abort();
45aba42f 1203 }
45aba42f
KW
1204}
1205
8b220eb7
PB
1206int coroutine_fn qcow2_write_caches(BlockDriverState *bs)
1207{
1208 BDRVQcow2State *s = bs->opaque;
1209 int ret;
f7d0fe02 1210
8b220eb7
PB
1211 ret = qcow2_cache_write(bs, s->l2_table_cache);
1212 if (ret < 0) {
1213 return ret;
1214 }
1215
1216 if (qcow2_need_accurate_refcounts(s)) {
1217 ret = qcow2_cache_write(bs, s->refcount_block_cache);
1218 if (ret < 0) {
1219 return ret;
1220 }
1221 }
1222
1223 return 0;
1224}
1225
1226int coroutine_fn qcow2_flush_caches(BlockDriverState *bs)
1227{
1228 int ret = qcow2_write_caches(bs);
1229 if (ret < 0) {
1230 return ret;
1231 }
1232
1233 return bdrv_flush(bs->file->bs);
1234}
f7d0fe02
KW
1235
1236/*********************************************************/
1237/* snapshots and image creation */
1238
1239
1240
f7d0fe02 1241/* update the refcounts of snapshots and the copied flag */
ed6ccf0f
KW
1242int qcow2_update_snapshot_refcount(BlockDriverState *bs,
1243 int64_t l1_table_offset, int l1_size, int addend)
f7d0fe02 1244{
ff99129a 1245 BDRVQcow2State *s = bs->opaque;
83ad165b 1246 uint64_t *l1_table, *l2_slice, l2_offset, entry, l1_size2, refcount;
de82815d 1247 bool l1_allocated = false;
b32cbae1 1248 int64_t old_entry, old_l2_offset;
83ad165b 1249 unsigned slice, slice_size2, n_slices;
a6e09846 1250 int i, j, l1_modified = 0;
29c1a730 1251 int ret;
f7d0fe02 1252
2aabe7c7
HR
1253 assert(addend >= -1 && addend <= 1);
1254
83ad165b 1255 l2_slice = NULL;
f7d0fe02 1256 l1_table = NULL;
02b1ecfa 1257 l1_size2 = l1_size * L1E_SIZE;
c8fd8554 1258 slice_size2 = s->l2_slice_size * l2_entry_size(s);
83ad165b 1259 n_slices = s->cluster_size / slice_size2;
43a0cac4 1260
0b919fae
KW
1261 s->cache_discards = true;
1262
43a0cac4
KW
1263 /* WARNING: qcow2_snapshot_goto relies on this function not using the
1264 * l1_table_offset when it is the current s->l1_table_offset! Be careful
1265 * when changing this! */
f7d0fe02 1266 if (l1_table_offset != s->l1_table_offset) {
ef97d608 1267 l1_table = g_try_malloc0(l1_size2);
de82815d
KW
1268 if (l1_size2 && l1_table == NULL) {
1269 ret = -ENOMEM;
1270 goto fail;
1271 }
1272 l1_allocated = true;
c2bc78b6 1273
cf2ab8fc 1274 ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);
c2bc78b6 1275 if (ret < 0) {
f7d0fe02 1276 goto fail;
93913dfd
KW
1277 }
1278
b32cbae1 1279 for (i = 0; i < l1_size; i++) {
f7d0fe02 1280 be64_to_cpus(&l1_table[i]);
b32cbae1 1281 }
f7d0fe02
KW
1282 } else {
1283 assert(l1_size == s->l1_size);
1284 l1_table = s->l1_table;
de82815d 1285 l1_allocated = false;
f7d0fe02
KW
1286 }
1287
b32cbae1 1288 for (i = 0; i < l1_size; i++) {
f7d0fe02
KW
1289 l2_offset = l1_table[i];
1290 if (l2_offset) {
1291 old_l2_offset = l2_offset;
8e37f681 1292 l2_offset &= L1E_OFFSET_MASK;
29c1a730 1293
a97c67ee
HR
1294 if (offset_into_cluster(s, l2_offset)) {
1295 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
1296 PRIx64 " unaligned (L1 index: %#x)",
1297 l2_offset, i);
1298 ret = -EIO;
1299 goto fail;
1300 }
1301
83ad165b 1302 for (slice = 0; slice < n_slices; slice++) {
ca62dd5c 1303 ret = qcow2_cache_get(bs, s->l2_table_cache,
83ad165b
AG
1304 l2_offset + slice * slice_size2,
1305 (void **) &l2_slice);
ca62dd5c
AG
1306 if (ret < 0) {
1307 goto fail;
1308 }
29c1a730 1309
83ad165b 1310 for (j = 0; j < s->l2_slice_size; j++) {
ca62dd5c
AG
1311 uint64_t cluster_index;
1312 uint64_t offset;
1313
12c6aebe 1314 entry = get_l2_entry(s, l2_slice, j);
ca62dd5c
AG
1315 old_entry = entry;
1316 entry &= ~QCOW_OFLAG_COPIED;
1317 offset = entry & L2E_OFFSET_MASK;
1318
808c2bb4 1319 switch (qcow2_get_cluster_type(bs, entry)) {
ca62dd5c 1320 case QCOW2_CLUSTER_COMPRESSED:
ca62dd5c 1321 if (addend != 0) {
a6e09846
VSO
1322 uint64_t coffset;
1323 int csize;
1324
1325 qcow2_parse_compressed_l2_entry(bs, entry,
1326 &coffset, &csize);
ca62dd5c 1327 ret = update_refcount(
a6e09846 1328 bs, coffset, csize,
b6c24694 1329 abs(addend), addend < 0,
6cfcb9b8 1330 QCOW2_DISCARD_SNAPSHOT);
ca62dd5c
AG
1331 if (ret < 0) {
1332 goto fail;
1333 }
1334 }
1335 /* compressed clusters are never modified */
1336 refcount = 2;
1337 break;
1338
1339 case QCOW2_CLUSTER_NORMAL:
1340 case QCOW2_CLUSTER_ZERO_ALLOC:
1341 if (offset_into_cluster(s, offset)) {
83ad165b
AG
1342 /* Here l2_index means table (not slice) index */
1343 int l2_index = slice * s->l2_slice_size + j;
ca62dd5c
AG
1344 qcow2_signal_corruption(
1345 bs, true, -1, -1, "Cluster "
1346 "allocation offset %#" PRIx64
1347 " unaligned (L2 offset: %#"
1348 PRIx64 ", L2 index: %#x)",
83ad165b 1349 offset, l2_offset, l2_index);
ca62dd5c 1350 ret = -EIO;
a97c67ee
HR
1351 goto fail;
1352 }
1353
ca62dd5c
AG
1354 cluster_index = offset >> s->cluster_bits;
1355 assert(cluster_index);
1356 if (addend != 0) {
1357 ret = qcow2_update_cluster_refcount(
1358 bs, cluster_index, abs(addend), addend < 0,
1359 QCOW2_DISCARD_SNAPSHOT);
1360 if (ret < 0) {
1361 goto fail;
1362 }
1363 }
1364
1365 ret = qcow2_get_refcount(bs, cluster_index, &refcount);
7324c10f 1366 if (ret < 0) {
018faafd
KW
1367 goto fail;
1368 }
ca62dd5c 1369 break;
bbd995d8 1370
ca62dd5c
AG
1371 case QCOW2_CLUSTER_ZERO_PLAIN:
1372 case QCOW2_CLUSTER_UNALLOCATED:
1373 refcount = 0;
1374 break;
8b81a7b6 1375
ca62dd5c
AG
1376 default:
1377 abort();
1378 }
8b81a7b6 1379
ca62dd5c
AG
1380 if (refcount == 1) {
1381 entry |= QCOW_OFLAG_COPIED;
1382 }
1383 if (entry != old_entry) {
1384 if (addend > 0) {
1385 qcow2_cache_set_dependency(bs, s->l2_table_cache,
1386 s->refcount_block_cache);
1387 }
12c6aebe 1388 set_l2_entry(s, l2_slice, j, entry);
ca62dd5c 1389 qcow2_cache_entry_mark_dirty(s->l2_table_cache,
83ad165b 1390 l2_slice);
f7d0fe02
KW
1391 }
1392 }
29c1a730 1393
83ad165b 1394 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
ca62dd5c 1395 }
29c1a730 1396
f7d0fe02 1397 if (addend != 0) {
c6e9d8ae
HR
1398 ret = qcow2_update_cluster_refcount(bs, l2_offset >>
1399 s->cluster_bits,
2aabe7c7 1400 abs(addend), addend < 0,
c6e9d8ae
HR
1401 QCOW2_DISCARD_SNAPSHOT);
1402 if (ret < 0) {
1403 goto fail;
1404 }
f7d0fe02 1405 }
7324c10f
HR
1406 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1407 &refcount);
1408 if (ret < 0) {
018faafd
KW
1409 goto fail;
1410 } else if (refcount == 1) {
f7d0fe02
KW
1411 l2_offset |= QCOW_OFLAG_COPIED;
1412 }
1413 if (l2_offset != old_l2_offset) {
1414 l1_table[i] = l2_offset;
1415 l1_modified = 1;
1416 }
1417 }
1418 }
93913dfd 1419
2154f24e 1420 ret = bdrv_flush(bs);
93913dfd 1421fail:
83ad165b
AG
1422 if (l2_slice) {
1423 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
93913dfd
KW
1424 }
1425
0b919fae
KW
1426 s->cache_discards = false;
1427 qcow2_process_discards(bs, ret);
1428
43a0cac4 1429 /* Update L1 only if it isn't deleted anyway (addend = -1) */
c2b6ff51
KW
1430 if (ret == 0 && addend >= 0 && l1_modified) {
1431 for (i = 0; i < l1_size; i++) {
f7d0fe02 1432 cpu_to_be64s(&l1_table[i]);
c2b6ff51
KW
1433 }
1434
d9ca2ea2 1435 ret = bdrv_pwrite_sync(bs->file, l1_table_offset,
9a4f4c31 1436 l1_table, l1_size2);
c2b6ff51
KW
1437
1438 for (i = 0; i < l1_size; i++) {
f7d0fe02 1439 be64_to_cpus(&l1_table[i]);
c2b6ff51 1440 }
f7d0fe02
KW
1441 }
1442 if (l1_allocated)
7267c094 1443 g_free(l1_table);
93913dfd 1444 return ret;
f7d0fe02
KW
1445}
1446
1447
1448
1449
1450/*********************************************************/
1451/* refcount checking functions */
1452
1453
c2551b47 1454static uint64_t refcount_array_byte_size(BDRVQcow2State *s, uint64_t entries)
5fee192e
HR
1455{
1456 /* This assertion holds because there is no way we can address more than
1457 * 2^(64 - 9) clusters at once (with cluster size 512 = 2^9, and because
1458 * offsets have to be representable in bytes); due to every cluster
1459 * corresponding to one refcount entry, we are well below that limit */
1460 assert(entries < (UINT64_C(1) << (64 - 9)));
1461
1462 /* Thanks to the assertion this will not overflow, because
1463 * s->refcount_order < 7.
1464 * (note: x << s->refcount_order == x * s->refcount_bits) */
1465 return DIV_ROUND_UP(entries << s->refcount_order, 8);
1466}
1467
1468/**
1469 * Reallocates *array so that it can hold new_size entries. *size must contain
1470 * the current number of entries in *array. If the reallocation fails, *array
1471 * and *size will not be modified and -errno will be returned. If the
1472 * reallocation is successful, *array will be set to the new buffer, *size
1473 * will be set to new_size and 0 will be returned. The size of the reallocated
1474 * refcount array buffer will be aligned to a cluster boundary, and the newly
1475 * allocated area will be zeroed.
1476 */
ff99129a 1477static int realloc_refcount_array(BDRVQcow2State *s, void **array,
5fee192e
HR
1478 int64_t *size, int64_t new_size)
1479{
b6d36def 1480 int64_t old_byte_size, new_byte_size;
7453c96b 1481 void *new_ptr;
5fee192e
HR
1482
1483 /* Round to clusters so the array can be directly written to disk */
1484 old_byte_size = size_to_clusters(s, refcount_array_byte_size(s, *size))
1485 * s->cluster_size;
1486 new_byte_size = size_to_clusters(s, refcount_array_byte_size(s, new_size))
1487 * s->cluster_size;
1488
1489 if (new_byte_size == old_byte_size) {
1490 *size = new_size;
1491 return 0;
1492 }
1493
1494 assert(new_byte_size > 0);
1495
b6d36def
HR
1496 if (new_byte_size > SIZE_MAX) {
1497 return -ENOMEM;
1498 }
1499
5fee192e
HR
1500 new_ptr = g_try_realloc(*array, new_byte_size);
1501 if (!new_ptr) {
1502 return -ENOMEM;
1503 }
1504
1505 if (new_byte_size > old_byte_size) {
b6d36def 1506 memset((char *)new_ptr + old_byte_size, 0,
5fee192e
HR
1507 new_byte_size - old_byte_size);
1508 }
1509
1510 *array = new_ptr;
1511 *size = new_size;
1512
1513 return 0;
1514}
f7d0fe02
KW
1515
1516/*
1517 * Increases the refcount for a range of clusters in a given refcount table.
1518 * This is used to construct a temporary refcount table out of L1 and L2 tables
b6af0975 1519 * which can be compared to the refcount table saved in the image.
f7d0fe02 1520 *
9ac228e0 1521 * Modifies the number of errors in res.
f7d0fe02 1522 */
8a5bb1f1
VSO
1523int qcow2_inc_refcounts_imrt(BlockDriverState *bs, BdrvCheckResult *res,
1524 void **refcount_table,
1525 int64_t *refcount_table_size,
1526 int64_t offset, int64_t size)
f7d0fe02 1527{
ff99129a 1528 BDRVQcow2State *s = bs->opaque;
7453c96b 1529 uint64_t start, last, cluster_offset, k, refcount;
a5fff8d4 1530 int64_t file_len;
5fee192e 1531 int ret;
f7d0fe02 1532
fef4d3d5
HR
1533 if (size <= 0) {
1534 return 0;
1535 }
f7d0fe02 1536
a5fff8d4
VSO
1537 file_len = bdrv_getlength(bs->file->bs);
1538 if (file_len < 0) {
1539 return file_len;
1540 }
1541
1542 /*
1543 * Last cluster of qcow2 image may be semi-allocated, so it may be OK to
1544 * reference some space after file end but it should be less than one
1545 * cluster.
1546 */
1547 if (offset + size - file_len >= s->cluster_size) {
1548 fprintf(stderr, "ERROR: counting reference for region exceeding the "
1549 "end of the file by one cluster or more: offset 0x%" PRIx64
1550 " size 0x%" PRIx64 "\n", offset, size);
1551 res->corruptions++;
1552 return 0;
1553 }
1554
ac95acdb
HT
1555 start = start_of_cluster(s, offset);
1556 last = start_of_cluster(s, offset + size - 1);
f7d0fe02
KW
1557 for(cluster_offset = start; cluster_offset <= last;
1558 cluster_offset += s->cluster_size) {
1559 k = cluster_offset >> s->cluster_bits;
641bb63c 1560 if (k >= *refcount_table_size) {
5fee192e
HR
1561 ret = realloc_refcount_array(s, refcount_table,
1562 refcount_table_size, k + 1);
1563 if (ret < 0) {
641bb63c 1564 res->check_errors++;
5fee192e 1565 return ret;
f7d0fe02 1566 }
641bb63c
HR
1567 }
1568
7453c96b
HR
1569 refcount = s->get_refcount(*refcount_table, k);
1570 if (refcount == s->refcount_max) {
641bb63c
HR
1571 fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64
1572 "\n", cluster_offset);
03bb78ed
HR
1573 fprintf(stderr, "Use qemu-img amend to increase the refcount entry "
1574 "width or qemu-img convert to create a clean copy if the "
1575 "image cannot be opened for writing\n");
641bb63c 1576 res->corruptions++;
7453c96b 1577 continue;
f7d0fe02 1578 }
7453c96b 1579 s->set_refcount(*refcount_table, k, refcount + 1);
f7d0fe02 1580 }
fef4d3d5
HR
1581
1582 return 0;
f7d0fe02
KW
1583}
1584
801f7044
SH
1585/* Flags for check_refcounts_l1() and check_refcounts_l2() */
1586enum {
fba31bae 1587 CHECK_FRAG_INFO = 0x2, /* update BlockFragInfo counters */
801f7044
SH
1588};
1589
a2debf65 1590/*
5c3216c0
VSO
1591 * Fix L2 entry by making it QCOW2_CLUSTER_ZERO_PLAIN (or making all its present
1592 * subclusters QCOW2_SUBCLUSTER_ZERO_PLAIN).
a2debf65
VSO
1593 *
1594 * This function decrements res->corruptions on success, so the caller is
1595 * responsible to increment res->corruptions prior to the call.
1596 *
1597 * On failure in-memory @l2_table may be modified.
1598 */
1599static int fix_l2_entry_by_zero(BlockDriverState *bs, BdrvCheckResult *res,
1600 uint64_t l2_offset,
1601 uint64_t *l2_table, int l2_index, bool active,
1602 bool *metadata_overlap)
1603{
1604 BDRVQcow2State *s = bs->opaque;
1605 int ret;
1606 int idx = l2_index * (l2_entry_size(s) / sizeof(uint64_t));
1607 uint64_t l2e_offset = l2_offset + (uint64_t)l2_index * l2_entry_size(s);
1608 int ign = active ? QCOW2_OL_ACTIVE_L2 : QCOW2_OL_INACTIVE_L2;
a2debf65 1609
5c3216c0
VSO
1610 if (has_subclusters(s)) {
1611 uint64_t l2_bitmap = get_l2_bitmap(s, l2_table, l2_index);
1612
1613 /* Allocated subclusters become zero */
1614 l2_bitmap |= l2_bitmap << 32;
1615 l2_bitmap &= QCOW_L2_BITMAP_ALL_ZEROES;
1616
1617 set_l2_bitmap(s, l2_table, l2_index, l2_bitmap);
1618 set_l2_entry(s, l2_table, l2_index, 0);
1619 } else {
1620 set_l2_entry(s, l2_table, l2_index, QCOW_OFLAG_ZERO);
1621 }
1622
a2debf65
VSO
1623 ret = qcow2_pre_write_overlap_check(bs, ign, l2e_offset, l2_entry_size(s),
1624 false);
1625 if (metadata_overlap) {
1626 *metadata_overlap = ret < 0;
1627 }
1628 if (ret < 0) {
1629 fprintf(stderr, "ERROR: Overlap check failed\n");
1630 goto fail;
1631 }
1632
1633 ret = bdrv_pwrite_sync(bs->file, l2e_offset, &l2_table[idx],
1634 l2_entry_size(s));
1635 if (ret < 0) {
1636 fprintf(stderr, "ERROR: Failed to overwrite L2 "
1637 "table entry: %s\n", strerror(-ret));
1638 goto fail;
1639 }
1640
1641 res->corruptions--;
1642 res->corruptions_fixed++;
1643 return 0;
1644
1645fail:
1646 res->check_errors++;
1647 return ret;
1648}
1649
f7d0fe02
KW
1650/*
1651 * Increases the refcount in the given refcount table for the all clusters
1652 * referenced in the L2 table. While doing so, performs some checks on L2
1653 * entries.
1654 *
1655 * Returns the number of errors found by the checks or -errno if an internal
1656 * error occurred.
1657 */
9ac228e0 1658static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res,
7453c96b
HR
1659 void **refcount_table,
1660 int64_t *refcount_table_size, int64_t l2_offset,
1ef337b7 1661 int flags, BdrvCheckMode fix, bool active)
f7d0fe02 1662{
ff99129a 1663 BDRVQcow2State *s = bs->opaque;
9631c782 1664 uint64_t l2_entry, l2_bitmap;
fba31bae 1665 uint64_t next_contiguous_offset = 0;
a6e09846 1666 int i, ret;
786c22d9
VSO
1667 size_t l2_size_bytes = s->l2_size * l2_entry_size(s);
1668 g_autofree uint64_t *l2_table = g_malloc(l2_size_bytes);
a2debf65 1669 bool metadata_overlap;
f7d0fe02
KW
1670
1671 /* Read L2 table from disk */
786c22d9 1672 ret = bdrv_pread(bs->file, l2_offset, l2_table, l2_size_bytes);
ad27390c
HR
1673 if (ret < 0) {
1674 fprintf(stderr, "ERROR: I/O error in check_refcounts_l2\n");
1675 res->check_errors++;
786c22d9 1676 return ret;
ad27390c 1677 }
f7d0fe02
KW
1678
1679 /* Do the actual checks */
786c22d9 1680 for (i = 0; i < s->l2_size; i++) {
a6e09846
VSO
1681 uint64_t coffset;
1682 int csize;
12c6aebe 1683 l2_entry = get_l2_entry(s, l2_table, i);
9631c782 1684 l2_bitmap = get_l2_bitmap(s, l2_table, i);
afdf0abe 1685
808c2bb4 1686 switch (qcow2_get_cluster_type(bs, l2_entry)) {
afdf0abe
KW
1687 case QCOW2_CLUSTER_COMPRESSED:
1688 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1689 if (l2_entry & QCOW_OFLAG_COPIED) {
74c44a59 1690 fprintf(stderr, "ERROR: coffset=0x%" PRIx64 ": "
afdf0abe 1691 "copied flag must never be set for compressed "
74c44a59 1692 "clusters\n", l2_entry & s->cluster_offset_mask);
afdf0abe
KW
1693 l2_entry &= ~QCOW_OFLAG_COPIED;
1694 res->corruptions++;
1695 }
f7d0fe02 1696
e9f5b6de
KW
1697 if (has_data_file(bs)) {
1698 fprintf(stderr, "ERROR compressed cluster %d with data file, "
1699 "entry=0x%" PRIx64 "\n", i, l2_entry);
1700 res->corruptions++;
1701 break;
1702 }
1703
9631c782
VSO
1704 if (l2_bitmap) {
1705 fprintf(stderr, "ERROR compressed cluster %d with non-zero "
1706 "subcluster allocation bitmap, entry=0x%" PRIx64 "\n",
1707 i, l2_entry);
1708 res->corruptions++;
1709 break;
1710 }
1711
afdf0abe 1712 /* Mark cluster as used */
a6e09846 1713 qcow2_parse_compressed_l2_entry(bs, l2_entry, &coffset, &csize);
b6c24694 1714 ret = qcow2_inc_refcounts_imrt(
a6e09846 1715 bs, res, refcount_table, refcount_table_size, coffset, csize);
fef4d3d5 1716 if (ret < 0) {
786c22d9 1717 return ret;
fef4d3d5 1718 }
fba31bae
SH
1719
1720 if (flags & CHECK_FRAG_INFO) {
1721 res->bfi.allocated_clusters++;
4db35162 1722 res->bfi.compressed_clusters++;
fba31bae 1723
786c22d9
VSO
1724 /*
1725 * Compressed clusters are fragmented by nature. Since they
fba31bae
SH
1726 * take up sub-sector space but we only have sector granularity
1727 * I/O we need to re-read the same sectors even for adjacent
1728 * compressed clusters.
1729 */
1730 res->bfi.fragmented_clusters++;
1731 }
afdf0abe 1732 break;
f7d0fe02 1733
fdfab37d 1734 case QCOW2_CLUSTER_ZERO_ALLOC:
afdf0abe
KW
1735 case QCOW2_CLUSTER_NORMAL:
1736 {
afdf0abe 1737 uint64_t offset = l2_entry & L2E_OFFSET_MASK;
f7d0fe02 1738
9631c782
VSO
1739 if ((l2_bitmap >> 32) & l2_bitmap) {
1740 res->corruptions++;
1741 fprintf(stderr, "ERROR offset=%" PRIx64 ": Allocated "
1742 "cluster has corrupted subcluster allocation bitmap\n",
1743 offset);
1744 }
1745
ac5b787a
HR
1746 /* Correct offsets are cluster aligned */
1747 if (offset_into_cluster(s, offset)) {
fc2e6528 1748 bool contains_data;
54b10010
VSO
1749 res->corruptions++;
1750
fc2e6528 1751 if (has_subclusters(s)) {
fc2e6528
AG
1752 contains_data = (l2_bitmap & QCOW_L2_BITMAP_ALL_ALLOC);
1753 } else {
1754 contains_data = !(l2_entry & QCOW_OFLAG_ZERO);
1755 }
1756
1757 if (!contains_data) {
1758 fprintf(stderr, "%s offset=%" PRIx64 ": Preallocated "
ac5b787a
HR
1759 "cluster is not properly aligned; L2 entry "
1760 "corrupted.\n",
1761 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR",
1762 offset);
1763 if (fix & BDRV_FIX_ERRORS) {
a2debf65
VSO
1764 ret = fix_l2_entry_by_zero(bs, res, l2_offset,
1765 l2_table, i, active,
1766 &metadata_overlap);
1767 if (metadata_overlap) {
786c22d9
VSO
1768 /*
1769 * Something is seriously wrong, so abort checking
1770 * this L2 table.
1771 */
1772 return ret;
ac5b787a
HR
1773 }
1774
a2debf65 1775 if (ret == 0) {
786c22d9
VSO
1776 /*
1777 * Skip marking the cluster as used
1778 * (it is unused now).
1779 */
ac5b787a
HR
1780 continue;
1781 }
a2debf65
VSO
1782
1783 /*
1784 * Failed to fix.
1785 * Do not abort, continue checking the rest of this
1786 * L2 table's entries.
1787 */
ac5b787a
HR
1788 }
1789 } else {
1790 fprintf(stderr, "ERROR offset=%" PRIx64 ": Data cluster is "
1791 "not properly aligned; L2 entry corrupted.\n", offset);
ac5b787a
HR
1792 }
1793 }
1794
cbb51e9f
VSO
1795 if (flags & CHECK_FRAG_INFO) {
1796 res->bfi.allocated_clusters++;
1797 if (next_contiguous_offset &&
1798 offset != next_contiguous_offset) {
1799 res->bfi.fragmented_clusters++;
1800 }
1801 next_contiguous_offset = offset + s->cluster_size;
1802 }
1803
afdf0abe 1804 /* Mark cluster as used */
e9f5b6de
KW
1805 if (!has_data_file(bs)) {
1806 ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table,
1807 refcount_table_size,
1808 offset, s->cluster_size);
1809 if (ret < 0) {
786c22d9 1810 return ret;
e9f5b6de 1811 }
fef4d3d5 1812 }
afdf0abe
KW
1813 break;
1814 }
1815
fdfab37d 1816 case QCOW2_CLUSTER_ZERO_PLAIN:
9631c782
VSO
1817 /* Impossible when image has subclusters */
1818 assert(!l2_bitmap);
1819 break;
1820
afdf0abe 1821 case QCOW2_CLUSTER_UNALLOCATED:
9631c782
VSO
1822 if (l2_bitmap & QCOW_L2_BITMAP_ALL_ALLOC) {
1823 res->corruptions++;
1824 fprintf(stderr, "ERROR: Unallocated "
1825 "cluster has non-zero subcluster allocation map\n");
1826 }
afdf0abe
KW
1827 break;
1828
1829 default:
1830 abort();
f7d0fe02
KW
1831 }
1832 }
1833
9ac228e0 1834 return 0;
f7d0fe02
KW
1835}
1836
1837/*
1838 * Increases the refcount for the L1 table, its L2 tables and all referenced
1839 * clusters in the given refcount table. While doing so, performs some checks
1840 * on L1 and L2 entries.
1841 *
1842 * Returns the number of errors found by the checks or -errno if an internal
1843 * error occurred.
1844 */
1845static int check_refcounts_l1(BlockDriverState *bs,
9ac228e0 1846 BdrvCheckResult *res,
7453c96b 1847 void **refcount_table,
641bb63c 1848 int64_t *refcount_table_size,
f7d0fe02 1849 int64_t l1_table_offset, int l1_size,
1ef337b7 1850 int flags, BdrvCheckMode fix, bool active)
f7d0fe02 1851{
ff99129a 1852 BDRVQcow2State *s = bs->opaque;
fef4d3d5 1853 uint64_t *l1_table = NULL, l2_offset, l1_size2;
4f6ed88c 1854 int i, ret;
f7d0fe02 1855
02b1ecfa 1856 l1_size2 = l1_size * L1E_SIZE;
f7d0fe02
KW
1857
1858 /* Mark L1 table as used */
8a5bb1f1
VSO
1859 ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, refcount_table_size,
1860 l1_table_offset, l1_size2);
fef4d3d5
HR
1861 if (ret < 0) {
1862 goto fail;
1863 }
f7d0fe02
KW
1864
1865 /* Read L1 table entries from disk */
fef4d3d5 1866 if (l1_size2 > 0) {
de82815d
KW
1867 l1_table = g_try_malloc(l1_size2);
1868 if (l1_table == NULL) {
1869 ret = -ENOMEM;
ad27390c 1870 res->check_errors++;
de82815d
KW
1871 goto fail;
1872 }
cf2ab8fc 1873 ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);
ad27390c
HR
1874 if (ret < 0) {
1875 fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
1876 res->check_errors++;
702ef63f 1877 goto fail;
ad27390c 1878 }
702ef63f
KW
1879 for(i = 0;i < l1_size; i++)
1880 be64_to_cpus(&l1_table[i]);
1881 }
f7d0fe02
KW
1882
1883 /* Do the actual checks */
1884 for(i = 0; i < l1_size; i++) {
1885 l2_offset = l1_table[i];
1886 if (l2_offset) {
f7d0fe02 1887 /* Mark L2 table as used */
afdf0abe 1888 l2_offset &= L1E_OFFSET_MASK;
8a5bb1f1
VSO
1889 ret = qcow2_inc_refcounts_imrt(bs, res,
1890 refcount_table, refcount_table_size,
1891 l2_offset, s->cluster_size);
fef4d3d5
HR
1892 if (ret < 0) {
1893 goto fail;
1894 }
f7d0fe02
KW
1895
1896 /* L2 tables are cluster aligned */
ac95acdb 1897 if (offset_into_cluster(s, l2_offset)) {
f7d0fe02
KW
1898 fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "
1899 "cluster aligned; L1 entry corrupted\n", l2_offset);
9ac228e0 1900 res->corruptions++;
f7d0fe02
KW
1901 }
1902
1903 /* Process and check L2 entries */
9ac228e0 1904 ret = check_refcounts_l2(bs, res, refcount_table,
ac5b787a 1905 refcount_table_size, l2_offset, flags,
1ef337b7 1906 fix, active);
f7d0fe02
KW
1907 if (ret < 0) {
1908 goto fail;
1909 }
f7d0fe02
KW
1910 }
1911 }
7267c094 1912 g_free(l1_table);
9ac228e0 1913 return 0;
f7d0fe02
KW
1914
1915fail:
7267c094 1916 g_free(l1_table);
ad27390c 1917 return ret;
f7d0fe02
KW
1918}
1919
4f6ed88c
HR
1920/*
1921 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1922 *
1923 * This function does not print an error message nor does it increment
44751917
HR
1924 * check_errors if qcow2_get_refcount fails (this is because such an error will
1925 * have been already detected and sufficiently signaled by the calling function
4f6ed88c
HR
1926 * (qcow2_check_refcounts) by the time this function is called).
1927 */
e23e400e
HR
1928static int check_oflag_copied(BlockDriverState *bs, BdrvCheckResult *res,
1929 BdrvCheckMode fix)
4f6ed88c 1930{
ff99129a 1931 BDRVQcow2State *s = bs->opaque;
4f6ed88c
HR
1932 uint64_t *l2_table = qemu_blockalign(bs, s->cluster_size);
1933 int ret;
0e06528e 1934 uint64_t refcount;
4f6ed88c 1935 int i, j;
3cce51c9
HR
1936 bool repair;
1937
1938 if (fix & BDRV_FIX_ERRORS) {
1939 /* Always repair */
1940 repair = true;
1941 } else if (fix & BDRV_FIX_LEAKS) {
1942 /* Repair only if that seems safe: This function is always
1943 * called after the refcounts have been fixed, so the refcount
1944 * is accurate if that repair was successful */
1945 repair = !res->check_errors && !res->corruptions && !res->leaks;
1946 } else {
1947 repair = false;
1948 }
4f6ed88c
HR
1949
1950 for (i = 0; i < s->l1_size; i++) {
1951 uint64_t l1_entry = s->l1_table[i];
1952 uint64_t l2_offset = l1_entry & L1E_OFFSET_MASK;
7e3e736c 1953 int l2_dirty = 0;
4f6ed88c
HR
1954
1955 if (!l2_offset) {
1956 continue;
1957 }
1958
7324c10f
HR
1959 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1960 &refcount);
1961 if (ret < 0) {
4f6ed88c
HR
1962 /* don't print message nor increment check_errors */
1963 continue;
1964 }
1965 if ((refcount == 1) != ((l1_entry & QCOW_OFLAG_COPIED) != 0)) {
54b10010 1966 res->corruptions++;
e23e400e 1967 fprintf(stderr, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
0e06528e 1968 "l1_entry=%" PRIx64 " refcount=%" PRIu64 "\n",
3cce51c9
HR
1969 repair ? "Repairing" : "ERROR", i, l1_entry, refcount);
1970 if (repair) {
e23e400e
HR
1971 s->l1_table[i] = refcount == 1
1972 ? l1_entry | QCOW_OFLAG_COPIED
1973 : l1_entry & ~QCOW_OFLAG_COPIED;
1974 ret = qcow2_write_l1_entry(bs, i);
1975 if (ret < 0) {
1976 res->check_errors++;
1977 goto fail;
1978 }
54b10010 1979 res->corruptions--;
e23e400e 1980 res->corruptions_fixed++;
e23e400e 1981 }
4f6ed88c
HR
1982 }
1983
cf2ab8fc 1984 ret = bdrv_pread(bs->file, l2_offset, l2_table,
c8fd8554 1985 s->l2_size * l2_entry_size(s));
4f6ed88c
HR
1986 if (ret < 0) {
1987 fprintf(stderr, "ERROR: Could not read L2 table: %s\n",
1988 strerror(-ret));
1989 res->check_errors++;
1990 goto fail;
1991 }
1992
1993 for (j = 0; j < s->l2_size; j++) {
12c6aebe 1994 uint64_t l2_entry = get_l2_entry(s, l2_table, j);
4f6ed88c 1995 uint64_t data_offset = l2_entry & L2E_OFFSET_MASK;
808c2bb4 1996 QCow2ClusterType cluster_type = qcow2_get_cluster_type(bs, l2_entry);
4f6ed88c 1997
fdfab37d
EB
1998 if (cluster_type == QCOW2_CLUSTER_NORMAL ||
1999 cluster_type == QCOW2_CLUSTER_ZERO_ALLOC) {
e9f5b6de
KW
2000 if (has_data_file(bs)) {
2001 refcount = 1;
2002 } else {
2003 ret = qcow2_get_refcount(bs,
2004 data_offset >> s->cluster_bits,
2005 &refcount);
2006 if (ret < 0) {
2007 /* don't print message nor increment check_errors */
2008 continue;
2009 }
4f6ed88c
HR
2010 }
2011 if ((refcount == 1) != ((l2_entry & QCOW_OFLAG_COPIED) != 0)) {
54b10010 2012 res->corruptions++;
e23e400e 2013 fprintf(stderr, "%s OFLAG_COPIED data cluster: "
0e06528e 2014 "l2_entry=%" PRIx64 " refcount=%" PRIu64 "\n",
3cce51c9
HR
2015 repair ? "Repairing" : "ERROR", l2_entry, refcount);
2016 if (repair) {
12c6aebe
AG
2017 set_l2_entry(s, l2_table, j,
2018 refcount == 1 ?
2019 l2_entry | QCOW_OFLAG_COPIED :
2020 l2_entry & ~QCOW_OFLAG_COPIED);
7e3e736c 2021 l2_dirty++;
e23e400e 2022 }
4f6ed88c
HR
2023 }
2024 }
2025 }
e23e400e 2026
7e3e736c 2027 if (l2_dirty > 0) {
231bb267 2028 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L2,
966b000f
KW
2029 l2_offset, s->cluster_size,
2030 false);
e23e400e
HR
2031 if (ret < 0) {
2032 fprintf(stderr, "ERROR: Could not write L2 table; metadata "
2033 "overlap check failed: %s\n", strerror(-ret));
2034 res->check_errors++;
2035 goto fail;
2036 }
2037
d9ca2ea2 2038 ret = bdrv_pwrite(bs->file, l2_offset, l2_table,
9a4f4c31 2039 s->cluster_size);
e23e400e
HR
2040 if (ret < 0) {
2041 fprintf(stderr, "ERROR: Could not write L2 table: %s\n",
2042 strerror(-ret));
2043 res->check_errors++;
2044 goto fail;
2045 }
54b10010 2046 res->corruptions -= l2_dirty;
7e3e736c 2047 res->corruptions_fixed += l2_dirty;
e23e400e 2048 }
4f6ed88c
HR
2049 }
2050
2051 ret = 0;
2052
2053fail:
2054 qemu_vfree(l2_table);
2055 return ret;
2056}
2057
6ca56bf5
HR
2058/*
2059 * Checks consistency of refblocks and accounts for each refblock in
2060 * *refcount_table.
2061 */
2062static int check_refblocks(BlockDriverState *bs, BdrvCheckResult *res,
f307b255 2063 BdrvCheckMode fix, bool *rebuild,
7453c96b 2064 void **refcount_table, int64_t *nb_clusters)
6ca56bf5 2065{
ff99129a 2066 BDRVQcow2State *s = bs->opaque;
001c158d 2067 int64_t i, size;
fef4d3d5 2068 int ret;
6ca56bf5 2069
f7d0fe02 2070 for(i = 0; i < s->refcount_table_size; i++) {
6882c8fa 2071 uint64_t offset, cluster;
f7d0fe02 2072 offset = s->refcount_table[i];
6882c8fa 2073 cluster = offset >> s->cluster_bits;
746c3cb5
KW
2074
2075 /* Refcount blocks are cluster aligned */
ac95acdb 2076 if (offset_into_cluster(s, offset)) {
166acf54 2077 fprintf(stderr, "ERROR refcount block %" PRId64 " is not "
746c3cb5 2078 "cluster aligned; refcount table entry corrupted\n", i);
9ac228e0 2079 res->corruptions++;
f307b255 2080 *rebuild = true;
6882c8fa
KW
2081 continue;
2082 }
2083
6ca56bf5 2084 if (cluster >= *nb_clusters) {
54b10010 2085 res->corruptions++;
001c158d
HR
2086 fprintf(stderr, "%s refcount block %" PRId64 " is outside image\n",
2087 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
2088
2089 if (fix & BDRV_FIX_ERRORS) {
5fee192e 2090 int64_t new_nb_clusters;
ed3d2ec9 2091 Error *local_err = NULL;
001c158d
HR
2092
2093 if (offset > INT64_MAX - s->cluster_size) {
2094 ret = -EINVAL;
2095 goto resize_fail;
2096 }
2097
c80d8b06 2098 ret = bdrv_truncate(bs->file, offset + s->cluster_size, false,
7b8e4857 2099 PREALLOC_MODE_OFF, 0, &local_err);
001c158d 2100 if (ret < 0) {
ed3d2ec9 2101 error_report_err(local_err);
001c158d
HR
2102 goto resize_fail;
2103 }
9a4f4c31 2104 size = bdrv_getlength(bs->file->bs);
001c158d
HR
2105 if (size < 0) {
2106 ret = size;
2107 goto resize_fail;
2108 }
2109
5fee192e
HR
2110 new_nb_clusters = size_to_clusters(s, size);
2111 assert(new_nb_clusters >= *nb_clusters);
001c158d 2112
5fee192e
HR
2113 ret = realloc_refcount_array(s, refcount_table,
2114 nb_clusters, new_nb_clusters);
2115 if (ret < 0) {
001c158d 2116 res->check_errors++;
5fee192e 2117 return ret;
001c158d 2118 }
001c158d
HR
2119
2120 if (cluster >= *nb_clusters) {
2121 ret = -EINVAL;
2122 goto resize_fail;
2123 }
2124
54b10010 2125 res->corruptions--;
001c158d 2126 res->corruptions_fixed++;
8a5bb1f1
VSO
2127 ret = qcow2_inc_refcounts_imrt(bs, res,
2128 refcount_table, nb_clusters,
2129 offset, s->cluster_size);
001c158d
HR
2130 if (ret < 0) {
2131 return ret;
2132 }
2133 /* No need to check whether the refcount is now greater than 1:
2134 * This area was just allocated and zeroed, so it can only be
8a5bb1f1 2135 * exactly 1 after qcow2_inc_refcounts_imrt() */
001c158d
HR
2136 continue;
2137
2138resize_fail:
f307b255 2139 *rebuild = true;
001c158d
HR
2140 fprintf(stderr, "ERROR could not resize image: %s\n",
2141 strerror(-ret));
001c158d 2142 }
6882c8fa 2143 continue;
746c3cb5
KW
2144 }
2145
f7d0fe02 2146 if (offset != 0) {
8a5bb1f1
VSO
2147 ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, nb_clusters,
2148 offset, s->cluster_size);
fef4d3d5
HR
2149 if (ret < 0) {
2150 return ret;
2151 }
7453c96b 2152 if (s->get_refcount(*refcount_table, cluster) != 1) {
f307b255 2153 fprintf(stderr, "ERROR refcount block %" PRId64
7453c96b
HR
2154 " refcount=%" PRIu64 "\n", i,
2155 s->get_refcount(*refcount_table, cluster));
f307b255
HR
2156 res->corruptions++;
2157 *rebuild = true;
746c3cb5 2158 }
f7d0fe02
KW
2159 }
2160 }
2161
6ca56bf5
HR
2162 return 0;
2163}
2164
057a3fe5
HR
2165/*
2166 * Calculates an in-memory refcount table.
2167 */
2168static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
f307b255 2169 BdrvCheckMode fix, bool *rebuild,
7453c96b 2170 void **refcount_table, int64_t *nb_clusters)
057a3fe5 2171{
ff99129a 2172 BDRVQcow2State *s = bs->opaque;
057a3fe5
HR
2173 int64_t i;
2174 QCowSnapshot *sn;
2175 int ret;
2176
9696df21 2177 if (!*refcount_table) {
5fee192e
HR
2178 int64_t old_size = 0;
2179 ret = realloc_refcount_array(s, refcount_table,
2180 &old_size, *nb_clusters);
2181 if (ret < 0) {
9696df21 2182 res->check_errors++;
5fee192e 2183 return ret;
9696df21 2184 }
057a3fe5
HR
2185 }
2186
2187 /* header */
8a5bb1f1
VSO
2188 ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, nb_clusters,
2189 0, s->cluster_size);
fef4d3d5
HR
2190 if (ret < 0) {
2191 return ret;
2192 }
057a3fe5
HR
2193
2194 /* current L1 table */
641bb63c 2195 ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
ac5b787a 2196 s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO,
1ef337b7 2197 fix, true);
057a3fe5
HR
2198 if (ret < 0) {
2199 return ret;
2200 }
2201
2202 /* snapshots */
e9f5b6de
KW
2203 if (has_data_file(bs) && s->nb_snapshots) {
2204 fprintf(stderr, "ERROR %d snapshots in image with data file\n",
2205 s->nb_snapshots);
2206 res->corruptions++;
2207 }
2208
057a3fe5
HR
2209 for (i = 0; i < s->nb_snapshots; i++) {
2210 sn = s->snapshots + i;
0c2ada81
AG
2211 if (offset_into_cluster(s, sn->l1_table_offset)) {
2212 fprintf(stderr, "ERROR snapshot %s (%s) l1_offset=%#" PRIx64 ": "
2213 "L1 table is not cluster aligned; snapshot table entry "
2214 "corrupted\n", sn->id_str, sn->name, sn->l1_table_offset);
2215 res->corruptions++;
2216 continue;
2217 }
02b1ecfa 2218 if (sn->l1_size > QCOW_MAX_L1_SIZE / L1E_SIZE) {
0c2ada81
AG
2219 fprintf(stderr, "ERROR snapshot %s (%s) l1_size=%#" PRIx32 ": "
2220 "L1 table is too large; snapshot table entry corrupted\n",
2221 sn->id_str, sn->name, sn->l1_size);
2222 res->corruptions++;
2223 continue;
2224 }
641bb63c 2225 ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
1ef337b7
VSO
2226 sn->l1_table_offset, sn->l1_size, 0, fix,
2227 false);
057a3fe5
HR
2228 if (ret < 0) {
2229 return ret;
2230 }
2231 }
8a5bb1f1
VSO
2232 ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, nb_clusters,
2233 s->snapshots_offset, s->snapshots_size);
fef4d3d5
HR
2234 if (ret < 0) {
2235 return ret;
2236 }
057a3fe5
HR
2237
2238 /* refcount data */
8a5bb1f1
VSO
2239 ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, nb_clusters,
2240 s->refcount_table_offset,
02b1ecfa
AG
2241 s->refcount_table_size *
2242 REFTABLE_ENTRY_SIZE);
fef4d3d5
HR
2243 if (ret < 0) {
2244 return ret;
2245 }
057a3fe5 2246
4652b8f3
DB
2247 /* encryption */
2248 if (s->crypto_header.length) {
8a5bb1f1
VSO
2249 ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, nb_clusters,
2250 s->crypto_header.offset,
2251 s->crypto_header.length);
4652b8f3
DB
2252 if (ret < 0) {
2253 return ret;
2254 }
2255 }
2256
88ddffae
VSO
2257 /* bitmaps */
2258 ret = qcow2_check_bitmaps_refcounts(bs, res, refcount_table, nb_clusters);
2259 if (ret < 0) {
2260 return ret;
2261 }
2262
f307b255 2263 return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);
057a3fe5
HR
2264}
2265
6ca56bf5
HR
2266/*
2267 * Compares the actual reference count for each cluster in the image against the
2268 * refcount as reported by the refcount structures on-disk.
2269 */
2270static void compare_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
f307b255
HR
2271 BdrvCheckMode fix, bool *rebuild,
2272 int64_t *highest_cluster,
7453c96b 2273 void *refcount_table, int64_t nb_clusters)
6ca56bf5 2274{
ff99129a 2275 BDRVQcow2State *s = bs->opaque;
6ca56bf5 2276 int64_t i;
0e06528e 2277 uint64_t refcount1, refcount2;
7324c10f 2278 int ret;
6ca56bf5
HR
2279
2280 for (i = 0, *highest_cluster = 0; i < nb_clusters; i++) {
7324c10f
HR
2281 ret = qcow2_get_refcount(bs, i, &refcount1);
2282 if (ret < 0) {
166acf54 2283 fprintf(stderr, "Can't get refcount for cluster %" PRId64 ": %s\n",
7324c10f 2284 i, strerror(-ret));
9ac228e0 2285 res->check_errors++;
f74550fd 2286 continue;
018faafd
KW
2287 }
2288
7453c96b 2289 refcount2 = s->get_refcount(refcount_table, i);
c6bb9ad1
FS
2290
2291 if (refcount1 > 0 || refcount2 > 0) {
6ca56bf5 2292 *highest_cluster = i;
c6bb9ad1
FS
2293 }
2294
f7d0fe02 2295 if (refcount1 != refcount2) {
166acf54
KW
2296 /* Check if we're allowed to fix the mismatch */
2297 int *num_fixed = NULL;
f307b255
HR
2298 if (refcount1 == 0) {
2299 *rebuild = true;
2300 } else if (refcount1 > refcount2 && (fix & BDRV_FIX_LEAKS)) {
166acf54
KW
2301 num_fixed = &res->leaks_fixed;
2302 } else if (refcount1 < refcount2 && (fix & BDRV_FIX_ERRORS)) {
2303 num_fixed = &res->corruptions_fixed;
2304 }
2305
0e06528e
HR
2306 fprintf(stderr, "%s cluster %" PRId64 " refcount=%" PRIu64
2307 " reference=%" PRIu64 "\n",
166acf54
KW
2308 num_fixed != NULL ? "Repairing" :
2309 refcount1 < refcount2 ? "ERROR" :
2310 "Leaked",
f7d0fe02 2311 i, refcount1, refcount2);
166acf54
KW
2312
2313 if (num_fixed) {
2314 ret = update_refcount(bs, i << s->cluster_bits, 1,
2aabe7c7
HR
2315 refcount_diff(refcount1, refcount2),
2316 refcount1 > refcount2,
6cfcb9b8 2317 QCOW2_DISCARD_ALWAYS);
166acf54
KW
2318 if (ret >= 0) {
2319 (*num_fixed)++;
2320 continue;
2321 }
2322 }
2323
2324 /* And if we couldn't, print an error */
9ac228e0
KW
2325 if (refcount1 < refcount2) {
2326 res->corruptions++;
2327 } else {
2328 res->leaks++;
2329 }
f7d0fe02
KW
2330 }
2331 }
6ca56bf5
HR
2332}
2333
c7c0681b
HR
2334/*
2335 * Allocates clusters using an in-memory refcount table (IMRT) in contrast to
2336 * the on-disk refcount structures.
2337 *
2338 * On input, *first_free_cluster tells where to start looking, and need not
2339 * actually be a free cluster; the returned offset will not be before that
2340 * cluster. On output, *first_free_cluster points to the first gap found, even
2341 * if that gap was too small to be used as the returned offset.
2342 *
2343 * Note that *first_free_cluster is a cluster index whereas the return value is
2344 * an offset.
2345 */
2346static int64_t alloc_clusters_imrt(BlockDriverState *bs,
2347 int cluster_count,
7453c96b 2348 void **refcount_table,
c7c0681b
HR
2349 int64_t *imrt_nb_clusters,
2350 int64_t *first_free_cluster)
2351{
ff99129a 2352 BDRVQcow2State *s = bs->opaque;
c7c0681b
HR
2353 int64_t cluster = *first_free_cluster, i;
2354 bool first_gap = true;
2355 int contiguous_free_clusters;
5fee192e 2356 int ret;
c7c0681b
HR
2357
2358 /* Starting at *first_free_cluster, find a range of at least cluster_count
2359 * continuously free clusters */
2360 for (contiguous_free_clusters = 0;
2361 cluster < *imrt_nb_clusters &&
2362 contiguous_free_clusters < cluster_count;
2363 cluster++)
2364 {
7453c96b 2365 if (!s->get_refcount(*refcount_table, cluster)) {
c7c0681b
HR
2366 contiguous_free_clusters++;
2367 if (first_gap) {
2368 /* If this is the first free cluster found, update
2369 * *first_free_cluster accordingly */
2370 *first_free_cluster = cluster;
2371 first_gap = false;
2372 }
2373 } else if (contiguous_free_clusters) {
2374 contiguous_free_clusters = 0;
2375 }
2376 }
2377
2378 /* If contiguous_free_clusters is greater than zero, it contains the number
2379 * of continuously free clusters until the current cluster; the first free
2380 * cluster in the current "gap" is therefore
2381 * cluster - contiguous_free_clusters */
2382
2383 /* If no such range could be found, grow the in-memory refcount table
2384 * accordingly to append free clusters at the end of the image */
2385 if (contiguous_free_clusters < cluster_count) {
c7c0681b
HR
2386 /* contiguous_free_clusters clusters are already empty at the image end;
2387 * we need cluster_count clusters; therefore, we have to allocate
2388 * cluster_count - contiguous_free_clusters new clusters at the end of
2389 * the image (which is the current value of cluster; note that cluster
2390 * may exceed old_imrt_nb_clusters if *first_free_cluster pointed beyond
2391 * the image end) */
5fee192e
HR
2392 ret = realloc_refcount_array(s, refcount_table, imrt_nb_clusters,
2393 cluster + cluster_count
2394 - contiguous_free_clusters);
2395 if (ret < 0) {
2396 return ret;
c7c0681b 2397 }
c7c0681b
HR
2398 }
2399
2400 /* Go back to the first free cluster */
2401 cluster -= contiguous_free_clusters;
2402 for (i = 0; i < cluster_count; i++) {
7453c96b 2403 s->set_refcount(*refcount_table, cluster + i, 1);
c7c0681b
HR
2404 }
2405
2406 return cluster << s->cluster_bits;
2407}
2408
2409/*
2410 * Creates a new refcount structure based solely on the in-memory information
2411 * given through *refcount_table. All necessary allocations will be reflected
2412 * in that array.
2413 *
2414 * On success, the old refcount structure is leaked (it will be covered by the
2415 * new refcount structure).
2416 */
2417static int rebuild_refcount_structure(BlockDriverState *bs,
2418 BdrvCheckResult *res,
7453c96b 2419 void **refcount_table,
c7c0681b
HR
2420 int64_t *nb_clusters)
2421{
ff99129a 2422 BDRVQcow2State *s = bs->opaque;
c7c0681b
HR
2423 int64_t first_free_cluster = 0, reftable_offset = -1, cluster = 0;
2424 int64_t refblock_offset, refblock_start, refblock_index;
2425 uint32_t reftable_size = 0;
2426 uint64_t *on_disk_reftable = NULL;
7453c96b
HR
2427 void *on_disk_refblock;
2428 int ret = 0;
c7c0681b
HR
2429 struct {
2430 uint64_t reftable_offset;
2431 uint32_t reftable_clusters;
2432 } QEMU_PACKED reftable_offset_and_clusters;
2433
2434 qcow2_cache_empty(bs, s->refcount_block_cache);
2435
2436write_refblocks:
2437 for (; cluster < *nb_clusters; cluster++) {
7453c96b 2438 if (!s->get_refcount(*refcount_table, cluster)) {
c7c0681b
HR
2439 continue;
2440 }
2441
2442 refblock_index = cluster >> s->refcount_block_bits;
2443 refblock_start = refblock_index << s->refcount_block_bits;
2444
2445 /* Don't allocate a cluster in a refblock already written to disk */
2446 if (first_free_cluster < refblock_start) {
2447 first_free_cluster = refblock_start;
2448 }
2449 refblock_offset = alloc_clusters_imrt(bs, 1, refcount_table,
2450 nb_clusters, &first_free_cluster);
2451 if (refblock_offset < 0) {
2452 fprintf(stderr, "ERROR allocating refblock: %s\n",
2453 strerror(-refblock_offset));
2454 res->check_errors++;
2455 ret = refblock_offset;
2456 goto fail;
2457 }
2458
2459 if (reftable_size <= refblock_index) {
2460 uint32_t old_reftable_size = reftable_size;
2461 uint64_t *new_on_disk_reftable;
2462
02b1ecfa
AG
2463 reftable_size = ROUND_UP((refblock_index + 1) * REFTABLE_ENTRY_SIZE,
2464 s->cluster_size) / REFTABLE_ENTRY_SIZE;
c7c0681b
HR
2465 new_on_disk_reftable = g_try_realloc(on_disk_reftable,
2466 reftable_size *
02b1ecfa 2467 REFTABLE_ENTRY_SIZE);
c7c0681b
HR
2468 if (!new_on_disk_reftable) {
2469 res->check_errors++;
2470 ret = -ENOMEM;
2471 goto fail;
2472 }
2473 on_disk_reftable = new_on_disk_reftable;
2474
2475 memset(on_disk_reftable + old_reftable_size, 0,
02b1ecfa 2476 (reftable_size - old_reftable_size) * REFTABLE_ENTRY_SIZE);
c7c0681b
HR
2477
2478 /* The offset we have for the reftable is now no longer valid;
2479 * this will leak that range, but we can easily fix that by running
2480 * a leak-fixing check after this rebuild operation */
2481 reftable_offset = -1;
f80ac75d
PMD
2482 } else {
2483 assert(on_disk_reftable);
c7c0681b
HR
2484 }
2485 on_disk_reftable[refblock_index] = refblock_offset;
2486
2487 /* If this is apparently the last refblock (for now), try to squeeze the
2488 * reftable in */
2489 if (refblock_index == (*nb_clusters - 1) >> s->refcount_block_bits &&
2490 reftable_offset < 0)
2491 {
2492 uint64_t reftable_clusters = size_to_clusters(s, reftable_size *
02b1ecfa 2493 REFTABLE_ENTRY_SIZE);
c7c0681b
HR
2494 reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,
2495 refcount_table, nb_clusters,
2496 &first_free_cluster);
2497 if (reftable_offset < 0) {
2498 fprintf(stderr, "ERROR allocating reftable: %s\n",
2499 strerror(-reftable_offset));
2500 res->check_errors++;
2501 ret = reftable_offset;
2502 goto fail;
2503 }
2504 }
2505
2506 ret = qcow2_pre_write_overlap_check(bs, 0, refblock_offset,
966b000f 2507 s->cluster_size, false);
c7c0681b
HR
2508 if (ret < 0) {
2509 fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));
2510 goto fail;
2511 }
2512
7453c96b
HR
2513 /* The size of *refcount_table is always cluster-aligned, therefore the
2514 * write operation will not overflow */
2515 on_disk_refblock = (void *)((char *) *refcount_table +
2516 refblock_index * s->cluster_size);
c7c0681b 2517
e3b4257d
AG
2518 ret = bdrv_pwrite(bs->file, refblock_offset, on_disk_refblock,
2519 s->cluster_size);
c7c0681b
HR
2520 if (ret < 0) {
2521 fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));
2522 goto fail;
2523 }
2524
2525 /* Go to the end of this refblock */
2526 cluster = refblock_start + s->refcount_block_size - 1;
2527 }
2528
2529 if (reftable_offset < 0) {
2530 uint64_t post_refblock_start, reftable_clusters;
2531
2532 post_refblock_start = ROUND_UP(*nb_clusters, s->refcount_block_size);
02b1ecfa
AG
2533 reftable_clusters =
2534 size_to_clusters(s, reftable_size * REFTABLE_ENTRY_SIZE);
c7c0681b
HR
2535 /* Not pretty but simple */
2536 if (first_free_cluster < post_refblock_start) {
2537 first_free_cluster = post_refblock_start;
2538 }
2539 reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,
2540 refcount_table, nb_clusters,
2541 &first_free_cluster);
2542 if (reftable_offset < 0) {
2543 fprintf(stderr, "ERROR allocating reftable: %s\n",
2544 strerror(-reftable_offset));
2545 res->check_errors++;
2546 ret = reftable_offset;
2547 goto fail;
2548 }
2549
2550 goto write_refblocks;
2551 }
2552
c7c0681b
HR
2553 for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
2554 cpu_to_be64s(&on_disk_reftable[refblock_index]);
2555 }
2556
2557 ret = qcow2_pre_write_overlap_check(bs, 0, reftable_offset,
02b1ecfa 2558 reftable_size * REFTABLE_ENTRY_SIZE,
966b000f 2559 false);
c7c0681b
HR
2560 if (ret < 0) {
2561 fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));
2562 goto fail;
2563 }
2564
02b1ecfa 2565 assert(reftable_size < INT_MAX / REFTABLE_ENTRY_SIZE);
d9ca2ea2 2566 ret = bdrv_pwrite(bs->file, reftable_offset, on_disk_reftable,
02b1ecfa 2567 reftable_size * REFTABLE_ENTRY_SIZE);
c7c0681b
HR
2568 if (ret < 0) {
2569 fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));
2570 goto fail;
2571 }
2572
2573 /* Enter new reftable into the image header */
f1f7a1dd
PM
2574 reftable_offset_and_clusters.reftable_offset = cpu_to_be64(reftable_offset);
2575 reftable_offset_and_clusters.reftable_clusters =
02b1ecfa 2576 cpu_to_be32(size_to_clusters(s, reftable_size * REFTABLE_ENTRY_SIZE));
d9ca2ea2
KW
2577 ret = bdrv_pwrite_sync(bs->file,
2578 offsetof(QCowHeader, refcount_table_offset),
c7c0681b
HR
2579 &reftable_offset_and_clusters,
2580 sizeof(reftable_offset_and_clusters));
2581 if (ret < 0) {
2582 fprintf(stderr, "ERROR setting reftable: %s\n", strerror(-ret));
2583 goto fail;
2584 }
2585
2586 for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
2587 be64_to_cpus(&on_disk_reftable[refblock_index]);
2588 }
2589 s->refcount_table = on_disk_reftable;
2590 s->refcount_table_offset = reftable_offset;
2591 s->refcount_table_size = reftable_size;
7061a078 2592 update_max_refcount_table_index(s);
c7c0681b
HR
2593
2594 return 0;
2595
2596fail:
2597 g_free(on_disk_reftable);
2598 return ret;
2599}
2600
6ca56bf5
HR
2601/*
2602 * Checks an image for refcount consistency.
2603 *
2604 * Returns 0 if no errors are found, the number of errors in case the image is
2605 * detected as corrupted, and -errno when an internal error occurred.
2606 */
2607int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
2608 BdrvCheckMode fix)
2609{
ff99129a 2610 BDRVQcow2State *s = bs->opaque;
c7c0681b 2611 BdrvCheckResult pre_compare_res;
6ca56bf5 2612 int64_t size, highest_cluster, nb_clusters;
7453c96b 2613 void *refcount_table = NULL;
f307b255 2614 bool rebuild = false;
6ca56bf5
HR
2615 int ret;
2616
9a4f4c31 2617 size = bdrv_getlength(bs->file->bs);
6ca56bf5
HR
2618 if (size < 0) {
2619 res->check_errors++;
2620 return size;
2621 }
2622
2623 nb_clusters = size_to_clusters(s, size);
2624 if (nb_clusters > INT_MAX) {
2625 res->check_errors++;
2626 return -EFBIG;
2627 }
2628
2629 res->bfi.total_clusters =
2630 size_to_clusters(s, bs->total_sectors * BDRV_SECTOR_SIZE);
2631
f307b255
HR
2632 ret = calculate_refcounts(bs, res, fix, &rebuild, &refcount_table,
2633 &nb_clusters);
6ca56bf5
HR
2634 if (ret < 0) {
2635 goto fail;
2636 }
2637
c7c0681b
HR
2638 /* In case we don't need to rebuild the refcount structure (but want to fix
2639 * something), this function is immediately called again, in which case the
2640 * result should be ignored */
2641 pre_compare_res = *res;
2642 compare_refcounts(bs, res, 0, &rebuild, &highest_cluster, refcount_table,
6ca56bf5 2643 nb_clusters);
f7d0fe02 2644
c7c0681b 2645 if (rebuild && (fix & BDRV_FIX_ERRORS)) {
791230d8
HR
2646 BdrvCheckResult old_res = *res;
2647 int fresh_leaks = 0;
2648
c7c0681b
HR
2649 fprintf(stderr, "Rebuilding refcount structure\n");
2650 ret = rebuild_refcount_structure(bs, res, &refcount_table,
2651 &nb_clusters);
2652 if (ret < 0) {
2653 goto fail;
2654 }
791230d8
HR
2655
2656 res->corruptions = 0;
2657 res->leaks = 0;
2658
2659 /* Because the old reftable has been exchanged for a new one the
2660 * references have to be recalculated */
2661 rebuild = false;
7453c96b 2662 memset(refcount_table, 0, refcount_array_byte_size(s, nb_clusters));
791230d8
HR
2663 ret = calculate_refcounts(bs, res, 0, &rebuild, &refcount_table,
2664 &nb_clusters);
2665 if (ret < 0) {
2666 goto fail;
2667 }
2668
2669 if (fix & BDRV_FIX_LEAKS) {
2670 /* The old refcount structures are now leaked, fix it; the result
2671 * can be ignored, aside from leaks which were introduced by
2672 * rebuild_refcount_structure() that could not be fixed */
2673 BdrvCheckResult saved_res = *res;
2674 *res = (BdrvCheckResult){ 0 };
2675
2676 compare_refcounts(bs, res, BDRV_FIX_LEAKS, &rebuild,
2677 &highest_cluster, refcount_table, nb_clusters);
2678 if (rebuild) {
2679 fprintf(stderr, "ERROR rebuilt refcount structure is still "
2680 "broken\n");
2681 }
2682
2683 /* Any leaks accounted for here were introduced by
2684 * rebuild_refcount_structure() because that function has created a
2685 * new refcount structure from scratch */
2686 fresh_leaks = res->leaks;
2687 *res = saved_res;
2688 }
2689
2690 if (res->corruptions < old_res.corruptions) {
2691 res->corruptions_fixed += old_res.corruptions - res->corruptions;
2692 }
2693 if (res->leaks < old_res.leaks) {
2694 res->leaks_fixed += old_res.leaks - res->leaks;
2695 }
2696 res->leaks += fresh_leaks;
c7c0681b
HR
2697 } else if (fix) {
2698 if (rebuild) {
2699 fprintf(stderr, "ERROR need to rebuild refcount structures\n");
2700 res->check_errors++;
2701 ret = -EIO;
2702 goto fail;
2703 }
2704
2705 if (res->leaks || res->corruptions) {
2706 *res = pre_compare_res;
2707 compare_refcounts(bs, res, fix, &rebuild, &highest_cluster,
2708 refcount_table, nb_clusters);
2709 }
f307b255
HR
2710 }
2711
4f6ed88c 2712 /* check OFLAG_COPIED */
e23e400e 2713 ret = check_oflag_copied(bs, res, fix);
4f6ed88c
HR
2714 if (ret < 0) {
2715 goto fail;
2716 }
2717
c6bb9ad1 2718 res->image_end_offset = (highest_cluster + 1) * s->cluster_size;
80fa3341
KW
2719 ret = 0;
2720
2721fail:
7267c094 2722 g_free(refcount_table);
f7d0fe02 2723
80fa3341 2724 return ret;
f7d0fe02
KW
2725}
2726
a40f1c2a
HR
2727#define overlaps_with(ofs, sz) \
2728 ranges_overlap(offset, size, ofs, sz)
2729
2730/*
2731 * Checks if the given offset into the image file is actually free to use by
2732 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
2733 * i.e. a sanity check without relying on the refcount tables.
2734 *
231bb267
HR
2735 * The ign parameter specifies what checks not to perform (being a bitmask of
2736 * QCow2MetadataOverlap values), i.e., what sections to ignore.
a40f1c2a
HR
2737 *
2738 * Returns:
2739 * - 0 if writing to this offset will not affect the mentioned metadata
2740 * - a positive QCow2MetadataOverlap value indicating one overlapping section
2741 * - a negative value (-errno) indicating an error while performing a check,
f4649069 2742 * e.g. when bdrv_pread failed on QCOW2_OL_INACTIVE_L2
a40f1c2a 2743 */
231bb267 2744int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
a40f1c2a
HR
2745 int64_t size)
2746{
ff99129a 2747 BDRVQcow2State *s = bs->opaque;
3e355390 2748 int chk = s->overlap_check & ~ign;
a40f1c2a
HR
2749 int i, j;
2750
2751 if (!size) {
2752 return 0;
2753 }
2754
2755 if (chk & QCOW2_OL_MAIN_HEADER) {
2756 if (offset < s->cluster_size) {
2757 return QCOW2_OL_MAIN_HEADER;
2758 }
2759 }
2760
2761 /* align range to test to cluster boundaries */
9e029689 2762 size = ROUND_UP(offset_into_cluster(s, offset) + size, s->cluster_size);
a40f1c2a
HR
2763 offset = start_of_cluster(s, offset);
2764
2765 if ((chk & QCOW2_OL_ACTIVE_L1) && s->l1_size) {
02b1ecfa 2766 if (overlaps_with(s->l1_table_offset, s->l1_size * L1E_SIZE)) {
a40f1c2a
HR
2767 return QCOW2_OL_ACTIVE_L1;
2768 }
2769 }
2770
2771 if ((chk & QCOW2_OL_REFCOUNT_TABLE) && s->refcount_table_size) {
2772 if (overlaps_with(s->refcount_table_offset,
02b1ecfa 2773 s->refcount_table_size * REFTABLE_ENTRY_SIZE)) {
a40f1c2a
HR
2774 return QCOW2_OL_REFCOUNT_TABLE;
2775 }
2776 }
2777
2778 if ((chk & QCOW2_OL_SNAPSHOT_TABLE) && s->snapshots_size) {
2779 if (overlaps_with(s->snapshots_offset, s->snapshots_size)) {
2780 return QCOW2_OL_SNAPSHOT_TABLE;
2781 }
2782 }
2783
2784 if ((chk & QCOW2_OL_INACTIVE_L1) && s->snapshots) {
2785 for (i = 0; i < s->nb_snapshots; i++) {
2786 if (s->snapshots[i].l1_size &&
2787 overlaps_with(s->snapshots[i].l1_table_offset,
02b1ecfa 2788 s->snapshots[i].l1_size * L1E_SIZE)) {
a40f1c2a
HR
2789 return QCOW2_OL_INACTIVE_L1;
2790 }
2791 }
2792 }
2793
2794 if ((chk & QCOW2_OL_ACTIVE_L2) && s->l1_table) {
2795 for (i = 0; i < s->l1_size; i++) {
2796 if ((s->l1_table[i] & L1E_OFFSET_MASK) &&
2797 overlaps_with(s->l1_table[i] & L1E_OFFSET_MASK,
2798 s->cluster_size)) {
2799 return QCOW2_OL_ACTIVE_L2;
2800 }
2801 }
2802 }
2803
2804 if ((chk & QCOW2_OL_REFCOUNT_BLOCK) && s->refcount_table) {
7061a078
AG
2805 unsigned last_entry = s->max_refcount_table_index;
2806 assert(last_entry < s->refcount_table_size);
2807 assert(last_entry + 1 == s->refcount_table_size ||
2808 (s->refcount_table[last_entry + 1] & REFT_OFFSET_MASK) == 0);
2809 for (i = 0; i <= last_entry; i++) {
a40f1c2a
HR
2810 if ((s->refcount_table[i] & REFT_OFFSET_MASK) &&
2811 overlaps_with(s->refcount_table[i] & REFT_OFFSET_MASK,
2812 s->cluster_size)) {
2813 return QCOW2_OL_REFCOUNT_BLOCK;
2814 }
2815 }
2816 }
2817
2818 if ((chk & QCOW2_OL_INACTIVE_L2) && s->snapshots) {
2819 for (i = 0; i < s->nb_snapshots; i++) {
2820 uint64_t l1_ofs = s->snapshots[i].l1_table_offset;
2821 uint32_t l1_sz = s->snapshots[i].l1_size;
02b1ecfa 2822 uint64_t l1_sz2 = l1_sz * L1E_SIZE;
c7a9d81d 2823 uint64_t *l1;
a40f1c2a
HR
2824 int ret;
2825
02b1ecfa 2826 ret = qcow2_validate_table(bs, l1_ofs, l1_sz, L1E_SIZE,
c7a9d81d
AG
2827 QCOW_MAX_L1_SIZE, "", NULL);
2828 if (ret < 0) {
2829 return ret;
2830 }
2831
2832 l1 = g_try_malloc(l1_sz2);
2833
de82815d
KW
2834 if (l1_sz2 && l1 == NULL) {
2835 return -ENOMEM;
2836 }
2837
cf2ab8fc 2838 ret = bdrv_pread(bs->file, l1_ofs, l1, l1_sz2);
a40f1c2a
HR
2839 if (ret < 0) {
2840 g_free(l1);
2841 return ret;
2842 }
2843
2844 for (j = 0; j < l1_sz; j++) {
1e242b55
HR
2845 uint64_t l2_ofs = be64_to_cpu(l1[j]) & L1E_OFFSET_MASK;
2846 if (l2_ofs && overlaps_with(l2_ofs, s->cluster_size)) {
a40f1c2a
HR
2847 g_free(l1);
2848 return QCOW2_OL_INACTIVE_L2;
2849 }
2850 }
2851
2852 g_free(l1);
2853 }
2854 }
2855
0e4e4318
VSO
2856 if ((chk & QCOW2_OL_BITMAP_DIRECTORY) &&
2857 (s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS))
2858 {
2859 if (overlaps_with(s->bitmap_directory_offset,
2860 s->bitmap_directory_size))
2861 {
2862 return QCOW2_OL_BITMAP_DIRECTORY;
2863 }
2864 }
2865
a40f1c2a
HR
2866 return 0;
2867}
2868
2869static const char *metadata_ol_names[] = {
7cb6d3c9
LM
2870 [QCOW2_OL_MAIN_HEADER_BITNR] = "qcow2_header",
2871 [QCOW2_OL_ACTIVE_L1_BITNR] = "active L1 table",
2872 [QCOW2_OL_ACTIVE_L2_BITNR] = "active L2 table",
2873 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = "refcount table",
2874 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = "refcount block",
2875 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = "snapshot table",
2876 [QCOW2_OL_INACTIVE_L1_BITNR] = "inactive L1 table",
2877 [QCOW2_OL_INACTIVE_L2_BITNR] = "inactive L2 table",
2878 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = "bitmap directory",
a40f1c2a 2879};
7cb6d3c9 2880QEMU_BUILD_BUG_ON(QCOW2_OL_MAX_BITNR != ARRAY_SIZE(metadata_ol_names));
a40f1c2a
HR
2881
2882/*
2883 * First performs a check for metadata overlaps (through
2884 * qcow2_check_metadata_overlap); if that fails with a negative value (error
2885 * while performing a check), that value is returned. If an impending overlap
2886 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
2887 * and -EIO returned.
2888 *
2889 * Returns 0 if there were neither overlaps nor errors while checking for
2890 * overlaps; or a negative value (-errno) on error.
2891 */
231bb267 2892int qcow2_pre_write_overlap_check(BlockDriverState *bs, int ign, int64_t offset,
966b000f 2893 int64_t size, bool data_file)
a40f1c2a 2894{
966b000f
KW
2895 int ret;
2896
2897 if (data_file && has_data_file(bs)) {
2898 return 0;
2899 }
a40f1c2a 2900
966b000f 2901 ret = qcow2_check_metadata_overlap(bs, ign, offset, size);
a40f1c2a
HR
2902 if (ret < 0) {
2903 return ret;
2904 } else if (ret > 0) {
786a4ea8 2905 int metadata_ol_bitnr = ctz32(ret);
a40f1c2a
HR
2906 assert(metadata_ol_bitnr < QCOW2_OL_MAX_BITNR);
2907
adb43552
HR
2908 qcow2_signal_corruption(bs, true, offset, size, "Preventing invalid "
2909 "write on metadata (overlaps with %s)",
2910 metadata_ol_names[metadata_ol_bitnr]);
a40f1c2a
HR
2911 return -EIO;
2912 }
2913
2914 return 0;
2915}
791c9a00
HR
2916
2917/* A pointer to a function of this type is given to walk_over_reftable(). That
2918 * function will create refblocks and pass them to a RefblockFinishOp once they
2919 * are completed (@refblock). @refblock_empty is set if the refblock is
2920 * completely empty.
2921 *
2922 * Along with the refblock, a corresponding reftable entry is passed, in the
2923 * reftable @reftable (which may be reallocated) at @reftable_index.
2924 *
2925 * @allocated should be set to true if a new cluster has been allocated.
2926 */
2927typedef int (RefblockFinishOp)(BlockDriverState *bs, uint64_t **reftable,
2928 uint64_t reftable_index, uint64_t *reftable_size,
2929 void *refblock, bool refblock_empty,
2930 bool *allocated, Error **errp);
2931
2932/**
2933 * This "operation" for walk_over_reftable() allocates the refblock on disk (if
2934 * it is not empty) and inserts its offset into the new reftable. The size of
2935 * this new reftable is increased as required.
2936 */
2937static int alloc_refblock(BlockDriverState *bs, uint64_t **reftable,
2938 uint64_t reftable_index, uint64_t *reftable_size,
2939 void *refblock, bool refblock_empty, bool *allocated,
2940 Error **errp)
2941{
2942 BDRVQcow2State *s = bs->opaque;
2943 int64_t offset;
2944
2945 if (!refblock_empty && reftable_index >= *reftable_size) {
2946 uint64_t *new_reftable;
2947 uint64_t new_reftable_size;
2948
2949 new_reftable_size = ROUND_UP(reftable_index + 1,
02b1ecfa
AG
2950 s->cluster_size / REFTABLE_ENTRY_SIZE);
2951 if (new_reftable_size > QCOW_MAX_REFTABLE_SIZE / REFTABLE_ENTRY_SIZE) {
791c9a00
HR
2952 error_setg(errp,
2953 "This operation would make the refcount table grow "
2954 "beyond the maximum size supported by QEMU, aborting");
2955 return -ENOTSUP;
2956 }
2957
2958 new_reftable = g_try_realloc(*reftable, new_reftable_size *
02b1ecfa 2959 REFTABLE_ENTRY_SIZE);
791c9a00
HR
2960 if (!new_reftable) {
2961 error_setg(errp, "Failed to increase reftable buffer size");
2962 return -ENOMEM;
2963 }
2964
2965 memset(new_reftable + *reftable_size, 0,
02b1ecfa 2966 (new_reftable_size - *reftable_size) * REFTABLE_ENTRY_SIZE);
791c9a00
HR
2967
2968 *reftable = new_reftable;
2969 *reftable_size = new_reftable_size;
2970 }
2971
2972 if (!refblock_empty && !(*reftable)[reftable_index]) {
2973 offset = qcow2_alloc_clusters(bs, s->cluster_size);
2974 if (offset < 0) {
2975 error_setg_errno(errp, -offset, "Failed to allocate refblock");
2976 return offset;
2977 }
2978 (*reftable)[reftable_index] = offset;
2979 *allocated = true;
2980 }
2981
2982 return 0;
2983}
2984
2985/**
2986 * This "operation" for walk_over_reftable() writes the refblock to disk at the
2987 * offset specified by the new reftable's entry. It does not modify the new
2988 * reftable or change any refcounts.
2989 */
2990static int flush_refblock(BlockDriverState *bs, uint64_t **reftable,
2991 uint64_t reftable_index, uint64_t *reftable_size,
2992 void *refblock, bool refblock_empty, bool *allocated,
2993 Error **errp)
2994{
2995 BDRVQcow2State *s = bs->opaque;
2996 int64_t offset;
2997 int ret;
2998
2999 if (reftable_index < *reftable_size && (*reftable)[reftable_index]) {
3000 offset = (*reftable)[reftable_index];
3001
966b000f
KW
3002 ret = qcow2_pre_write_overlap_check(bs, 0, offset, s->cluster_size,
3003 false);
791c9a00
HR
3004 if (ret < 0) {
3005 error_setg_errno(errp, -ret, "Overlap check failed");
3006 return ret;
3007 }
3008
d9ca2ea2 3009 ret = bdrv_pwrite(bs->file, offset, refblock, s->cluster_size);
791c9a00
HR
3010 if (ret < 0) {
3011 error_setg_errno(errp, -ret, "Failed to write refblock");
3012 return ret;
3013 }
3014 } else {
3015 assert(refblock_empty);
3016 }
3017
3018 return 0;
3019}
3020
3021/**
3022 * This function walks over the existing reftable and every referenced refblock;
3023 * if @new_set_refcount is non-NULL, it is called for every refcount entry to
3024 * create an equal new entry in the passed @new_refblock. Once that
3025 * @new_refblock is completely filled, @operation will be called.
3026 *
3027 * @status_cb and @cb_opaque are used for the amend operation's status callback.
3028 * @index is the index of the walk_over_reftable() calls and @total is the total
3029 * number of walk_over_reftable() calls per amend operation. Both are used for
3030 * calculating the parameters for the status callback.
3031 *
3032 * @allocated is set to true if a new cluster has been allocated.
3033 */
3034static int walk_over_reftable(BlockDriverState *bs, uint64_t **new_reftable,
3035 uint64_t *new_reftable_index,
3036 uint64_t *new_reftable_size,
3037 void *new_refblock, int new_refblock_size,
3038 int new_refcount_bits,
3039 RefblockFinishOp *operation, bool *allocated,
3040 Qcow2SetRefcountFunc *new_set_refcount,
3041 BlockDriverAmendStatusCB *status_cb,
3042 void *cb_opaque, int index, int total,
3043 Error **errp)
3044{
3045 BDRVQcow2State *s = bs->opaque;
3046 uint64_t reftable_index;
3047 bool new_refblock_empty = true;
3048 int refblock_index;
3049 int new_refblock_index = 0;
3050 int ret;
3051
3052 for (reftable_index = 0; reftable_index < s->refcount_table_size;
3053 reftable_index++)
3054 {
3055 uint64_t refblock_offset = s->refcount_table[reftable_index]
3056 & REFT_OFFSET_MASK;
3057
3058 status_cb(bs, (uint64_t)index * s->refcount_table_size + reftable_index,
3059 (uint64_t)total * s->refcount_table_size, cb_opaque);
3060
3061 if (refblock_offset) {
3062 void *refblock;
3063
3064 if (offset_into_cluster(s, refblock_offset)) {
3065 qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#"
3066 PRIx64 " unaligned (reftable index: %#"
3067 PRIx64 ")", refblock_offset,
3068 reftable_index);
3069 error_setg(errp,
3070 "Image is corrupt (unaligned refblock offset)");
3071 return -EIO;
3072 }
3073
3074 ret = qcow2_cache_get(bs, s->refcount_block_cache, refblock_offset,
3075 &refblock);
3076 if (ret < 0) {
3077 error_setg_errno(errp, -ret, "Failed to retrieve refblock");
3078 return ret;
3079 }
3080
3081 for (refblock_index = 0; refblock_index < s->refcount_block_size;
3082 refblock_index++)
3083 {
3084 uint64_t refcount;
3085
3086 if (new_refblock_index >= new_refblock_size) {
3087 /* new_refblock is now complete */
3088 ret = operation(bs, new_reftable, *new_reftable_index,
3089 new_reftable_size, new_refblock,
3090 new_refblock_empty, allocated, errp);
3091 if (ret < 0) {
2013c3d4 3092 qcow2_cache_put(s->refcount_block_cache, &refblock);
791c9a00
HR
3093 return ret;
3094 }
3095
3096 (*new_reftable_index)++;
3097 new_refblock_index = 0;
3098 new_refblock_empty = true;
3099 }
3100
3101 refcount = s->get_refcount(refblock, refblock_index);
3102 if (new_refcount_bits < 64 && refcount >> new_refcount_bits) {
3103 uint64_t offset;
3104
2013c3d4 3105 qcow2_cache_put(s->refcount_block_cache, &refblock);
791c9a00
HR
3106
3107 offset = ((reftable_index << s->refcount_block_bits)
3108 + refblock_index) << s->cluster_bits;
3109
3110 error_setg(errp, "Cannot decrease refcount entry width to "
3111 "%i bits: Cluster at offset %#" PRIx64 " has a "
3112 "refcount of %" PRIu64, new_refcount_bits,
3113 offset, refcount);
3114 return -EINVAL;
3115 }
3116
3117 if (new_set_refcount) {
3118 new_set_refcount(new_refblock, new_refblock_index++,
3119 refcount);
3120 } else {
3121 new_refblock_index++;
3122 }
3123 new_refblock_empty = new_refblock_empty && refcount == 0;
3124 }
3125
2013c3d4 3126 qcow2_cache_put(s->refcount_block_cache, &refblock);
791c9a00
HR
3127 } else {
3128 /* No refblock means every refcount is 0 */
3129 for (refblock_index = 0; refblock_index < s->refcount_block_size;
3130 refblock_index++)
3131 {
3132 if (new_refblock_index >= new_refblock_size) {
3133 /* new_refblock is now complete */
3134 ret = operation(bs, new_reftable, *new_reftable_index,
3135 new_reftable_size, new_refblock,
3136 new_refblock_empty, allocated, errp);
3137 if (ret < 0) {
3138 return ret;
3139 }
3140
3141 (*new_reftable_index)++;
3142 new_refblock_index = 0;
3143 new_refblock_empty = true;
3144 }
3145
3146 if (new_set_refcount) {
3147 new_set_refcount(new_refblock, new_refblock_index++, 0);
3148 } else {
3149 new_refblock_index++;
3150 }
3151 }
3152 }
3153 }
3154
3155 if (new_refblock_index > 0) {
3156 /* Complete the potentially existing partially filled final refblock */
3157 if (new_set_refcount) {
3158 for (; new_refblock_index < new_refblock_size;
3159 new_refblock_index++)
3160 {
3161 new_set_refcount(new_refblock, new_refblock_index, 0);
3162 }
3163 }
3164
3165 ret = operation(bs, new_reftable, *new_reftable_index,
3166 new_reftable_size, new_refblock, new_refblock_empty,
3167 allocated, errp);
3168 if (ret < 0) {
3169 return ret;
3170 }
3171
3172 (*new_reftable_index)++;
3173 }
3174
3175 status_cb(bs, (uint64_t)(index + 1) * s->refcount_table_size,
3176 (uint64_t)total * s->refcount_table_size, cb_opaque);
3177
3178 return 0;
3179}
3180
3181int qcow2_change_refcount_order(BlockDriverState *bs, int refcount_order,
3182 BlockDriverAmendStatusCB *status_cb,
3183 void *cb_opaque, Error **errp)
3184{
3185 BDRVQcow2State *s = bs->opaque;
3186 Qcow2GetRefcountFunc *new_get_refcount;
3187 Qcow2SetRefcountFunc *new_set_refcount;
3188 void *new_refblock = qemu_blockalign(bs->file->bs, s->cluster_size);
3189 uint64_t *new_reftable = NULL, new_reftable_size = 0;
3190 uint64_t *old_reftable, old_reftable_size, old_reftable_offset;
3191 uint64_t new_reftable_index = 0;
3192 uint64_t i;
3193 int64_t new_reftable_offset = 0, allocated_reftable_size = 0;
3194 int new_refblock_size, new_refcount_bits = 1 << refcount_order;
3195 int old_refcount_order;
3196 int walk_index = 0;
3197 int ret;
3198 bool new_allocation;
3199
3200 assert(s->qcow_version >= 3);
3201 assert(refcount_order >= 0 && refcount_order <= 6);
3202
3203 /* see qcow2_open() */
3204 new_refblock_size = 1 << (s->cluster_bits - (refcount_order - 3));
3205
3206 new_get_refcount = get_refcount_funcs[refcount_order];
3207 new_set_refcount = set_refcount_funcs[refcount_order];
3208
3209
3210 do {
3211 int total_walks;
3212
3213 new_allocation = false;
3214
3215 /* At least we have to do this walk and the one which writes the
3216 * refblocks; also, at least we have to do this loop here at least
3217 * twice (normally), first to do the allocations, and second to
3218 * determine that everything is correctly allocated, this then makes
3219 * three walks in total */
3220 total_walks = MAX(walk_index + 2, 3);
3221
3222 /* First, allocate the structures so they are present in the refcount
3223 * structures */
3224 ret = walk_over_reftable(bs, &new_reftable, &new_reftable_index,
3225 &new_reftable_size, NULL, new_refblock_size,
3226 new_refcount_bits, &alloc_refblock,
3227 &new_allocation, NULL, status_cb, cb_opaque,
3228 walk_index++, total_walks, errp);
3229 if (ret < 0) {
3230 goto done;
3231 }
3232
3233 new_reftable_index = 0;
3234
3235 if (new_allocation) {
3236 if (new_reftable_offset) {
02b1ecfa
AG
3237 qcow2_free_clusters(
3238 bs, new_reftable_offset,
3239 allocated_reftable_size * REFTABLE_ENTRY_SIZE,
3240 QCOW2_DISCARD_NEVER);
791c9a00
HR
3241 }
3242
3243 new_reftable_offset = qcow2_alloc_clusters(bs, new_reftable_size *
02b1ecfa 3244 REFTABLE_ENTRY_SIZE);
791c9a00
HR
3245 if (new_reftable_offset < 0) {
3246 error_setg_errno(errp, -new_reftable_offset,
3247 "Failed to allocate the new reftable");
3248 ret = new_reftable_offset;
3249 goto done;
3250 }
3251 allocated_reftable_size = new_reftable_size;
3252 }
3253 } while (new_allocation);
3254
3255 /* Second, write the new refblocks */
3256 ret = walk_over_reftable(bs, &new_reftable, &new_reftable_index,
3257 &new_reftable_size, new_refblock,
3258 new_refblock_size, new_refcount_bits,
3259 &flush_refblock, &new_allocation, new_set_refcount,
3260 status_cb, cb_opaque, walk_index, walk_index + 1,
3261 errp);
3262 if (ret < 0) {
3263 goto done;
3264 }
3265 assert(!new_allocation);
3266
3267
3268 /* Write the new reftable */
3269 ret = qcow2_pre_write_overlap_check(bs, 0, new_reftable_offset,
02b1ecfa 3270 new_reftable_size * REFTABLE_ENTRY_SIZE,
966b000f 3271 false);
791c9a00
HR
3272 if (ret < 0) {
3273 error_setg_errno(errp, -ret, "Overlap check failed");
3274 goto done;
3275 }
3276
3277 for (i = 0; i < new_reftable_size; i++) {
3278 cpu_to_be64s(&new_reftable[i]);
3279 }
3280
d9ca2ea2 3281 ret = bdrv_pwrite(bs->file, new_reftable_offset, new_reftable,
02b1ecfa 3282 new_reftable_size * REFTABLE_ENTRY_SIZE);
791c9a00
HR
3283
3284 for (i = 0; i < new_reftable_size; i++) {
3285 be64_to_cpus(&new_reftable[i]);
3286 }
3287
3288 if (ret < 0) {
3289 error_setg_errno(errp, -ret, "Failed to write the new reftable");
3290 goto done;
3291 }
3292
3293
3294 /* Empty the refcount cache */
3295 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
3296 if (ret < 0) {
3297 error_setg_errno(errp, -ret, "Failed to flush the refblock cache");
3298 goto done;
3299 }
3300
3301 /* Update the image header to point to the new reftable; this only updates
3302 * the fields which are relevant to qcow2_update_header(); other fields
3303 * such as s->refcount_table or s->refcount_bits stay stale for now
3304 * (because we have to restore everything if qcow2_update_header() fails) */
3305 old_refcount_order = s->refcount_order;
3306 old_reftable_size = s->refcount_table_size;
3307 old_reftable_offset = s->refcount_table_offset;
3308
3309 s->refcount_order = refcount_order;
3310 s->refcount_table_size = new_reftable_size;
3311 s->refcount_table_offset = new_reftable_offset;
3312
3313 ret = qcow2_update_header(bs);
3314 if (ret < 0) {
3315 s->refcount_order = old_refcount_order;
3316 s->refcount_table_size = old_reftable_size;
3317 s->refcount_table_offset = old_reftable_offset;
3318 error_setg_errno(errp, -ret, "Failed to update the qcow2 header");
3319 goto done;
3320 }
3321
3322 /* Now update the rest of the in-memory information */
3323 old_reftable = s->refcount_table;
3324 s->refcount_table = new_reftable;
7061a078 3325 update_max_refcount_table_index(s);
791c9a00
HR
3326
3327 s->refcount_bits = 1 << refcount_order;
3328 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
3329 s->refcount_max += s->refcount_max - 1;
3330
3331 s->refcount_block_bits = s->cluster_bits - (refcount_order - 3);
3332 s->refcount_block_size = 1 << s->refcount_block_bits;
3333
3334 s->get_refcount = new_get_refcount;
3335 s->set_refcount = new_set_refcount;
3336
3337 /* For cleaning up all old refblocks and the old reftable below the "done"
3338 * label */
3339 new_reftable = old_reftable;
3340 new_reftable_size = old_reftable_size;
3341 new_reftable_offset = old_reftable_offset;
3342
3343done:
3344 if (new_reftable) {
3345 /* On success, new_reftable actually points to the old reftable (and
3346 * new_reftable_size is the old reftable's size); but that is just
3347 * fine */
3348 for (i = 0; i < new_reftable_size; i++) {
3349 uint64_t offset = new_reftable[i] & REFT_OFFSET_MASK;
3350 if (offset) {
3351 qcow2_free_clusters(bs, offset, s->cluster_size,
3352 QCOW2_DISCARD_OTHER);
3353 }
3354 }
3355 g_free(new_reftable);
3356
3357 if (new_reftable_offset > 0) {
3358 qcow2_free_clusters(bs, new_reftable_offset,
02b1ecfa 3359 new_reftable_size * REFTABLE_ENTRY_SIZE,
791c9a00
HR
3360 QCOW2_DISCARD_OTHER);
3361 }
3362 }
3363
3364 qemu_vfree(new_refblock);
3365 return ret;
3366}
46b732cd 3367
23482f8a
HR
3368static int64_t get_refblock_offset(BlockDriverState *bs, uint64_t offset)
3369{
3370 BDRVQcow2State *s = bs->opaque;
3371 uint32_t index = offset_to_reftable_index(s, offset);
3372 int64_t covering_refblock_offset = 0;
3373
3374 if (index < s->refcount_table_size) {
3375 covering_refblock_offset = s->refcount_table[index] & REFT_OFFSET_MASK;
3376 }
3377 if (!covering_refblock_offset) {
3378 qcow2_signal_corruption(bs, true, -1, -1, "Refblock at %#" PRIx64 " is "
3379 "not covered by the refcount structures",
3380 offset);
3381 return -EIO;
3382 }
3383
3384 return covering_refblock_offset;
3385}
3386
46b732cd
PB
3387static int qcow2_discard_refcount_block(BlockDriverState *bs,
3388 uint64_t discard_block_offs)
3389{
3390 BDRVQcow2State *s = bs->opaque;
23482f8a 3391 int64_t refblock_offs;
46b732cd
PB
3392 uint64_t cluster_index = discard_block_offs >> s->cluster_bits;
3393 uint32_t block_index = cluster_index & (s->refcount_block_size - 1);
3394 void *refblock;
3395 int ret;
3396
23482f8a
HR
3397 refblock_offs = get_refblock_offset(bs, discard_block_offs);
3398 if (refblock_offs < 0) {
3399 return refblock_offs;
3400 }
3401
46b732cd
PB
3402 assert(discard_block_offs != 0);
3403
3404 ret = qcow2_cache_get(bs, s->refcount_block_cache, refblock_offs,
3405 &refblock);
3406 if (ret < 0) {
3407 return ret;
3408 }
3409
3410 if (s->get_refcount(refblock, block_index) != 1) {
3411 qcow2_signal_corruption(bs, true, -1, -1, "Invalid refcount:"
3412 " refblock offset %#" PRIx64
3413 ", reftable index %u"
3414 ", block offset %#" PRIx64
3415 ", refcount %#" PRIx64,
3416 refblock_offs,
3417 offset_to_reftable_index(s, discard_block_offs),
3418 discard_block_offs,
3419 s->get_refcount(refblock, block_index));
2013c3d4 3420 qcow2_cache_put(s->refcount_block_cache, &refblock);
46b732cd
PB
3421 return -EINVAL;
3422 }
3423 s->set_refcount(refblock, block_index, 0);
3424
2d135ee9 3425 qcow2_cache_entry_mark_dirty(s->refcount_block_cache, refblock);
46b732cd 3426
2013c3d4 3427 qcow2_cache_put(s->refcount_block_cache, &refblock);
46b732cd
PB
3428
3429 if (cluster_index < s->free_cluster_index) {
3430 s->free_cluster_index = cluster_index;
3431 }
3432
6e6fa760 3433 refblock = qcow2_cache_is_table_offset(s->refcount_block_cache,
46b732cd
PB
3434 discard_block_offs);
3435 if (refblock) {
3436 /* discard refblock from the cache if refblock is cached */
77aadd7b 3437 qcow2_cache_discard(s->refcount_block_cache, refblock);
46b732cd
PB
3438 }
3439 update_refcount_discard(bs, discard_block_offs, s->cluster_size);
3440
3441 return 0;
3442}
3443
3444int qcow2_shrink_reftable(BlockDriverState *bs)
3445{
3446 BDRVQcow2State *s = bs->opaque;
3447 uint64_t *reftable_tmp =
02b1ecfa 3448 g_malloc(s->refcount_table_size * REFTABLE_ENTRY_SIZE);
46b732cd
PB
3449 int i, ret;
3450
3451 for (i = 0; i < s->refcount_table_size; i++) {
3452 int64_t refblock_offs = s->refcount_table[i] & REFT_OFFSET_MASK;
3453 void *refblock;
3454 bool unused_block;
3455
3456 if (refblock_offs == 0) {
3457 reftable_tmp[i] = 0;
3458 continue;
3459 }
3460 ret = qcow2_cache_get(bs, s->refcount_block_cache, refblock_offs,
3461 &refblock);
3462 if (ret < 0) {
3463 goto out;
3464 }
3465
3466 /* the refblock has own reference */
3467 if (i == offset_to_reftable_index(s, refblock_offs)) {
3468 uint64_t block_index = (refblock_offs >> s->cluster_bits) &
3469 (s->refcount_block_size - 1);
3470 uint64_t refcount = s->get_refcount(refblock, block_index);
3471
3472 s->set_refcount(refblock, block_index, 0);
3473
3474 unused_block = buffer_is_zero(refblock, s->cluster_size);
3475
3476 s->set_refcount(refblock, block_index, refcount);
3477 } else {
3478 unused_block = buffer_is_zero(refblock, s->cluster_size);
3479 }
2013c3d4 3480 qcow2_cache_put(s->refcount_block_cache, &refblock);
46b732cd
PB
3481
3482 reftable_tmp[i] = unused_block ? 0 : cpu_to_be64(s->refcount_table[i]);
3483 }
3484
3485 ret = bdrv_pwrite_sync(bs->file, s->refcount_table_offset, reftable_tmp,
02b1ecfa 3486 s->refcount_table_size * REFTABLE_ENTRY_SIZE);
46b732cd
PB
3487 /*
3488 * If the write in the reftable failed the image may contain a partially
3489 * overwritten reftable. In this case it would be better to clear the
3490 * reftable in memory to avoid possible image corruption.
3491 */
3492 for (i = 0; i < s->refcount_table_size; i++) {
3493 if (s->refcount_table[i] && !reftable_tmp[i]) {
3494 if (ret == 0) {
3495 ret = qcow2_discard_refcount_block(bs, s->refcount_table[i] &
3496 REFT_OFFSET_MASK);
3497 }
3498 s->refcount_table[i] = 0;
3499 }
3500 }
3501
3502 if (!s->cache_discards) {
3503 qcow2_process_discards(bs, ret);
3504 }
3505
3506out:
3507 g_free(reftable_tmp);
3508 return ret;
3509}
163bc39d
PB
3510
3511int64_t qcow2_get_last_cluster(BlockDriverState *bs, int64_t size)
3512{
3513 BDRVQcow2State *s = bs->opaque;
3514 int64_t i;
3515
3516 for (i = size_to_clusters(s, size) - 1; i >= 0; i--) {
3517 uint64_t refcount;
3518 int ret = qcow2_get_refcount(bs, i, &refcount);
3519 if (ret < 0) {
3520 fprintf(stderr, "Can't get refcount for cluster %" PRId64 ": %s\n",
3521 i, strerror(-ret));
3522 return ret;
3523 }
3524 if (refcount > 0) {
3525 return i;
3526 }
3527 }
3528 qcow2_signal_corruption(bs, true, -1, -1,
3529 "There are no references in the refcount table.");
3530 return -EIO;
3531}
69f47505
VSO
3532
3533int qcow2_detect_metadata_preallocation(BlockDriverState *bs)
3534{
3535 BDRVQcow2State *s = bs->opaque;
3536 int64_t i, end_cluster, cluster_count = 0, threshold;
3537 int64_t file_length, real_allocation, real_clusters;
3538
5e978550
KW
3539 qemu_co_mutex_assert_locked(&s->lock);
3540
69f47505
VSO
3541 file_length = bdrv_getlength(bs->file->bs);
3542 if (file_length < 0) {
3543 return file_length;
3544 }
3545
3546 real_allocation = bdrv_get_allocated_file_size(bs->file->bs);
3547 if (real_allocation < 0) {
3548 return real_allocation;
3549 }
3550
3551 real_clusters = real_allocation / s->cluster_size;
3552 threshold = MAX(real_clusters * 10 / 9, real_clusters + 2);
3553
3554 end_cluster = size_to_clusters(s, file_length);
3555 for (i = 0; i < end_cluster && cluster_count < threshold; i++) {
3556 uint64_t refcount;
3557 int ret = qcow2_get_refcount(bs, i, &refcount);
3558 if (ret < 0) {
3559 return ret;
3560 }
3561 cluster_count += !!refcount;
3562 }
3563
3564 return cluster_count >= threshold;
3565}