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