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