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