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