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