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