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