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