xref: /openbmc/qemu/block/qcow2-refcount.c (revision b8bcf811)
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-common.h"
26 #include "block/block_int.h"
27 #include "block/qcow2.h"
28 #include "qemu/range.h"
29 #include "qapi/qmp/types.h"
30 
31 static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size);
32 static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
33                             int64_t offset, int64_t length,
34                             int addend, enum qcow2_discard_type type);
35 
36 
37 /*********************************************************/
38 /* refcount handling */
39 
40 int qcow2_refcount_init(BlockDriverState *bs)
41 {
42     BDRVQcowState *s = bs->opaque;
43     int ret, refcount_table_size2, i;
44 
45     refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
46     s->refcount_table = g_malloc(refcount_table_size2);
47     if (s->refcount_table_size > 0) {
48         BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_LOAD);
49         ret = bdrv_pread(bs->file, s->refcount_table_offset,
50                          s->refcount_table, refcount_table_size2);
51         if (ret != refcount_table_size2)
52             goto fail;
53         for(i = 0; i < s->refcount_table_size; i++)
54             be64_to_cpus(&s->refcount_table[i]);
55     }
56     return 0;
57  fail:
58     return -ENOMEM;
59 }
60 
61 void qcow2_refcount_close(BlockDriverState *bs)
62 {
63     BDRVQcowState *s = bs->opaque;
64     g_free(s->refcount_table);
65 }
66 
67 
68 static int load_refcount_block(BlockDriverState *bs,
69                                int64_t refcount_block_offset,
70                                void **refcount_block)
71 {
72     BDRVQcowState *s = bs->opaque;
73     int ret;
74 
75     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_LOAD);
76     ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
77         refcount_block);
78 
79     return ret;
80 }
81 
82 /*
83  * Returns the refcount of the cluster given by its index. Any non-negative
84  * return value is the refcount of the cluster, negative values are -errno
85  * and indicate an error.
86  */
87 static int get_refcount(BlockDriverState *bs, int64_t cluster_index)
88 {
89     BDRVQcowState *s = bs->opaque;
90     int refcount_table_index, block_index;
91     int64_t refcount_block_offset;
92     int ret;
93     uint16_t *refcount_block;
94     uint16_t refcount;
95 
96     refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
97     if (refcount_table_index >= s->refcount_table_size)
98         return 0;
99     refcount_block_offset = s->refcount_table[refcount_table_index];
100     if (!refcount_block_offset)
101         return 0;
102 
103     ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
104         (void**) &refcount_block);
105     if (ret < 0) {
106         return ret;
107     }
108 
109     block_index = cluster_index &
110         ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
111     refcount = be16_to_cpu(refcount_block[block_index]);
112 
113     ret = qcow2_cache_put(bs, s->refcount_block_cache,
114         (void**) &refcount_block);
115     if (ret < 0) {
116         return ret;
117     }
118 
119     return refcount;
120 }
121 
122 /*
123  * Rounds the refcount table size up to avoid growing the table for each single
124  * refcount block that is allocated.
125  */
126 static unsigned int next_refcount_table_size(BDRVQcowState *s,
127     unsigned int min_size)
128 {
129     unsigned int min_clusters = (min_size >> (s->cluster_bits - 3)) + 1;
130     unsigned int refcount_table_clusters =
131         MAX(1, s->refcount_table_size >> (s->cluster_bits - 3));
132 
133     while (min_clusters > refcount_table_clusters) {
134         refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
135     }
136 
137     return refcount_table_clusters << (s->cluster_bits - 3);
138 }
139 
140 
141 /* Checks if two offsets are described by the same refcount block */
142 static int in_same_refcount_block(BDRVQcowState *s, uint64_t offset_a,
143     uint64_t offset_b)
144 {
145     uint64_t block_a = offset_a >> (2 * s->cluster_bits - REFCOUNT_SHIFT);
146     uint64_t block_b = offset_b >> (2 * s->cluster_bits - REFCOUNT_SHIFT);
147 
148     return (block_a == block_b);
149 }
150 
151 /*
152  * Loads a refcount block. If it doesn't exist yet, it is allocated first
153  * (including growing the refcount table if needed).
154  *
155  * Returns 0 on success or -errno in error case
156  */
157 static int alloc_refcount_block(BlockDriverState *bs,
158     int64_t cluster_index, uint16_t **refcount_block)
159 {
160     BDRVQcowState *s = bs->opaque;
161     unsigned int refcount_table_index;
162     int ret;
163 
164     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
165 
166     /* Find the refcount block for the given cluster */
167     refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
168 
169     if (refcount_table_index < s->refcount_table_size) {
170 
171         uint64_t refcount_block_offset =
172             s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
173 
174         /* If it's already there, we're done */
175         if (refcount_block_offset) {
176              return load_refcount_block(bs, refcount_block_offset,
177                  (void**) refcount_block);
178         }
179     }
180 
181     /*
182      * If we came here, we need to allocate something. Something is at least
183      * a cluster for the new refcount block. It may also include a new refcount
184      * table if the old refcount table is too small.
185      *
186      * Note that allocating clusters here needs some special care:
187      *
188      * - We can't use the normal qcow2_alloc_clusters(), it would try to
189      *   increase the refcount and very likely we would end up with an endless
190      *   recursion. Instead we must place the refcount blocks in a way that
191      *   they can describe them themselves.
192      *
193      * - We need to consider that at this point we are inside update_refcounts
194      *   and doing the initial refcount increase. This means that some clusters
195      *   have already been allocated by the caller, but their refcount isn't
196      *   accurate yet. free_cluster_index tells us where this allocation ends
197      *   as long as we don't overwrite it by freeing clusters.
198      *
199      * - alloc_clusters_noref and qcow2_free_clusters may load a different
200      *   refcount block into the cache
201      */
202 
203     *refcount_block = NULL;
204 
205     /* We write to the refcount table, so we might depend on L2 tables */
206     ret = qcow2_cache_flush(bs, s->l2_table_cache);
207     if (ret < 0) {
208         return ret;
209     }
210 
211     /* Allocate the refcount block itself and mark it as used */
212     int64_t new_block = alloc_clusters_noref(bs, s->cluster_size);
213     if (new_block < 0) {
214         return new_block;
215     }
216 
217 #ifdef DEBUG_ALLOC2
218     fprintf(stderr, "qcow2: Allocate refcount block %d for %" PRIx64
219         " at %" PRIx64 "\n",
220         refcount_table_index, cluster_index << s->cluster_bits, new_block);
221 #endif
222 
223     if (in_same_refcount_block(s, new_block, cluster_index << s->cluster_bits)) {
224         /* Zero the new refcount block before updating it */
225         ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
226             (void**) refcount_block);
227         if (ret < 0) {
228             goto fail_block;
229         }
230 
231         memset(*refcount_block, 0, s->cluster_size);
232 
233         /* The block describes itself, need to update the cache */
234         int block_index = (new_block >> s->cluster_bits) &
235             ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
236         (*refcount_block)[block_index] = cpu_to_be16(1);
237     } else {
238         /* Described somewhere else. This can recurse at most twice before we
239          * arrive at a block that describes itself. */
240         ret = update_refcount(bs, new_block, s->cluster_size, 1,
241                               QCOW2_DISCARD_NEVER);
242         if (ret < 0) {
243             goto fail_block;
244         }
245 
246         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
247         if (ret < 0) {
248             goto fail_block;
249         }
250 
251         /* Initialize the new refcount block only after updating its refcount,
252          * update_refcount uses the refcount cache itself */
253         ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
254             (void**) refcount_block);
255         if (ret < 0) {
256             goto fail_block;
257         }
258 
259         memset(*refcount_block, 0, s->cluster_size);
260     }
261 
262     /* Now the new refcount block needs to be written to disk */
263     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE);
264     qcow2_cache_entry_mark_dirty(s->refcount_block_cache, *refcount_block);
265     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
266     if (ret < 0) {
267         goto fail_block;
268     }
269 
270     /* If the refcount table is big enough, just hook the block up there */
271     if (refcount_table_index < s->refcount_table_size) {
272         uint64_t data64 = cpu_to_be64(new_block);
273         BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_HOOKUP);
274         ret = bdrv_pwrite_sync(bs->file,
275             s->refcount_table_offset + refcount_table_index * sizeof(uint64_t),
276             &data64, sizeof(data64));
277         if (ret < 0) {
278             goto fail_block;
279         }
280 
281         s->refcount_table[refcount_table_index] = new_block;
282         return 0;
283     }
284 
285     ret = qcow2_cache_put(bs, s->refcount_block_cache, (void**) refcount_block);
286     if (ret < 0) {
287         goto fail_block;
288     }
289 
290     /*
291      * If we come here, we need to grow the refcount table. Again, a new
292      * refcount table needs some space and we can't simply allocate to avoid
293      * endless recursion.
294      *
295      * Therefore let's grab new refcount blocks at the end of the image, which
296      * will describe themselves and the new refcount table. This way we can
297      * reference them only in the new table and do the switch to the new
298      * refcount table at once without producing an inconsistent state in
299      * between.
300      */
301     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_GROW);
302 
303     /* Calculate the number of refcount blocks needed so far */
304     uint64_t refcount_block_clusters = 1 << (s->cluster_bits - REFCOUNT_SHIFT);
305     uint64_t blocks_used = (s->free_cluster_index +
306         refcount_block_clusters - 1) / refcount_block_clusters;
307 
308     /* And now we need at least one block more for the new metadata */
309     uint64_t table_size = next_refcount_table_size(s, blocks_used + 1);
310     uint64_t last_table_size;
311     uint64_t blocks_clusters;
312     do {
313         uint64_t table_clusters =
314             size_to_clusters(s, table_size * sizeof(uint64_t));
315         blocks_clusters = 1 +
316             ((table_clusters + refcount_block_clusters - 1)
317             / refcount_block_clusters);
318         uint64_t meta_clusters = table_clusters + blocks_clusters;
319 
320         last_table_size = table_size;
321         table_size = next_refcount_table_size(s, blocks_used +
322             ((meta_clusters + refcount_block_clusters - 1)
323             / refcount_block_clusters));
324 
325     } while (last_table_size != table_size);
326 
327 #ifdef DEBUG_ALLOC2
328     fprintf(stderr, "qcow2: Grow refcount table %" PRId32 " => %" PRId64 "\n",
329         s->refcount_table_size, table_size);
330 #endif
331 
332     /* Create the new refcount table and blocks */
333     uint64_t meta_offset = (blocks_used * refcount_block_clusters) *
334         s->cluster_size;
335     uint64_t table_offset = meta_offset + blocks_clusters * s->cluster_size;
336     uint16_t *new_blocks = g_malloc0(blocks_clusters * s->cluster_size);
337     uint64_t *new_table = g_malloc0(table_size * sizeof(uint64_t));
338 
339     assert(meta_offset >= (s->free_cluster_index * s->cluster_size));
340 
341     /* Fill the new refcount table */
342     memcpy(new_table, s->refcount_table,
343         s->refcount_table_size * sizeof(uint64_t));
344     new_table[refcount_table_index] = new_block;
345 
346     int i;
347     for (i = 0; i < blocks_clusters; i++) {
348         new_table[blocks_used + i] = meta_offset + (i * s->cluster_size);
349     }
350 
351     /* Fill the refcount blocks */
352     uint64_t table_clusters = size_to_clusters(s, table_size * sizeof(uint64_t));
353     int block = 0;
354     for (i = 0; i < table_clusters + blocks_clusters; i++) {
355         new_blocks[block++] = cpu_to_be16(1);
356     }
357 
358     /* Write refcount blocks to disk */
359     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS);
360     ret = bdrv_pwrite_sync(bs->file, meta_offset, new_blocks,
361         blocks_clusters * s->cluster_size);
362     g_free(new_blocks);
363     if (ret < 0) {
364         goto fail_table;
365     }
366 
367     /* Write refcount table to disk */
368     for(i = 0; i < table_size; i++) {
369         cpu_to_be64s(&new_table[i]);
370     }
371 
372     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE);
373     ret = bdrv_pwrite_sync(bs->file, table_offset, new_table,
374         table_size * sizeof(uint64_t));
375     if (ret < 0) {
376         goto fail_table;
377     }
378 
379     for(i = 0; i < table_size; i++) {
380         be64_to_cpus(&new_table[i]);
381     }
382 
383     /* Hook up the new refcount table in the qcow2 header */
384     uint8_t data[12];
385     cpu_to_be64w((uint64_t*)data, table_offset);
386     cpu_to_be32w((uint32_t*)(data + 8), table_clusters);
387     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE);
388     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, refcount_table_offset),
389         data, sizeof(data));
390     if (ret < 0) {
391         goto fail_table;
392     }
393 
394     /* And switch it in memory */
395     uint64_t old_table_offset = s->refcount_table_offset;
396     uint64_t old_table_size = s->refcount_table_size;
397 
398     g_free(s->refcount_table);
399     s->refcount_table = new_table;
400     s->refcount_table_size = table_size;
401     s->refcount_table_offset = table_offset;
402 
403     /* Free old table. Remember, we must not change free_cluster_index */
404     uint64_t old_free_cluster_index = s->free_cluster_index;
405     qcow2_free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t),
406                         QCOW2_DISCARD_OTHER);
407     s->free_cluster_index = old_free_cluster_index;
408 
409     ret = load_refcount_block(bs, new_block, (void**) refcount_block);
410     if (ret < 0) {
411         return ret;
412     }
413 
414     return 0;
415 
416 fail_table:
417     g_free(new_table);
418 fail_block:
419     if (*refcount_block != NULL) {
420         qcow2_cache_put(bs, s->refcount_block_cache, (void**) refcount_block);
421     }
422     return ret;
423 }
424 
425 void qcow2_process_discards(BlockDriverState *bs, int ret)
426 {
427     BDRVQcowState *s = bs->opaque;
428     Qcow2DiscardRegion *d, *next;
429 
430     QTAILQ_FOREACH_SAFE(d, &s->discards, next, next) {
431         QTAILQ_REMOVE(&s->discards, d, next);
432 
433         /* Discard is optional, ignore the return value */
434         if (ret >= 0) {
435             bdrv_discard(bs->file,
436                          d->offset >> BDRV_SECTOR_BITS,
437                          d->bytes >> BDRV_SECTOR_BITS);
438         }
439 
440         g_free(d);
441     }
442 }
443 
444 static void update_refcount_discard(BlockDriverState *bs,
445                                     uint64_t offset, uint64_t length)
446 {
447     BDRVQcowState *s = bs->opaque;
448     Qcow2DiscardRegion *d, *p, *next;
449 
450     QTAILQ_FOREACH(d, &s->discards, next) {
451         uint64_t new_start = MIN(offset, d->offset);
452         uint64_t new_end = MAX(offset + length, d->offset + d->bytes);
453 
454         if (new_end - new_start <= length + d->bytes) {
455             /* There can't be any overlap, areas ending up here have no
456              * references any more and therefore shouldn't get freed another
457              * time. */
458             assert(d->bytes + length == new_end - new_start);
459             d->offset = new_start;
460             d->bytes = new_end - new_start;
461             goto found;
462         }
463     }
464 
465     d = g_malloc(sizeof(*d));
466     *d = (Qcow2DiscardRegion) {
467         .bs     = bs,
468         .offset = offset,
469         .bytes  = length,
470     };
471     QTAILQ_INSERT_TAIL(&s->discards, d, next);
472 
473 found:
474     /* Merge discard requests if they are adjacent now */
475     QTAILQ_FOREACH_SAFE(p, &s->discards, next, next) {
476         if (p == d
477             || p->offset > d->offset + d->bytes
478             || d->offset > p->offset + p->bytes)
479         {
480             continue;
481         }
482 
483         /* Still no overlap possible */
484         assert(p->offset == d->offset + d->bytes
485             || d->offset == p->offset + p->bytes);
486 
487         QTAILQ_REMOVE(&s->discards, p, next);
488         d->offset = MIN(d->offset, p->offset);
489         d->bytes += p->bytes;
490     }
491 }
492 
493 /* XXX: cache several refcount block clusters ? */
494 static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
495     int64_t offset, int64_t length, int addend, enum qcow2_discard_type type)
496 {
497     BDRVQcowState *s = bs->opaque;
498     int64_t start, last, cluster_offset;
499     uint16_t *refcount_block = NULL;
500     int64_t old_table_index = -1;
501     int ret;
502 
503 #ifdef DEBUG_ALLOC2
504     fprintf(stderr, "update_refcount: offset=%" PRId64 " size=%" PRId64 " addend=%d\n",
505            offset, length, addend);
506 #endif
507     if (length < 0) {
508         return -EINVAL;
509     } else if (length == 0) {
510         return 0;
511     }
512 
513     if (addend < 0) {
514         qcow2_cache_set_dependency(bs, s->refcount_block_cache,
515             s->l2_table_cache);
516     }
517 
518     start = start_of_cluster(s, offset);
519     last = start_of_cluster(s, offset + length - 1);
520     for(cluster_offset = start; cluster_offset <= last;
521         cluster_offset += s->cluster_size)
522     {
523         int block_index, refcount;
524         int64_t cluster_index = cluster_offset >> s->cluster_bits;
525         int64_t table_index =
526             cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);
527 
528         /* Load the refcount block and allocate it if needed */
529         if (table_index != old_table_index) {
530             if (refcount_block) {
531                 ret = qcow2_cache_put(bs, s->refcount_block_cache,
532                     (void**) &refcount_block);
533                 if (ret < 0) {
534                     goto fail;
535                 }
536             }
537 
538             ret = alloc_refcount_block(bs, cluster_index, &refcount_block);
539             if (ret < 0) {
540                 goto fail;
541             }
542         }
543         old_table_index = table_index;
544 
545         qcow2_cache_entry_mark_dirty(s->refcount_block_cache, refcount_block);
546 
547         /* we can update the count and save it */
548         block_index = cluster_index &
549             ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);
550 
551         refcount = be16_to_cpu(refcount_block[block_index]);
552         refcount += addend;
553         if (refcount < 0 || refcount > 0xffff) {
554             ret = -EINVAL;
555             goto fail;
556         }
557         if (refcount == 0 && cluster_index < s->free_cluster_index) {
558             s->free_cluster_index = cluster_index;
559         }
560         refcount_block[block_index] = cpu_to_be16(refcount);
561 
562         if (refcount == 0 && s->discard_passthrough[type]) {
563             update_refcount_discard(bs, cluster_offset, s->cluster_size);
564         }
565     }
566 
567     ret = 0;
568 fail:
569     if (!s->cache_discards) {
570         qcow2_process_discards(bs, ret);
571     }
572 
573     /* Write last changed block to disk */
574     if (refcount_block) {
575         int wret;
576         wret = qcow2_cache_put(bs, s->refcount_block_cache,
577             (void**) &refcount_block);
578         if (wret < 0) {
579             return ret < 0 ? ret : wret;
580         }
581     }
582 
583     /*
584      * Try do undo any updates if an error is returned (This may succeed in
585      * some cases like ENOSPC for allocating a new refcount block)
586      */
587     if (ret < 0) {
588         int dummy;
589         dummy = update_refcount(bs, offset, cluster_offset - offset, -addend,
590                                 QCOW2_DISCARD_NEVER);
591         (void)dummy;
592     }
593 
594     return ret;
595 }
596 
597 /*
598  * Increases or decreases the refcount of a given cluster by one.
599  * addend must be 1 or -1.
600  *
601  * If the return value is non-negative, it is the new refcount of the cluster.
602  * If it is negative, it is -errno and indicates an error.
603  */
604 int qcow2_update_cluster_refcount(BlockDriverState *bs,
605                                   int64_t cluster_index,
606                                   int addend,
607                                   enum qcow2_discard_type type)
608 {
609     BDRVQcowState *s = bs->opaque;
610     int ret;
611 
612     ret = update_refcount(bs, cluster_index << s->cluster_bits, 1, addend,
613                           type);
614     if (ret < 0) {
615         return ret;
616     }
617 
618     return get_refcount(bs, cluster_index);
619 }
620 
621 
622 
623 /*********************************************************/
624 /* cluster allocation functions */
625 
626 
627 
628 /* return < 0 if error */
629 static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)
630 {
631     BDRVQcowState *s = bs->opaque;
632     int i, nb_clusters, refcount;
633 
634     nb_clusters = size_to_clusters(s, size);
635 retry:
636     for(i = 0; i < nb_clusters; i++) {
637         int64_t next_cluster_index = s->free_cluster_index++;
638         refcount = get_refcount(bs, next_cluster_index);
639 
640         if (refcount < 0) {
641             return refcount;
642         } else if (refcount != 0) {
643             goto retry;
644         }
645     }
646 #ifdef DEBUG_ALLOC2
647     fprintf(stderr, "alloc_clusters: size=%" PRId64 " -> %" PRId64 "\n",
648             size,
649             (s->free_cluster_index - nb_clusters) << s->cluster_bits);
650 #endif
651     return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
652 }
653 
654 int64_t qcow2_alloc_clusters(BlockDriverState *bs, int64_t size)
655 {
656     int64_t offset;
657     int ret;
658 
659     BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);
660     offset = alloc_clusters_noref(bs, size);
661     if (offset < 0) {
662         return offset;
663     }
664 
665     ret = update_refcount(bs, offset, size, 1, QCOW2_DISCARD_NEVER);
666     if (ret < 0) {
667         return ret;
668     }
669 
670     return offset;
671 }
672 
673 int qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset,
674     int nb_clusters)
675 {
676     BDRVQcowState *s = bs->opaque;
677     uint64_t cluster_index;
678     uint64_t old_free_cluster_index;
679     uint64_t i;
680     int refcount, ret;
681 
682     assert(nb_clusters >= 0);
683     if (nb_clusters == 0) {
684         return 0;
685     }
686 
687     /* Check how many clusters there are free */
688     cluster_index = offset >> s->cluster_bits;
689     for(i = 0; i < nb_clusters; i++) {
690         refcount = get_refcount(bs, cluster_index++);
691 
692         if (refcount < 0) {
693             return refcount;
694         } else if (refcount != 0) {
695             break;
696         }
697     }
698 
699     /* And then allocate them */
700     old_free_cluster_index = s->free_cluster_index;
701     s->free_cluster_index = cluster_index + i;
702 
703     ret = update_refcount(bs, offset, i << s->cluster_bits, 1,
704                           QCOW2_DISCARD_NEVER);
705     if (ret < 0) {
706         return ret;
707     }
708 
709     s->free_cluster_index = old_free_cluster_index;
710 
711     return i;
712 }
713 
714 /* only used to allocate compressed sectors. We try to allocate
715    contiguous sectors. size must be <= cluster_size */
716 int64_t qcow2_alloc_bytes(BlockDriverState *bs, int size)
717 {
718     BDRVQcowState *s = bs->opaque;
719     int64_t offset, cluster_offset;
720     int free_in_cluster;
721 
722     BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_BYTES);
723     assert(size > 0 && size <= s->cluster_size);
724     if (s->free_byte_offset == 0) {
725         offset = qcow2_alloc_clusters(bs, s->cluster_size);
726         if (offset < 0) {
727             return offset;
728         }
729         s->free_byte_offset = offset;
730     }
731  redo:
732     free_in_cluster = s->cluster_size -
733         offset_into_cluster(s, s->free_byte_offset);
734     if (size <= free_in_cluster) {
735         /* enough space in current cluster */
736         offset = s->free_byte_offset;
737         s->free_byte_offset += size;
738         free_in_cluster -= size;
739         if (free_in_cluster == 0)
740             s->free_byte_offset = 0;
741         if (offset_into_cluster(s, offset) != 0)
742             qcow2_update_cluster_refcount(bs, offset >> s->cluster_bits, 1,
743                                           QCOW2_DISCARD_NEVER);
744     } else {
745         offset = qcow2_alloc_clusters(bs, s->cluster_size);
746         if (offset < 0) {
747             return offset;
748         }
749         cluster_offset = start_of_cluster(s, s->free_byte_offset);
750         if ((cluster_offset + s->cluster_size) == offset) {
751             /* we are lucky: contiguous data */
752             offset = s->free_byte_offset;
753             qcow2_update_cluster_refcount(bs, offset >> s->cluster_bits, 1,
754                                           QCOW2_DISCARD_NEVER);
755             s->free_byte_offset += size;
756         } else {
757             s->free_byte_offset = offset;
758             goto redo;
759         }
760     }
761 
762     /* The cluster refcount was incremented, either by qcow2_alloc_clusters()
763      * or explicitly by qcow2_update_cluster_refcount().  Refcount blocks must
764      * be flushed before the caller's L2 table updates.
765      */
766     qcow2_cache_set_dependency(bs, s->l2_table_cache, s->refcount_block_cache);
767     return offset;
768 }
769 
770 void qcow2_free_clusters(BlockDriverState *bs,
771                           int64_t offset, int64_t size,
772                           enum qcow2_discard_type type)
773 {
774     int ret;
775 
776     BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_FREE);
777     ret = update_refcount(bs, offset, size, -1, type);
778     if (ret < 0) {
779         fprintf(stderr, "qcow2_free_clusters failed: %s\n", strerror(-ret));
780         /* TODO Remember the clusters to free them later and avoid leaking */
781     }
782 }
783 
784 /*
785  * Free a cluster using its L2 entry (handles clusters of all types, e.g.
786  * normal cluster, compressed cluster, etc.)
787  */
788 void qcow2_free_any_clusters(BlockDriverState *bs, uint64_t l2_entry,
789                              int nb_clusters, enum qcow2_discard_type type)
790 {
791     BDRVQcowState *s = bs->opaque;
792 
793     switch (qcow2_get_cluster_type(l2_entry)) {
794     case QCOW2_CLUSTER_COMPRESSED:
795         {
796             int nb_csectors;
797             nb_csectors = ((l2_entry >> s->csize_shift) &
798                            s->csize_mask) + 1;
799             qcow2_free_clusters(bs,
800                 (l2_entry & s->cluster_offset_mask) & ~511,
801                 nb_csectors * 512, type);
802         }
803         break;
804     case QCOW2_CLUSTER_NORMAL:
805     case QCOW2_CLUSTER_ZERO:
806         if (l2_entry & L2E_OFFSET_MASK) {
807             qcow2_free_clusters(bs, l2_entry & L2E_OFFSET_MASK,
808                                 nb_clusters << s->cluster_bits, type);
809         }
810         break;
811     case QCOW2_CLUSTER_UNALLOCATED:
812         break;
813     default:
814         abort();
815     }
816 }
817 
818 
819 
820 /*********************************************************/
821 /* snapshots and image creation */
822 
823 
824 
825 /* update the refcounts of snapshots and the copied flag */
826 int qcow2_update_snapshot_refcount(BlockDriverState *bs,
827     int64_t l1_table_offset, int l1_size, int addend)
828 {
829     BDRVQcowState *s = bs->opaque;
830     uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;
831     int64_t old_offset, old_l2_offset;
832     int i, j, l1_modified = 0, nb_csectors, refcount;
833     int ret;
834 
835     l2_table = NULL;
836     l1_table = NULL;
837     l1_size2 = l1_size * sizeof(uint64_t);
838 
839     s->cache_discards = true;
840 
841     /* WARNING: qcow2_snapshot_goto relies on this function not using the
842      * l1_table_offset when it is the current s->l1_table_offset! Be careful
843      * when changing this! */
844     if (l1_table_offset != s->l1_table_offset) {
845         l1_table = g_malloc0(align_offset(l1_size2, 512));
846         l1_allocated = 1;
847 
848         ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);
849         if (ret < 0) {
850             goto fail;
851         }
852 
853         for(i = 0;i < l1_size; i++)
854             be64_to_cpus(&l1_table[i]);
855     } else {
856         assert(l1_size == s->l1_size);
857         l1_table = s->l1_table;
858         l1_allocated = 0;
859     }
860 
861     for(i = 0; i < l1_size; i++) {
862         l2_offset = l1_table[i];
863         if (l2_offset) {
864             old_l2_offset = l2_offset;
865             l2_offset &= L1E_OFFSET_MASK;
866 
867             ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
868                 (void**) &l2_table);
869             if (ret < 0) {
870                 goto fail;
871             }
872 
873             for(j = 0; j < s->l2_size; j++) {
874                 uint64_t cluster_index;
875 
876                 offset = be64_to_cpu(l2_table[j]);
877                 old_offset = offset;
878                 offset &= ~QCOW_OFLAG_COPIED;
879 
880                 switch (qcow2_get_cluster_type(offset)) {
881                     case QCOW2_CLUSTER_COMPRESSED:
882                         nb_csectors = ((offset >> s->csize_shift) &
883                                        s->csize_mask) + 1;
884                         if (addend != 0) {
885                             ret = update_refcount(bs,
886                                 (offset & s->cluster_offset_mask) & ~511,
887                                 nb_csectors * 512, addend,
888                                 QCOW2_DISCARD_SNAPSHOT);
889                             if (ret < 0) {
890                                 goto fail;
891                             }
892                         }
893                         /* compressed clusters are never modified */
894                         refcount = 2;
895                         break;
896 
897                     case QCOW2_CLUSTER_NORMAL:
898                     case QCOW2_CLUSTER_ZERO:
899                         cluster_index = (offset & L2E_OFFSET_MASK) >> s->cluster_bits;
900                         if (!cluster_index) {
901                             /* unallocated */
902                             refcount = 0;
903                             break;
904                         }
905                         if (addend != 0) {
906                             refcount = qcow2_update_cluster_refcount(bs,
907                                     cluster_index, addend,
908                                     QCOW2_DISCARD_SNAPSHOT);
909                         } else {
910                             refcount = get_refcount(bs, cluster_index);
911                         }
912 
913                         if (refcount < 0) {
914                             ret = refcount;
915                             goto fail;
916                         }
917                         break;
918 
919                     case QCOW2_CLUSTER_UNALLOCATED:
920                         refcount = 0;
921                         break;
922 
923                     default:
924                         abort();
925                 }
926 
927                 if (refcount == 1) {
928                     offset |= QCOW_OFLAG_COPIED;
929                 }
930                 if (offset != old_offset) {
931                     if (addend > 0) {
932                         qcow2_cache_set_dependency(bs, s->l2_table_cache,
933                             s->refcount_block_cache);
934                     }
935                     l2_table[j] = cpu_to_be64(offset);
936                     qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
937                 }
938             }
939 
940             ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
941             if (ret < 0) {
942                 goto fail;
943             }
944 
945 
946             if (addend != 0) {
947                 refcount = qcow2_update_cluster_refcount(bs, l2_offset >>
948                         s->cluster_bits, addend, QCOW2_DISCARD_SNAPSHOT);
949             } else {
950                 refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
951             }
952             if (refcount < 0) {
953                 ret = refcount;
954                 goto fail;
955             } else if (refcount == 1) {
956                 l2_offset |= QCOW_OFLAG_COPIED;
957             }
958             if (l2_offset != old_l2_offset) {
959                 l1_table[i] = l2_offset;
960                 l1_modified = 1;
961             }
962         }
963     }
964 
965     ret = bdrv_flush(bs);
966 fail:
967     if (l2_table) {
968         qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
969     }
970 
971     s->cache_discards = false;
972     qcow2_process_discards(bs, ret);
973 
974     /* Update L1 only if it isn't deleted anyway (addend = -1) */
975     if (ret == 0 && addend >= 0 && l1_modified) {
976         for (i = 0; i < l1_size; i++) {
977             cpu_to_be64s(&l1_table[i]);
978         }
979 
980         ret = bdrv_pwrite_sync(bs->file, l1_table_offset, l1_table, l1_size2);
981 
982         for (i = 0; i < l1_size; i++) {
983             be64_to_cpus(&l1_table[i]);
984         }
985     }
986     if (l1_allocated)
987         g_free(l1_table);
988     return ret;
989 }
990 
991 
992 
993 
994 /*********************************************************/
995 /* refcount checking functions */
996 
997 
998 
999 /*
1000  * Increases the refcount for a range of clusters in a given refcount table.
1001  * This is used to construct a temporary refcount table out of L1 and L2 tables
1002  * which can be compared the the refcount table saved in the image.
1003  *
1004  * Modifies the number of errors in res.
1005  */
1006 static void inc_refcounts(BlockDriverState *bs,
1007                           BdrvCheckResult *res,
1008                           uint16_t *refcount_table,
1009                           int refcount_table_size,
1010                           int64_t offset, int64_t size)
1011 {
1012     BDRVQcowState *s = bs->opaque;
1013     int64_t start, last, cluster_offset;
1014     int k;
1015 
1016     if (size <= 0)
1017         return;
1018 
1019     start = start_of_cluster(s, offset);
1020     last = start_of_cluster(s, offset + size - 1);
1021     for(cluster_offset = start; cluster_offset <= last;
1022         cluster_offset += s->cluster_size) {
1023         k = cluster_offset >> s->cluster_bits;
1024         if (k < 0) {
1025             fprintf(stderr, "ERROR: invalid cluster offset=0x%" PRIx64 "\n",
1026                 cluster_offset);
1027             res->corruptions++;
1028         } else if (k >= refcount_table_size) {
1029             fprintf(stderr, "Warning: cluster offset=0x%" PRIx64 " is after "
1030                 "the end of the image file, can't properly check refcounts.\n",
1031                 cluster_offset);
1032             res->check_errors++;
1033         } else {
1034             if (++refcount_table[k] == 0) {
1035                 fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64
1036                     "\n", cluster_offset);
1037                 res->corruptions++;
1038             }
1039         }
1040     }
1041 }
1042 
1043 /* Flags for check_refcounts_l1() and check_refcounts_l2() */
1044 enum {
1045     CHECK_FRAG_INFO = 0x2,      /* update BlockFragInfo counters */
1046 };
1047 
1048 /*
1049  * Increases the refcount in the given refcount table for the all clusters
1050  * referenced in the L2 table. While doing so, performs some checks on L2
1051  * entries.
1052  *
1053  * Returns the number of errors found by the checks or -errno if an internal
1054  * error occurred.
1055  */
1056 static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res,
1057     uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,
1058     int flags)
1059 {
1060     BDRVQcowState *s = bs->opaque;
1061     uint64_t *l2_table, l2_entry;
1062     uint64_t next_contiguous_offset = 0;
1063     int i, l2_size, nb_csectors;
1064 
1065     /* Read L2 table from disk */
1066     l2_size = s->l2_size * sizeof(uint64_t);
1067     l2_table = g_malloc(l2_size);
1068 
1069     if (bdrv_pread(bs->file, l2_offset, l2_table, l2_size) != l2_size)
1070         goto fail;
1071 
1072     /* Do the actual checks */
1073     for(i = 0; i < s->l2_size; i++) {
1074         l2_entry = be64_to_cpu(l2_table[i]);
1075 
1076         switch (qcow2_get_cluster_type(l2_entry)) {
1077         case QCOW2_CLUSTER_COMPRESSED:
1078             /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1079             if (l2_entry & QCOW_OFLAG_COPIED) {
1080                 fprintf(stderr, "ERROR: cluster %" PRId64 ": "
1081                     "copied flag must never be set for compressed "
1082                     "clusters\n", l2_entry >> s->cluster_bits);
1083                 l2_entry &= ~QCOW_OFLAG_COPIED;
1084                 res->corruptions++;
1085             }
1086 
1087             /* Mark cluster as used */
1088             nb_csectors = ((l2_entry >> s->csize_shift) &
1089                            s->csize_mask) + 1;
1090             l2_entry &= s->cluster_offset_mask;
1091             inc_refcounts(bs, res, refcount_table, refcount_table_size,
1092                 l2_entry & ~511, nb_csectors * 512);
1093 
1094             if (flags & CHECK_FRAG_INFO) {
1095                 res->bfi.allocated_clusters++;
1096                 res->bfi.compressed_clusters++;
1097 
1098                 /* Compressed clusters are fragmented by nature.  Since they
1099                  * take up sub-sector space but we only have sector granularity
1100                  * I/O we need to re-read the same sectors even for adjacent
1101                  * compressed clusters.
1102                  */
1103                 res->bfi.fragmented_clusters++;
1104             }
1105             break;
1106 
1107         case QCOW2_CLUSTER_ZERO:
1108             if ((l2_entry & L2E_OFFSET_MASK) == 0) {
1109                 break;
1110             }
1111             /* fall through */
1112 
1113         case QCOW2_CLUSTER_NORMAL:
1114         {
1115             uint64_t offset = l2_entry & L2E_OFFSET_MASK;
1116 
1117             if (flags & CHECK_FRAG_INFO) {
1118                 res->bfi.allocated_clusters++;
1119                 if (next_contiguous_offset &&
1120                     offset != next_contiguous_offset) {
1121                     res->bfi.fragmented_clusters++;
1122                 }
1123                 next_contiguous_offset = offset + s->cluster_size;
1124             }
1125 
1126             /* Mark cluster as used */
1127             inc_refcounts(bs, res, refcount_table,refcount_table_size,
1128                 offset, s->cluster_size);
1129 
1130             /* Correct offsets are cluster aligned */
1131             if (offset_into_cluster(s, offset)) {
1132                 fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "
1133                     "properly aligned; L2 entry corrupted.\n", offset);
1134                 res->corruptions++;
1135             }
1136             break;
1137         }
1138 
1139         case QCOW2_CLUSTER_UNALLOCATED:
1140             break;
1141 
1142         default:
1143             abort();
1144         }
1145     }
1146 
1147     g_free(l2_table);
1148     return 0;
1149 
1150 fail:
1151     fprintf(stderr, "ERROR: I/O error in check_refcounts_l2\n");
1152     g_free(l2_table);
1153     return -EIO;
1154 }
1155 
1156 /*
1157  * Increases the refcount for the L1 table, its L2 tables and all referenced
1158  * clusters in the given refcount table. While doing so, performs some checks
1159  * on L1 and L2 entries.
1160  *
1161  * Returns the number of errors found by the checks or -errno if an internal
1162  * error occurred.
1163  */
1164 static int check_refcounts_l1(BlockDriverState *bs,
1165                               BdrvCheckResult *res,
1166                               uint16_t *refcount_table,
1167                               int refcount_table_size,
1168                               int64_t l1_table_offset, int l1_size,
1169                               int flags)
1170 {
1171     BDRVQcowState *s = bs->opaque;
1172     uint64_t *l1_table, l2_offset, l1_size2;
1173     int i, ret;
1174 
1175     l1_size2 = l1_size * sizeof(uint64_t);
1176 
1177     /* Mark L1 table as used */
1178     inc_refcounts(bs, res, refcount_table, refcount_table_size,
1179         l1_table_offset, l1_size2);
1180 
1181     /* Read L1 table entries from disk */
1182     if (l1_size2 == 0) {
1183         l1_table = NULL;
1184     } else {
1185         l1_table = g_malloc(l1_size2);
1186         if (bdrv_pread(bs->file, l1_table_offset,
1187                        l1_table, l1_size2) != l1_size2)
1188             goto fail;
1189         for(i = 0;i < l1_size; i++)
1190             be64_to_cpus(&l1_table[i]);
1191     }
1192 
1193     /* Do the actual checks */
1194     for(i = 0; i < l1_size; i++) {
1195         l2_offset = l1_table[i];
1196         if (l2_offset) {
1197             /* Mark L2 table as used */
1198             l2_offset &= L1E_OFFSET_MASK;
1199             inc_refcounts(bs, res, refcount_table, refcount_table_size,
1200                 l2_offset, s->cluster_size);
1201 
1202             /* L2 tables are cluster aligned */
1203             if (offset_into_cluster(s, l2_offset)) {
1204                 fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "
1205                     "cluster aligned; L1 entry corrupted\n", l2_offset);
1206                 res->corruptions++;
1207             }
1208 
1209             /* Process and check L2 entries */
1210             ret = check_refcounts_l2(bs, res, refcount_table,
1211                                      refcount_table_size, l2_offset, flags);
1212             if (ret < 0) {
1213                 goto fail;
1214             }
1215         }
1216     }
1217     g_free(l1_table);
1218     return 0;
1219 
1220 fail:
1221     fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
1222     res->check_errors++;
1223     g_free(l1_table);
1224     return -EIO;
1225 }
1226 
1227 /*
1228  * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1229  *
1230  * This function does not print an error message nor does it increment
1231  * check_errors if get_refcount fails (this is because such an error will have
1232  * been already detected and sufficiently signaled by the calling function
1233  * (qcow2_check_refcounts) by the time this function is called).
1234  */
1235 static int check_oflag_copied(BlockDriverState *bs, BdrvCheckResult *res,
1236                               BdrvCheckMode fix)
1237 {
1238     BDRVQcowState *s = bs->opaque;
1239     uint64_t *l2_table = qemu_blockalign(bs, s->cluster_size);
1240     int ret;
1241     int refcount;
1242     int i, j;
1243 
1244     for (i = 0; i < s->l1_size; i++) {
1245         uint64_t l1_entry = s->l1_table[i];
1246         uint64_t l2_offset = l1_entry & L1E_OFFSET_MASK;
1247         bool l2_dirty = false;
1248 
1249         if (!l2_offset) {
1250             continue;
1251         }
1252 
1253         refcount = get_refcount(bs, l2_offset >> s->cluster_bits);
1254         if (refcount < 0) {
1255             /* don't print message nor increment check_errors */
1256             continue;
1257         }
1258         if ((refcount == 1) != ((l1_entry & QCOW_OFLAG_COPIED) != 0)) {
1259             fprintf(stderr, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
1260                     "l1_entry=%" PRIx64 " refcount=%d\n",
1261                     fix & BDRV_FIX_ERRORS ? "Repairing" :
1262                                             "ERROR",
1263                     i, l1_entry, refcount);
1264             if (fix & BDRV_FIX_ERRORS) {
1265                 s->l1_table[i] = refcount == 1
1266                                ? l1_entry |  QCOW_OFLAG_COPIED
1267                                : l1_entry & ~QCOW_OFLAG_COPIED;
1268                 ret = qcow2_write_l1_entry(bs, i);
1269                 if (ret < 0) {
1270                     res->check_errors++;
1271                     goto fail;
1272                 }
1273                 res->corruptions_fixed++;
1274             } else {
1275                 res->corruptions++;
1276             }
1277         }
1278 
1279         ret = bdrv_pread(bs->file, l2_offset, l2_table,
1280                          s->l2_size * sizeof(uint64_t));
1281         if (ret < 0) {
1282             fprintf(stderr, "ERROR: Could not read L2 table: %s\n",
1283                     strerror(-ret));
1284             res->check_errors++;
1285             goto fail;
1286         }
1287 
1288         for (j = 0; j < s->l2_size; j++) {
1289             uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1290             uint64_t data_offset = l2_entry & L2E_OFFSET_MASK;
1291             int cluster_type = qcow2_get_cluster_type(l2_entry);
1292 
1293             if ((cluster_type == QCOW2_CLUSTER_NORMAL) ||
1294                 ((cluster_type == QCOW2_CLUSTER_ZERO) && (data_offset != 0))) {
1295                 refcount = get_refcount(bs, data_offset >> s->cluster_bits);
1296                 if (refcount < 0) {
1297                     /* don't print message nor increment check_errors */
1298                     continue;
1299                 }
1300                 if ((refcount == 1) != ((l2_entry & QCOW_OFLAG_COPIED) != 0)) {
1301                     fprintf(stderr, "%s OFLAG_COPIED data cluster: "
1302                             "l2_entry=%" PRIx64 " refcount=%d\n",
1303                             fix & BDRV_FIX_ERRORS ? "Repairing" :
1304                                                     "ERROR",
1305                             l2_entry, refcount);
1306                     if (fix & BDRV_FIX_ERRORS) {
1307                         l2_table[j] = cpu_to_be64(refcount == 1
1308                                     ? l2_entry |  QCOW_OFLAG_COPIED
1309                                     : l2_entry & ~QCOW_OFLAG_COPIED);
1310                         l2_dirty = true;
1311                         res->corruptions_fixed++;
1312                     } else {
1313                         res->corruptions++;
1314                     }
1315                 }
1316             }
1317         }
1318 
1319         if (l2_dirty) {
1320             ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L2,
1321                                                 l2_offset, s->cluster_size);
1322             if (ret < 0) {
1323                 fprintf(stderr, "ERROR: Could not write L2 table; metadata "
1324                         "overlap check failed: %s\n", strerror(-ret));
1325                 res->check_errors++;
1326                 goto fail;
1327             }
1328 
1329             ret = bdrv_pwrite(bs->file, l2_offset, l2_table, s->cluster_size);
1330             if (ret < 0) {
1331                 fprintf(stderr, "ERROR: Could not write L2 table: %s\n",
1332                         strerror(-ret));
1333                 res->check_errors++;
1334                 goto fail;
1335             }
1336         }
1337     }
1338 
1339     ret = 0;
1340 
1341 fail:
1342     qemu_vfree(l2_table);
1343     return ret;
1344 }
1345 
1346 /*
1347  * Writes one sector of the refcount table to the disk
1348  */
1349 #define RT_ENTRIES_PER_SECTOR (512 / sizeof(uint64_t))
1350 static int write_reftable_entry(BlockDriverState *bs, int rt_index)
1351 {
1352     BDRVQcowState *s = bs->opaque;
1353     uint64_t buf[RT_ENTRIES_PER_SECTOR];
1354     int rt_start_index;
1355     int i, ret;
1356 
1357     rt_start_index = rt_index & ~(RT_ENTRIES_PER_SECTOR - 1);
1358     for (i = 0; i < RT_ENTRIES_PER_SECTOR; i++) {
1359         buf[i] = cpu_to_be64(s->refcount_table[rt_start_index + i]);
1360     }
1361 
1362     ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_REFCOUNT_TABLE,
1363             s->refcount_table_offset + rt_start_index * sizeof(uint64_t),
1364             sizeof(buf));
1365     if (ret < 0) {
1366         return ret;
1367     }
1368 
1369     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
1370     ret = bdrv_pwrite_sync(bs->file, s->refcount_table_offset +
1371             rt_start_index * sizeof(uint64_t), buf, sizeof(buf));
1372     if (ret < 0) {
1373         return ret;
1374     }
1375 
1376     return 0;
1377 }
1378 
1379 /*
1380  * Allocates a new cluster for the given refcount block (represented by its
1381  * offset in the image file) and copies the current content there. This function
1382  * does _not_ decrement the reference count for the currently occupied cluster.
1383  *
1384  * This function prints an informative message to stderr on error (and returns
1385  * -errno); on success, 0 is returned.
1386  */
1387 static int64_t realloc_refcount_block(BlockDriverState *bs, int reftable_index,
1388                                       uint64_t offset)
1389 {
1390     BDRVQcowState *s = bs->opaque;
1391     int64_t new_offset = 0;
1392     void *refcount_block = NULL;
1393     int ret;
1394 
1395     /* allocate new refcount block */
1396     new_offset = qcow2_alloc_clusters(bs, s->cluster_size);
1397     if (new_offset < 0) {
1398         fprintf(stderr, "Could not allocate new cluster: %s\n",
1399                 strerror(-new_offset));
1400         ret = new_offset;
1401         goto fail;
1402     }
1403 
1404     /* fetch current refcount block content */
1405     ret = qcow2_cache_get(bs, s->refcount_block_cache, offset, &refcount_block);
1406     if (ret < 0) {
1407         fprintf(stderr, "Could not fetch refcount block: %s\n", strerror(-ret));
1408         goto fail;
1409     }
1410 
1411     /* new block has not yet been entered into refcount table, therefore it is
1412      * no refcount block yet (regarding this check) */
1413     ret = qcow2_pre_write_overlap_check(bs, 0, new_offset, s->cluster_size);
1414     if (ret < 0) {
1415         fprintf(stderr, "Could not write refcount block; metadata overlap "
1416                 "check failed: %s\n", strerror(-ret));
1417         /* the image will be marked corrupt, so don't even attempt on freeing
1418          * the cluster */
1419         new_offset = 0;
1420         goto fail;
1421     }
1422 
1423     /* write to new block */
1424     ret = bdrv_write(bs->file, new_offset / BDRV_SECTOR_SIZE, refcount_block,
1425             s->cluster_sectors);
1426     if (ret < 0) {
1427         fprintf(stderr, "Could not write refcount block: %s\n", strerror(-ret));
1428         goto fail;
1429     }
1430 
1431     /* update refcount table */
1432     assert(!offset_into_cluster(s, new_offset));
1433     s->refcount_table[reftable_index] = new_offset;
1434     ret = write_reftable_entry(bs, reftable_index);
1435     if (ret < 0) {
1436         fprintf(stderr, "Could not update refcount table: %s\n",
1437                 strerror(-ret));
1438         goto fail;
1439     }
1440 
1441 fail:
1442     if (new_offset && (ret < 0)) {
1443         qcow2_free_clusters(bs, new_offset, s->cluster_size,
1444                 QCOW2_DISCARD_ALWAYS);
1445     }
1446     if (refcount_block) {
1447         if (ret < 0) {
1448             qcow2_cache_put(bs, s->refcount_block_cache, &refcount_block);
1449         } else {
1450             ret = qcow2_cache_put(bs, s->refcount_block_cache, &refcount_block);
1451         }
1452     }
1453     if (ret < 0) {
1454         return ret;
1455     }
1456     return new_offset;
1457 }
1458 
1459 /*
1460  * Checks an image for refcount consistency.
1461  *
1462  * Returns 0 if no errors are found, the number of errors in case the image is
1463  * detected as corrupted, and -errno when an internal error occurred.
1464  */
1465 int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
1466                           BdrvCheckMode fix)
1467 {
1468     BDRVQcowState *s = bs->opaque;
1469     int64_t size, i, highest_cluster;
1470     int nb_clusters, refcount1, refcount2;
1471     QCowSnapshot *sn;
1472     uint16_t *refcount_table;
1473     int ret;
1474 
1475     size = bdrv_getlength(bs->file);
1476     nb_clusters = size_to_clusters(s, size);
1477     refcount_table = g_malloc0(nb_clusters * sizeof(uint16_t));
1478 
1479     res->bfi.total_clusters =
1480         size_to_clusters(s, bs->total_sectors * BDRV_SECTOR_SIZE);
1481 
1482     /* header */
1483     inc_refcounts(bs, res, refcount_table, nb_clusters,
1484         0, s->cluster_size);
1485 
1486     /* current L1 table */
1487     ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
1488                              s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);
1489     if (ret < 0) {
1490         goto fail;
1491     }
1492 
1493     /* snapshots */
1494     for(i = 0; i < s->nb_snapshots; i++) {
1495         sn = s->snapshots + i;
1496         ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
1497             sn->l1_table_offset, sn->l1_size, 0);
1498         if (ret < 0) {
1499             goto fail;
1500         }
1501     }
1502     inc_refcounts(bs, res, refcount_table, nb_clusters,
1503         s->snapshots_offset, s->snapshots_size);
1504 
1505     /* refcount data */
1506     inc_refcounts(bs, res, refcount_table, nb_clusters,
1507         s->refcount_table_offset,
1508         s->refcount_table_size * sizeof(uint64_t));
1509 
1510     for(i = 0; i < s->refcount_table_size; i++) {
1511         uint64_t offset, cluster;
1512         offset = s->refcount_table[i];
1513         cluster = offset >> s->cluster_bits;
1514 
1515         /* Refcount blocks are cluster aligned */
1516         if (offset_into_cluster(s, offset)) {
1517             fprintf(stderr, "ERROR refcount block %" PRId64 " is not "
1518                 "cluster aligned; refcount table entry corrupted\n", i);
1519             res->corruptions++;
1520             continue;
1521         }
1522 
1523         if (cluster >= nb_clusters) {
1524             fprintf(stderr, "ERROR refcount block %" PRId64
1525                     " is outside image\n", i);
1526             res->corruptions++;
1527             continue;
1528         }
1529 
1530         if (offset != 0) {
1531             inc_refcounts(bs, res, refcount_table, nb_clusters,
1532                 offset, s->cluster_size);
1533             if (refcount_table[cluster] != 1) {
1534                 fprintf(stderr, "%s refcount block %" PRId64
1535                     " refcount=%d\n",
1536                     fix & BDRV_FIX_ERRORS ? "Repairing" :
1537                                             "ERROR",
1538                     i, refcount_table[cluster]);
1539 
1540                 if (fix & BDRV_FIX_ERRORS) {
1541                     int64_t new_offset;
1542 
1543                     new_offset = realloc_refcount_block(bs, i, offset);
1544                     if (new_offset < 0) {
1545                         res->corruptions++;
1546                         continue;
1547                     }
1548 
1549                     /* update refcounts */
1550                     if ((new_offset >> s->cluster_bits) >= nb_clusters) {
1551                         /* increase refcount_table size if necessary */
1552                         int old_nb_clusters = nb_clusters;
1553                         nb_clusters = (new_offset >> s->cluster_bits) + 1;
1554                         refcount_table = g_realloc(refcount_table,
1555                                 nb_clusters * sizeof(uint16_t));
1556                         memset(&refcount_table[old_nb_clusters], 0, (nb_clusters
1557                                 - old_nb_clusters) * sizeof(uint16_t));
1558                     }
1559                     refcount_table[cluster]--;
1560                     inc_refcounts(bs, res, refcount_table, nb_clusters,
1561                             new_offset, s->cluster_size);
1562 
1563                     res->corruptions_fixed++;
1564                 } else {
1565                     res->corruptions++;
1566                 }
1567             }
1568         }
1569     }
1570 
1571     /* compare ref counts */
1572     for (i = 0, highest_cluster = 0; i < nb_clusters; i++) {
1573         refcount1 = get_refcount(bs, i);
1574         if (refcount1 < 0) {
1575             fprintf(stderr, "Can't get refcount for cluster %" PRId64 ": %s\n",
1576                 i, strerror(-refcount1));
1577             res->check_errors++;
1578             continue;
1579         }
1580 
1581         refcount2 = refcount_table[i];
1582 
1583         if (refcount1 > 0 || refcount2 > 0) {
1584             highest_cluster = i;
1585         }
1586 
1587         if (refcount1 != refcount2) {
1588 
1589             /* Check if we're allowed to fix the mismatch */
1590             int *num_fixed = NULL;
1591             if (refcount1 > refcount2 && (fix & BDRV_FIX_LEAKS)) {
1592                 num_fixed = &res->leaks_fixed;
1593             } else if (refcount1 < refcount2 && (fix & BDRV_FIX_ERRORS)) {
1594                 num_fixed = &res->corruptions_fixed;
1595             }
1596 
1597             fprintf(stderr, "%s cluster %" PRId64 " refcount=%d reference=%d\n",
1598                    num_fixed != NULL     ? "Repairing" :
1599                    refcount1 < refcount2 ? "ERROR" :
1600                                            "Leaked",
1601                    i, refcount1, refcount2);
1602 
1603             if (num_fixed) {
1604                 ret = update_refcount(bs, i << s->cluster_bits, 1,
1605                                       refcount2 - refcount1,
1606                                       QCOW2_DISCARD_ALWAYS);
1607                 if (ret >= 0) {
1608                     (*num_fixed)++;
1609                     continue;
1610                 }
1611             }
1612 
1613             /* And if we couldn't, print an error */
1614             if (refcount1 < refcount2) {
1615                 res->corruptions++;
1616             } else {
1617                 res->leaks++;
1618             }
1619         }
1620     }
1621 
1622     /* check OFLAG_COPIED */
1623     ret = check_oflag_copied(bs, res, fix);
1624     if (ret < 0) {
1625         goto fail;
1626     }
1627 
1628     res->image_end_offset = (highest_cluster + 1) * s->cluster_size;
1629     ret = 0;
1630 
1631 fail:
1632     g_free(refcount_table);
1633 
1634     return ret;
1635 }
1636 
1637 #define overlaps_with(ofs, sz) \
1638     ranges_overlap(offset, size, ofs, sz)
1639 
1640 /*
1641  * Checks if the given offset into the image file is actually free to use by
1642  * looking for overlaps with important metadata sections (L1/L2 tables etc.),
1643  * i.e. a sanity check without relying on the refcount tables.
1644  *
1645  * The ign parameter specifies what checks not to perform (being a bitmask of
1646  * QCow2MetadataOverlap values), i.e., what sections to ignore.
1647  *
1648  * Returns:
1649  * - 0 if writing to this offset will not affect the mentioned metadata
1650  * - a positive QCow2MetadataOverlap value indicating one overlapping section
1651  * - a negative value (-errno) indicating an error while performing a check,
1652  *   e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
1653  */
1654 int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
1655                                  int64_t size)
1656 {
1657     BDRVQcowState *s = bs->opaque;
1658     int chk = s->overlap_check & ~ign;
1659     int i, j;
1660 
1661     if (!size) {
1662         return 0;
1663     }
1664 
1665     if (chk & QCOW2_OL_MAIN_HEADER) {
1666         if (offset < s->cluster_size) {
1667             return QCOW2_OL_MAIN_HEADER;
1668         }
1669     }
1670 
1671     /* align range to test to cluster boundaries */
1672     size = align_offset(offset_into_cluster(s, offset) + size, s->cluster_size);
1673     offset = start_of_cluster(s, offset);
1674 
1675     if ((chk & QCOW2_OL_ACTIVE_L1) && s->l1_size) {
1676         if (overlaps_with(s->l1_table_offset, s->l1_size * sizeof(uint64_t))) {
1677             return QCOW2_OL_ACTIVE_L1;
1678         }
1679     }
1680 
1681     if ((chk & QCOW2_OL_REFCOUNT_TABLE) && s->refcount_table_size) {
1682         if (overlaps_with(s->refcount_table_offset,
1683             s->refcount_table_size * sizeof(uint64_t))) {
1684             return QCOW2_OL_REFCOUNT_TABLE;
1685         }
1686     }
1687 
1688     if ((chk & QCOW2_OL_SNAPSHOT_TABLE) && s->snapshots_size) {
1689         if (overlaps_with(s->snapshots_offset, s->snapshots_size)) {
1690             return QCOW2_OL_SNAPSHOT_TABLE;
1691         }
1692     }
1693 
1694     if ((chk & QCOW2_OL_INACTIVE_L1) && s->snapshots) {
1695         for (i = 0; i < s->nb_snapshots; i++) {
1696             if (s->snapshots[i].l1_size &&
1697                 overlaps_with(s->snapshots[i].l1_table_offset,
1698                 s->snapshots[i].l1_size * sizeof(uint64_t))) {
1699                 return QCOW2_OL_INACTIVE_L1;
1700             }
1701         }
1702     }
1703 
1704     if ((chk & QCOW2_OL_ACTIVE_L2) && s->l1_table) {
1705         for (i = 0; i < s->l1_size; i++) {
1706             if ((s->l1_table[i] & L1E_OFFSET_MASK) &&
1707                 overlaps_with(s->l1_table[i] & L1E_OFFSET_MASK,
1708                 s->cluster_size)) {
1709                 return QCOW2_OL_ACTIVE_L2;
1710             }
1711         }
1712     }
1713 
1714     if ((chk & QCOW2_OL_REFCOUNT_BLOCK) && s->refcount_table) {
1715         for (i = 0; i < s->refcount_table_size; i++) {
1716             if ((s->refcount_table[i] & REFT_OFFSET_MASK) &&
1717                 overlaps_with(s->refcount_table[i] & REFT_OFFSET_MASK,
1718                 s->cluster_size)) {
1719                 return QCOW2_OL_REFCOUNT_BLOCK;
1720             }
1721         }
1722     }
1723 
1724     if ((chk & QCOW2_OL_INACTIVE_L2) && s->snapshots) {
1725         for (i = 0; i < s->nb_snapshots; i++) {
1726             uint64_t l1_ofs = s->snapshots[i].l1_table_offset;
1727             uint32_t l1_sz  = s->snapshots[i].l1_size;
1728             uint64_t l1_sz2 = l1_sz * sizeof(uint64_t);
1729             uint64_t *l1 = g_malloc(l1_sz2);
1730             int ret;
1731 
1732             ret = bdrv_pread(bs->file, l1_ofs, l1, l1_sz2);
1733             if (ret < 0) {
1734                 g_free(l1);
1735                 return ret;
1736             }
1737 
1738             for (j = 0; j < l1_sz; j++) {
1739                 uint64_t l2_ofs = be64_to_cpu(l1[j]) & L1E_OFFSET_MASK;
1740                 if (l2_ofs && overlaps_with(l2_ofs, s->cluster_size)) {
1741                     g_free(l1);
1742                     return QCOW2_OL_INACTIVE_L2;
1743                 }
1744             }
1745 
1746             g_free(l1);
1747         }
1748     }
1749 
1750     return 0;
1751 }
1752 
1753 static const char *metadata_ol_names[] = {
1754     [QCOW2_OL_MAIN_HEADER_BITNR]    = "qcow2_header",
1755     [QCOW2_OL_ACTIVE_L1_BITNR]      = "active L1 table",
1756     [QCOW2_OL_ACTIVE_L2_BITNR]      = "active L2 table",
1757     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = "refcount table",
1758     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = "refcount block",
1759     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = "snapshot table",
1760     [QCOW2_OL_INACTIVE_L1_BITNR]    = "inactive L1 table",
1761     [QCOW2_OL_INACTIVE_L2_BITNR]    = "inactive L2 table",
1762 };
1763 
1764 /*
1765  * First performs a check for metadata overlaps (through
1766  * qcow2_check_metadata_overlap); if that fails with a negative value (error
1767  * while performing a check), that value is returned. If an impending overlap
1768  * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
1769  * and -EIO returned.
1770  *
1771  * Returns 0 if there were neither overlaps nor errors while checking for
1772  * overlaps; or a negative value (-errno) on error.
1773  */
1774 int qcow2_pre_write_overlap_check(BlockDriverState *bs, int ign, int64_t offset,
1775                                   int64_t size)
1776 {
1777     int ret = qcow2_check_metadata_overlap(bs, ign, offset, size);
1778 
1779     if (ret < 0) {
1780         return ret;
1781     } else if (ret > 0) {
1782         int metadata_ol_bitnr = ffs(ret) - 1;
1783         char *message;
1784         QObject *data;
1785 
1786         assert(metadata_ol_bitnr < QCOW2_OL_MAX_BITNR);
1787 
1788         fprintf(stderr, "qcow2: Preventing invalid write on metadata (overlaps "
1789                 "with %s); image marked as corrupt.\n",
1790                 metadata_ol_names[metadata_ol_bitnr]);
1791         message = g_strdup_printf("Prevented %s overwrite",
1792                 metadata_ol_names[metadata_ol_bitnr]);
1793         data = qobject_from_jsonf("{ 'device': %s, 'msg': %s, 'offset': %"
1794                 PRId64 ", 'size': %" PRId64 " }", bs->device_name, message,
1795                 offset, size);
1796         monitor_protocol_event(QEVENT_BLOCK_IMAGE_CORRUPTED, data);
1797         g_free(message);
1798         qobject_decref(data);
1799 
1800         qcow2_mark_corrupt(bs);
1801         bs->drv = NULL; /* make BDS unusable */
1802         return -EIO;
1803     }
1804 
1805     return 0;
1806 }
1807