xref: /openbmc/qemu/block/qcow2-cluster.c (revision 795c40b8)
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 <zlib.h>
27 
28 #include "qapi/error.h"
29 #include "qemu-common.h"
30 #include "block/block_int.h"
31 #include "block/qcow2.h"
32 #include "qemu/bswap.h"
33 #include "trace.h"
34 
35 int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
36                         bool exact_size)
37 {
38     BDRVQcow2State *s = bs->opaque;
39     int new_l1_size2, ret, i;
40     uint64_t *new_l1_table;
41     int64_t old_l1_table_offset, old_l1_size;
42     int64_t new_l1_table_offset, new_l1_size;
43     uint8_t data[12];
44 
45     if (min_size <= s->l1_size)
46         return 0;
47 
48     /* Do a sanity check on min_size before trying to calculate new_l1_size
49      * (this prevents overflows during the while loop for the calculation of
50      * new_l1_size) */
51     if (min_size > INT_MAX / sizeof(uint64_t)) {
52         return -EFBIG;
53     }
54 
55     if (exact_size) {
56         new_l1_size = min_size;
57     } else {
58         /* Bump size up to reduce the number of times we have to grow */
59         new_l1_size = s->l1_size;
60         if (new_l1_size == 0) {
61             new_l1_size = 1;
62         }
63         while (min_size > new_l1_size) {
64             new_l1_size = (new_l1_size * 3 + 1) / 2;
65         }
66     }
67 
68     QEMU_BUILD_BUG_ON(QCOW_MAX_L1_SIZE > INT_MAX);
69     if (new_l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
70         return -EFBIG;
71     }
72 
73 #ifdef DEBUG_ALLOC2
74     fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
75             s->l1_size, new_l1_size);
76 #endif
77 
78     new_l1_size2 = sizeof(uint64_t) * new_l1_size;
79     new_l1_table = qemu_try_blockalign(bs->file->bs,
80                                        align_offset(new_l1_size2, 512));
81     if (new_l1_table == NULL) {
82         return -ENOMEM;
83     }
84     memset(new_l1_table, 0, align_offset(new_l1_size2, 512));
85 
86     if (s->l1_size) {
87         memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
88     }
89 
90     /* write new table (align to cluster) */
91     BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
92     new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
93     if (new_l1_table_offset < 0) {
94         qemu_vfree(new_l1_table);
95         return new_l1_table_offset;
96     }
97 
98     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
99     if (ret < 0) {
100         goto fail;
101     }
102 
103     /* the L1 position has not yet been updated, so these clusters must
104      * indeed be completely free */
105     ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,
106                                         new_l1_size2);
107     if (ret < 0) {
108         goto fail;
109     }
110 
111     BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
112     for(i = 0; i < s->l1_size; i++)
113         new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
114     ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset,
115                            new_l1_table, new_l1_size2);
116     if (ret < 0)
117         goto fail;
118     for(i = 0; i < s->l1_size; i++)
119         new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
120 
121     /* set new table */
122     BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
123     stl_be_p(data, new_l1_size);
124     stq_be_p(data + 4, new_l1_table_offset);
125     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size),
126                            data, sizeof(data));
127     if (ret < 0) {
128         goto fail;
129     }
130     qemu_vfree(s->l1_table);
131     old_l1_table_offset = s->l1_table_offset;
132     s->l1_table_offset = new_l1_table_offset;
133     s->l1_table = new_l1_table;
134     old_l1_size = s->l1_size;
135     s->l1_size = new_l1_size;
136     qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
137                         QCOW2_DISCARD_OTHER);
138     return 0;
139  fail:
140     qemu_vfree(new_l1_table);
141     qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
142                         QCOW2_DISCARD_OTHER);
143     return ret;
144 }
145 
146 /*
147  * l2_load
148  *
149  * Loads a L2 table into memory. If the table is in the cache, the cache
150  * is used; otherwise the L2 table is loaded from the image file.
151  *
152  * Returns a pointer to the L2 table on success, or NULL if the read from
153  * the image file failed.
154  */
155 
156 static int l2_load(BlockDriverState *bs, uint64_t l2_offset,
157     uint64_t **l2_table)
158 {
159     BDRVQcow2State *s = bs->opaque;
160 
161     return qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
162                            (void **)l2_table);
163 }
164 
165 /*
166  * Writes one sector of the L1 table to the disk (can't update single entries
167  * and we really don't want bdrv_pread to perform a read-modify-write)
168  */
169 #define L1_ENTRIES_PER_SECTOR (512 / 8)
170 int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index)
171 {
172     BDRVQcow2State *s = bs->opaque;
173     uint64_t buf[L1_ENTRIES_PER_SECTOR] = { 0 };
174     int l1_start_index;
175     int i, ret;
176 
177     l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);
178     for (i = 0; i < L1_ENTRIES_PER_SECTOR && l1_start_index + i < s->l1_size;
179          i++)
180     {
181         buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
182     }
183 
184     ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L1,
185             s->l1_table_offset + 8 * l1_start_index, sizeof(buf));
186     if (ret < 0) {
187         return ret;
188     }
189 
190     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
191     ret = bdrv_pwrite_sync(bs->file,
192                            s->l1_table_offset + 8 * l1_start_index,
193                            buf, sizeof(buf));
194     if (ret < 0) {
195         return ret;
196     }
197 
198     return 0;
199 }
200 
201 /*
202  * l2_allocate
203  *
204  * Allocate a new l2 entry in the file. If l1_index points to an already
205  * used entry in the L2 table (i.e. we are doing a copy on write for the L2
206  * table) copy the contents of the old L2 table into the newly allocated one.
207  * Otherwise the new table is initialized with zeros.
208  *
209  */
210 
211 static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
212 {
213     BDRVQcow2State *s = bs->opaque;
214     uint64_t old_l2_offset;
215     uint64_t *l2_table = NULL;
216     int64_t l2_offset;
217     int ret;
218 
219     old_l2_offset = s->l1_table[l1_index];
220 
221     trace_qcow2_l2_allocate(bs, l1_index);
222 
223     /* allocate a new l2 entry */
224 
225     l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
226     if (l2_offset < 0) {
227         ret = l2_offset;
228         goto fail;
229     }
230 
231     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
232     if (ret < 0) {
233         goto fail;
234     }
235 
236     /* allocate a new entry in the l2 cache */
237 
238     trace_qcow2_l2_allocate_get_empty(bs, l1_index);
239     ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);
240     if (ret < 0) {
241         goto fail;
242     }
243 
244     l2_table = *table;
245 
246     if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
247         /* if there was no old l2 table, clear the new table */
248         memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
249     } else {
250         uint64_t* old_table;
251 
252         /* if there was an old l2 table, read it from the disk */
253         BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
254         ret = qcow2_cache_get(bs, s->l2_table_cache,
255             old_l2_offset & L1E_OFFSET_MASK,
256             (void**) &old_table);
257         if (ret < 0) {
258             goto fail;
259         }
260 
261         memcpy(l2_table, old_table, s->cluster_size);
262 
263         qcow2_cache_put(bs, s->l2_table_cache, (void **) &old_table);
264     }
265 
266     /* write the l2 table to the file */
267     BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
268 
269     trace_qcow2_l2_allocate_write_l2(bs, l1_index);
270     qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
271     ret = qcow2_cache_flush(bs, s->l2_table_cache);
272     if (ret < 0) {
273         goto fail;
274     }
275 
276     /* update the L1 entry */
277     trace_qcow2_l2_allocate_write_l1(bs, l1_index);
278     s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
279     ret = qcow2_write_l1_entry(bs, l1_index);
280     if (ret < 0) {
281         goto fail;
282     }
283 
284     *table = l2_table;
285     trace_qcow2_l2_allocate_done(bs, l1_index, 0);
286     return 0;
287 
288 fail:
289     trace_qcow2_l2_allocate_done(bs, l1_index, ret);
290     if (l2_table != NULL) {
291         qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
292     }
293     s->l1_table[l1_index] = old_l2_offset;
294     if (l2_offset > 0) {
295         qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
296                             QCOW2_DISCARD_ALWAYS);
297     }
298     return ret;
299 }
300 
301 /*
302  * Checks how many clusters in a given L2 table are contiguous in the image
303  * file. As soon as one of the flags in the bitmask stop_flags changes compared
304  * to the first cluster, the search is stopped and the cluster is not counted
305  * as contiguous. (This allows it, for example, to stop at the first compressed
306  * cluster which may require a different handling)
307  */
308 static int count_contiguous_clusters(int nb_clusters, int cluster_size,
309         uint64_t *l2_table, uint64_t stop_flags)
310 {
311     int i;
312     QCow2ClusterType first_cluster_type;
313     uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW_OFLAG_COMPRESSED;
314     uint64_t first_entry = be64_to_cpu(l2_table[0]);
315     uint64_t offset = first_entry & mask;
316 
317     if (!offset) {
318         return 0;
319     }
320 
321     /* must be allocated */
322     first_cluster_type = qcow2_get_cluster_type(first_entry);
323     assert(first_cluster_type == QCOW2_CLUSTER_NORMAL ||
324            first_cluster_type == QCOW2_CLUSTER_ZERO_ALLOC);
325 
326     for (i = 0; i < nb_clusters; i++) {
327         uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;
328         if (offset + (uint64_t) i * cluster_size != l2_entry) {
329             break;
330         }
331     }
332 
333 	return i;
334 }
335 
336 /*
337  * Checks how many consecutive unallocated clusters in a given L2
338  * table have the same cluster type.
339  */
340 static int count_contiguous_clusters_unallocated(int nb_clusters,
341                                                  uint64_t *l2_table,
342                                                  QCow2ClusterType wanted_type)
343 {
344     int i;
345 
346     assert(wanted_type == QCOW2_CLUSTER_ZERO_PLAIN ||
347            wanted_type == QCOW2_CLUSTER_UNALLOCATED);
348     for (i = 0; i < nb_clusters; i++) {
349         uint64_t entry = be64_to_cpu(l2_table[i]);
350         QCow2ClusterType type = qcow2_get_cluster_type(entry);
351 
352         if (type != wanted_type) {
353             break;
354         }
355     }
356 
357     return i;
358 }
359 
360 /* The crypt function is compatible with the linux cryptoloop
361    algorithm for < 4 GB images. NOTE: out_buf == in_buf is
362    supported */
363 int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
364                           uint8_t *out_buf, const uint8_t *in_buf,
365                           int nb_sectors, bool enc,
366                           Error **errp)
367 {
368     union {
369         uint64_t ll[2];
370         uint8_t b[16];
371     } ivec;
372     int i;
373     int ret;
374 
375     for(i = 0; i < nb_sectors; i++) {
376         ivec.ll[0] = cpu_to_le64(sector_num);
377         ivec.ll[1] = 0;
378         if (qcrypto_cipher_setiv(s->cipher,
379                                  ivec.b, G_N_ELEMENTS(ivec.b),
380                                  errp) < 0) {
381             return -1;
382         }
383         if (enc) {
384             ret = qcrypto_cipher_encrypt(s->cipher,
385                                          in_buf,
386                                          out_buf,
387                                          512,
388                                          errp);
389         } else {
390             ret = qcrypto_cipher_decrypt(s->cipher,
391                                          in_buf,
392                                          out_buf,
393                                          512,
394                                          errp);
395         }
396         if (ret < 0) {
397             return -1;
398         }
399         sector_num++;
400         in_buf += 512;
401         out_buf += 512;
402     }
403     return 0;
404 }
405 
406 static int coroutine_fn do_perform_cow(BlockDriverState *bs,
407                                        uint64_t src_cluster_offset,
408                                        uint64_t cluster_offset,
409                                        int offset_in_cluster,
410                                        int bytes)
411 {
412     BDRVQcow2State *s = bs->opaque;
413     QEMUIOVector qiov;
414     struct iovec iov;
415     int ret;
416 
417     iov.iov_len = bytes;
418     iov.iov_base = qemu_try_blockalign(bs, iov.iov_len);
419     if (iov.iov_base == NULL) {
420         return -ENOMEM;
421     }
422 
423     qemu_iovec_init_external(&qiov, &iov, 1);
424 
425     BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
426 
427     if (!bs->drv) {
428         ret = -ENOMEDIUM;
429         goto out;
430     }
431 
432     /* Call .bdrv_co_readv() directly instead of using the public block-layer
433      * interface.  This avoids double I/O throttling and request tracking,
434      * which can lead to deadlock when block layer copy-on-read is enabled.
435      */
436     ret = bs->drv->bdrv_co_preadv(bs, src_cluster_offset + offset_in_cluster,
437                                   bytes, &qiov, 0);
438     if (ret < 0) {
439         goto out;
440     }
441 
442     if (bs->encrypted) {
443         Error *err = NULL;
444         int64_t sector = (src_cluster_offset + offset_in_cluster)
445                          >> BDRV_SECTOR_BITS;
446         assert(s->cipher);
447         assert((offset_in_cluster & ~BDRV_SECTOR_MASK) == 0);
448         assert((bytes & ~BDRV_SECTOR_MASK) == 0);
449         if (qcow2_encrypt_sectors(s, sector, iov.iov_base, iov.iov_base,
450                                   bytes >> BDRV_SECTOR_BITS, true, &err) < 0) {
451             ret = -EIO;
452             error_free(err);
453             goto out;
454         }
455     }
456 
457     ret = qcow2_pre_write_overlap_check(bs, 0,
458             cluster_offset + offset_in_cluster, bytes);
459     if (ret < 0) {
460         goto out;
461     }
462 
463     BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
464     ret = bdrv_co_pwritev(bs->file, cluster_offset + offset_in_cluster,
465                           bytes, &qiov, 0);
466     if (ret < 0) {
467         goto out;
468     }
469 
470     ret = 0;
471 out:
472     qemu_vfree(iov.iov_base);
473     return ret;
474 }
475 
476 
477 /*
478  * get_cluster_offset
479  *
480  * For a given offset of the virtual disk, find the cluster type and offset in
481  * the qcow2 file. The offset is stored in *cluster_offset.
482  *
483  * On entry, *bytes is the maximum number of contiguous bytes starting at
484  * offset that we are interested in.
485  *
486  * On exit, *bytes is the number of bytes starting at offset that have the same
487  * cluster type and (if applicable) are stored contiguously in the image file.
488  * Compressed clusters are always returned one by one.
489  *
490  * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
491  * cases.
492  */
493 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
494                              unsigned int *bytes, uint64_t *cluster_offset)
495 {
496     BDRVQcow2State *s = bs->opaque;
497     unsigned int l2_index;
498     uint64_t l1_index, l2_offset, *l2_table;
499     int l1_bits, c;
500     unsigned int offset_in_cluster;
501     uint64_t bytes_available, bytes_needed, nb_clusters;
502     QCow2ClusterType type;
503     int ret;
504 
505     offset_in_cluster = offset_into_cluster(s, offset);
506     bytes_needed = (uint64_t) *bytes + offset_in_cluster;
507 
508     l1_bits = s->l2_bits + s->cluster_bits;
509 
510     /* compute how many bytes there are between the start of the cluster
511      * containing offset and the end of the l1 entry */
512     bytes_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1))
513                     + offset_in_cluster;
514 
515     if (bytes_needed > bytes_available) {
516         bytes_needed = bytes_available;
517     }
518 
519     *cluster_offset = 0;
520 
521     /* seek to the l2 offset in the l1 table */
522 
523     l1_index = offset >> l1_bits;
524     if (l1_index >= s->l1_size) {
525         type = QCOW2_CLUSTER_UNALLOCATED;
526         goto out;
527     }
528 
529     l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
530     if (!l2_offset) {
531         type = QCOW2_CLUSTER_UNALLOCATED;
532         goto out;
533     }
534 
535     if (offset_into_cluster(s, l2_offset)) {
536         qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
537                                 " unaligned (L1 index: %#" PRIx64 ")",
538                                 l2_offset, l1_index);
539         return -EIO;
540     }
541 
542     /* load the l2 table in memory */
543 
544     ret = l2_load(bs, l2_offset, &l2_table);
545     if (ret < 0) {
546         return ret;
547     }
548 
549     /* find the cluster offset for the given disk offset */
550 
551     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
552     *cluster_offset = be64_to_cpu(l2_table[l2_index]);
553 
554     nb_clusters = size_to_clusters(s, bytes_needed);
555     /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
556      * integers; the minimum cluster size is 512, so this assertion is always
557      * true */
558     assert(nb_clusters <= INT_MAX);
559 
560     type = qcow2_get_cluster_type(*cluster_offset);
561     if (s->qcow_version < 3 && (type == QCOW2_CLUSTER_ZERO_PLAIN ||
562                                 type == QCOW2_CLUSTER_ZERO_ALLOC)) {
563         qcow2_signal_corruption(bs, true, -1, -1, "Zero cluster entry found"
564                                 " in pre-v3 image (L2 offset: %#" PRIx64
565                                 ", L2 index: %#x)", l2_offset, l2_index);
566         ret = -EIO;
567         goto fail;
568     }
569     switch (type) {
570     case QCOW2_CLUSTER_COMPRESSED:
571         /* Compressed clusters can only be processed one by one */
572         c = 1;
573         *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;
574         break;
575     case QCOW2_CLUSTER_ZERO_PLAIN:
576     case QCOW2_CLUSTER_UNALLOCATED:
577         /* how many empty clusters ? */
578         c = count_contiguous_clusters_unallocated(nb_clusters,
579                                                   &l2_table[l2_index], type);
580         *cluster_offset = 0;
581         break;
582     case QCOW2_CLUSTER_ZERO_ALLOC:
583     case QCOW2_CLUSTER_NORMAL:
584         /* how many allocated clusters ? */
585         c = count_contiguous_clusters(nb_clusters, s->cluster_size,
586                                       &l2_table[l2_index], QCOW_OFLAG_ZERO);
587         *cluster_offset &= L2E_OFFSET_MASK;
588         if (offset_into_cluster(s, *cluster_offset)) {
589             qcow2_signal_corruption(bs, true, -1, -1,
590                                     "Cluster allocation offset %#"
591                                     PRIx64 " unaligned (L2 offset: %#" PRIx64
592                                     ", L2 index: %#x)", *cluster_offset,
593                                     l2_offset, l2_index);
594             ret = -EIO;
595             goto fail;
596         }
597         break;
598     default:
599         abort();
600     }
601 
602     qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
603 
604     bytes_available = (int64_t)c * s->cluster_size;
605 
606 out:
607     if (bytes_available > bytes_needed) {
608         bytes_available = bytes_needed;
609     }
610 
611     /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
612      * subtracting offset_in_cluster will therefore definitely yield something
613      * not exceeding UINT_MAX */
614     assert(bytes_available - offset_in_cluster <= UINT_MAX);
615     *bytes = bytes_available - offset_in_cluster;
616 
617     return type;
618 
619 fail:
620     qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
621     return ret;
622 }
623 
624 /*
625  * get_cluster_table
626  *
627  * for a given disk offset, load (and allocate if needed)
628  * the l2 table.
629  *
630  * the l2 table offset in the qcow2 file and the cluster index
631  * in the l2 table are given to the caller.
632  *
633  * Returns 0 on success, -errno in failure case
634  */
635 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
636                              uint64_t **new_l2_table,
637                              int *new_l2_index)
638 {
639     BDRVQcow2State *s = bs->opaque;
640     unsigned int l2_index;
641     uint64_t l1_index, l2_offset;
642     uint64_t *l2_table = NULL;
643     int ret;
644 
645     /* seek to the l2 offset in the l1 table */
646 
647     l1_index = offset >> (s->l2_bits + s->cluster_bits);
648     if (l1_index >= s->l1_size) {
649         ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
650         if (ret < 0) {
651             return ret;
652         }
653     }
654 
655     assert(l1_index < s->l1_size);
656     l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
657     if (offset_into_cluster(s, l2_offset)) {
658         qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
659                                 " unaligned (L1 index: %#" PRIx64 ")",
660                                 l2_offset, l1_index);
661         return -EIO;
662     }
663 
664     /* seek the l2 table of the given l2 offset */
665 
666     if (s->l1_table[l1_index] & QCOW_OFLAG_COPIED) {
667         /* load the l2 table in memory */
668         ret = l2_load(bs, l2_offset, &l2_table);
669         if (ret < 0) {
670             return ret;
671         }
672     } else {
673         /* First allocate a new L2 table (and do COW if needed) */
674         ret = l2_allocate(bs, l1_index, &l2_table);
675         if (ret < 0) {
676             return ret;
677         }
678 
679         /* Then decrease the refcount of the old table */
680         if (l2_offset) {
681             qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
682                                 QCOW2_DISCARD_OTHER);
683         }
684     }
685 
686     /* find the cluster offset for the given disk offset */
687 
688     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
689 
690     *new_l2_table = l2_table;
691     *new_l2_index = l2_index;
692 
693     return 0;
694 }
695 
696 /*
697  * alloc_compressed_cluster_offset
698  *
699  * For a given offset of the disk image, return cluster offset in
700  * qcow2 file.
701  *
702  * If the offset is not found, allocate a new compressed cluster.
703  *
704  * Return the cluster offset if successful,
705  * Return 0, otherwise.
706  *
707  */
708 
709 uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
710                                                uint64_t offset,
711                                                int compressed_size)
712 {
713     BDRVQcow2State *s = bs->opaque;
714     int l2_index, ret;
715     uint64_t *l2_table;
716     int64_t cluster_offset;
717     int nb_csectors;
718 
719     ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
720     if (ret < 0) {
721         return 0;
722     }
723 
724     /* Compression can't overwrite anything. Fail if the cluster was already
725      * allocated. */
726     cluster_offset = be64_to_cpu(l2_table[l2_index]);
727     if (cluster_offset & L2E_OFFSET_MASK) {
728         qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
729         return 0;
730     }
731 
732     cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
733     if (cluster_offset < 0) {
734         qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
735         return 0;
736     }
737 
738     nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
739                   (cluster_offset >> 9);
740 
741     cluster_offset |= QCOW_OFLAG_COMPRESSED |
742                       ((uint64_t)nb_csectors << s->csize_shift);
743 
744     /* update L2 table */
745 
746     /* compressed clusters never have the copied flag */
747 
748     BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
749     qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
750     l2_table[l2_index] = cpu_to_be64(cluster_offset);
751     qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
752 
753     return cluster_offset;
754 }
755 
756 static int perform_cow(BlockDriverState *bs, QCowL2Meta *m, Qcow2COWRegion *r)
757 {
758     BDRVQcow2State *s = bs->opaque;
759     int ret;
760 
761     if (r->nb_bytes == 0) {
762         return 0;
763     }
764 
765     qemu_co_mutex_unlock(&s->lock);
766     ret = do_perform_cow(bs, m->offset, m->alloc_offset, r->offset, r->nb_bytes);
767     qemu_co_mutex_lock(&s->lock);
768 
769     if (ret < 0) {
770         return ret;
771     }
772 
773     /*
774      * Before we update the L2 table to actually point to the new cluster, we
775      * need to be sure that the refcounts have been increased and COW was
776      * handled.
777      */
778     qcow2_cache_depends_on_flush(s->l2_table_cache);
779 
780     return 0;
781 }
782 
783 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
784 {
785     BDRVQcow2State *s = bs->opaque;
786     int i, j = 0, l2_index, ret;
787     uint64_t *old_cluster, *l2_table;
788     uint64_t cluster_offset = m->alloc_offset;
789 
790     trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
791     assert(m->nb_clusters > 0);
792 
793     old_cluster = g_try_new(uint64_t, m->nb_clusters);
794     if (old_cluster == NULL) {
795         ret = -ENOMEM;
796         goto err;
797     }
798 
799     /* copy content of unmodified sectors */
800     ret = perform_cow(bs, m, &m->cow_start);
801     if (ret < 0) {
802         goto err;
803     }
804 
805     ret = perform_cow(bs, m, &m->cow_end);
806     if (ret < 0) {
807         goto err;
808     }
809 
810     /* Update L2 table. */
811     if (s->use_lazy_refcounts) {
812         qcow2_mark_dirty(bs);
813     }
814     if (qcow2_need_accurate_refcounts(s)) {
815         qcow2_cache_set_dependency(bs, s->l2_table_cache,
816                                    s->refcount_block_cache);
817     }
818 
819     ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
820     if (ret < 0) {
821         goto err;
822     }
823     qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
824 
825     assert(l2_index + m->nb_clusters <= s->l2_size);
826     for (i = 0; i < m->nb_clusters; i++) {
827         /* if two concurrent writes happen to the same unallocated cluster
828          * each write allocates separate cluster and writes data concurrently.
829          * The first one to complete updates l2 table with pointer to its
830          * cluster the second one has to do RMW (which is done above by
831          * perform_cow()), update l2 table with its cluster pointer and free
832          * old cluster. This is what this loop does */
833         if (l2_table[l2_index + i] != 0) {
834             old_cluster[j++] = l2_table[l2_index + i];
835         }
836 
837         l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
838                     (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
839      }
840 
841 
842     qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
843 
844     /*
845      * If this was a COW, we need to decrease the refcount of the old cluster.
846      *
847      * Don't discard clusters that reach a refcount of 0 (e.g. compressed
848      * clusters), the next write will reuse them anyway.
849      */
850     if (!m->keep_old_clusters && j != 0) {
851         for (i = 0; i < j; i++) {
852             qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,
853                                     QCOW2_DISCARD_NEVER);
854         }
855     }
856 
857     ret = 0;
858 err:
859     g_free(old_cluster);
860     return ret;
861  }
862 
863 /*
864  * Returns the number of contiguous clusters that can be used for an allocating
865  * write, but require COW to be performed (this includes yet unallocated space,
866  * which must copy from the backing file)
867  */
868 static int count_cow_clusters(BDRVQcow2State *s, int nb_clusters,
869     uint64_t *l2_table, int l2_index)
870 {
871     int i;
872 
873     for (i = 0; i < nb_clusters; i++) {
874         uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);
875         QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
876 
877         switch(cluster_type) {
878         case QCOW2_CLUSTER_NORMAL:
879             if (l2_entry & QCOW_OFLAG_COPIED) {
880                 goto out;
881             }
882             break;
883         case QCOW2_CLUSTER_UNALLOCATED:
884         case QCOW2_CLUSTER_COMPRESSED:
885         case QCOW2_CLUSTER_ZERO_PLAIN:
886         case QCOW2_CLUSTER_ZERO_ALLOC:
887             break;
888         default:
889             abort();
890         }
891     }
892 
893 out:
894     assert(i <= nb_clusters);
895     return i;
896 }
897 
898 /*
899  * Check if there already is an AIO write request in flight which allocates
900  * the same cluster. In this case we need to wait until the previous
901  * request has completed and updated the L2 table accordingly.
902  *
903  * Returns:
904  *   0       if there was no dependency. *cur_bytes indicates the number of
905  *           bytes from guest_offset that can be read before the next
906  *           dependency must be processed (or the request is complete)
907  *
908  *   -EAGAIN if we had to wait for another request, previously gathered
909  *           information on cluster allocation may be invalid now. The caller
910  *           must start over anyway, so consider *cur_bytes undefined.
911  */
912 static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
913     uint64_t *cur_bytes, QCowL2Meta **m)
914 {
915     BDRVQcow2State *s = bs->opaque;
916     QCowL2Meta *old_alloc;
917     uint64_t bytes = *cur_bytes;
918 
919     QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
920 
921         uint64_t start = guest_offset;
922         uint64_t end = start + bytes;
923         uint64_t old_start = l2meta_cow_start(old_alloc);
924         uint64_t old_end = l2meta_cow_end(old_alloc);
925 
926         if (end <= old_start || start >= old_end) {
927             /* No intersection */
928         } else {
929             if (start < old_start) {
930                 /* Stop at the start of a running allocation */
931                 bytes = old_start - start;
932             } else {
933                 bytes = 0;
934             }
935 
936             /* Stop if already an l2meta exists. After yielding, it wouldn't
937              * be valid any more, so we'd have to clean up the old L2Metas
938              * and deal with requests depending on them before starting to
939              * gather new ones. Not worth the trouble. */
940             if (bytes == 0 && *m) {
941                 *cur_bytes = 0;
942                 return 0;
943             }
944 
945             if (bytes == 0) {
946                 /* Wait for the dependency to complete. We need to recheck
947                  * the free/allocated clusters when we continue. */
948                 qemu_co_queue_wait(&old_alloc->dependent_requests, &s->lock);
949                 return -EAGAIN;
950             }
951         }
952     }
953 
954     /* Make sure that existing clusters and new allocations are only used up to
955      * the next dependency if we shortened the request above */
956     *cur_bytes = bytes;
957 
958     return 0;
959 }
960 
961 /*
962  * Checks how many already allocated clusters that don't require a copy on
963  * write there are at the given guest_offset (up to *bytes). If
964  * *host_offset is not zero, only physically contiguous clusters beginning at
965  * this host offset are counted.
966  *
967  * Note that guest_offset may not be cluster aligned. In this case, the
968  * returned *host_offset points to exact byte referenced by guest_offset and
969  * therefore isn't cluster aligned as well.
970  *
971  * Returns:
972  *   0:     if no allocated clusters are available at the given offset.
973  *          *bytes is normally unchanged. It is set to 0 if the cluster
974  *          is allocated and doesn't need COW, but doesn't have the right
975  *          physical offset.
976  *
977  *   1:     if allocated clusters that don't require a COW are available at
978  *          the requested offset. *bytes may have decreased and describes
979  *          the length of the area that can be written to.
980  *
981  *  -errno: in error cases
982  */
983 static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
984     uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
985 {
986     BDRVQcow2State *s = bs->opaque;
987     int l2_index;
988     uint64_t cluster_offset;
989     uint64_t *l2_table;
990     uint64_t nb_clusters;
991     unsigned int keep_clusters;
992     int ret;
993 
994     trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
995                               *bytes);
996 
997     assert(*host_offset == 0 ||    offset_into_cluster(s, guest_offset)
998                                 == offset_into_cluster(s, *host_offset));
999 
1000     /*
1001      * Calculate the number of clusters to look for. We stop at L2 table
1002      * boundaries to keep things simple.
1003      */
1004     nb_clusters =
1005         size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1006 
1007     l2_index = offset_to_l2_index(s, guest_offset);
1008     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1009     assert(nb_clusters <= INT_MAX);
1010 
1011     /* Find L2 entry for the first involved cluster */
1012     ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1013     if (ret < 0) {
1014         return ret;
1015     }
1016 
1017     cluster_offset = be64_to_cpu(l2_table[l2_index]);
1018 
1019     /* Check how many clusters are already allocated and don't need COW */
1020     if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL
1021         && (cluster_offset & QCOW_OFLAG_COPIED))
1022     {
1023         /* If a specific host_offset is required, check it */
1024         bool offset_matches =
1025             (cluster_offset & L2E_OFFSET_MASK) == *host_offset;
1026 
1027         if (offset_into_cluster(s, cluster_offset & L2E_OFFSET_MASK)) {
1028             qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "
1029                                     "%#llx unaligned (guest offset: %#" PRIx64
1030                                     ")", cluster_offset & L2E_OFFSET_MASK,
1031                                     guest_offset);
1032             ret = -EIO;
1033             goto out;
1034         }
1035 
1036         if (*host_offset != 0 && !offset_matches) {
1037             *bytes = 0;
1038             ret = 0;
1039             goto out;
1040         }
1041 
1042         /* We keep all QCOW_OFLAG_COPIED clusters */
1043         keep_clusters =
1044             count_contiguous_clusters(nb_clusters, s->cluster_size,
1045                                       &l2_table[l2_index],
1046                                       QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);
1047         assert(keep_clusters <= nb_clusters);
1048 
1049         *bytes = MIN(*bytes,
1050                  keep_clusters * s->cluster_size
1051                  - offset_into_cluster(s, guest_offset));
1052 
1053         ret = 1;
1054     } else {
1055         ret = 0;
1056     }
1057 
1058     /* Cleanup */
1059 out:
1060     qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1061 
1062     /* Only return a host offset if we actually made progress. Otherwise we
1063      * would make requirements for handle_alloc() that it can't fulfill */
1064     if (ret > 0) {
1065         *host_offset = (cluster_offset & L2E_OFFSET_MASK)
1066                      + offset_into_cluster(s, guest_offset);
1067     }
1068 
1069     return ret;
1070 }
1071 
1072 /*
1073  * Allocates new clusters for the given guest_offset.
1074  *
1075  * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1076  * contain the number of clusters that have been allocated and are contiguous
1077  * in the image file.
1078  *
1079  * If *host_offset is non-zero, it specifies the offset in the image file at
1080  * which the new clusters must start. *nb_clusters can be 0 on return in this
1081  * case if the cluster at host_offset is already in use. If *host_offset is
1082  * zero, the clusters can be allocated anywhere in the image file.
1083  *
1084  * *host_offset is updated to contain the offset into the image file at which
1085  * the first allocated cluster starts.
1086  *
1087  * Return 0 on success and -errno in error cases. -EAGAIN means that the
1088  * function has been waiting for another request and the allocation must be
1089  * restarted, but the whole request should not be failed.
1090  */
1091 static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
1092                                    uint64_t *host_offset, uint64_t *nb_clusters)
1093 {
1094     BDRVQcow2State *s = bs->opaque;
1095 
1096     trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
1097                                          *host_offset, *nb_clusters);
1098 
1099     /* Allocate new clusters */
1100     trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1101     if (*host_offset == 0) {
1102         int64_t cluster_offset =
1103             qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1104         if (cluster_offset < 0) {
1105             return cluster_offset;
1106         }
1107         *host_offset = cluster_offset;
1108         return 0;
1109     } else {
1110         int64_t ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
1111         if (ret < 0) {
1112             return ret;
1113         }
1114         *nb_clusters = ret;
1115         return 0;
1116     }
1117 }
1118 
1119 /*
1120  * Allocates new clusters for an area that either is yet unallocated or needs a
1121  * copy on write. If *host_offset is non-zero, clusters are only allocated if
1122  * the new allocation can match the specified host offset.
1123  *
1124  * Note that guest_offset may not be cluster aligned. In this case, the
1125  * returned *host_offset points to exact byte referenced by guest_offset and
1126  * therefore isn't cluster aligned as well.
1127  *
1128  * Returns:
1129  *   0:     if no clusters could be allocated. *bytes is set to 0,
1130  *          *host_offset is left unchanged.
1131  *
1132  *   1:     if new clusters were allocated. *bytes may be decreased if the
1133  *          new allocation doesn't cover all of the requested area.
1134  *          *host_offset is updated to contain the host offset of the first
1135  *          newly allocated cluster.
1136  *
1137  *  -errno: in error cases
1138  */
1139 static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
1140     uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1141 {
1142     BDRVQcow2State *s = bs->opaque;
1143     int l2_index;
1144     uint64_t *l2_table;
1145     uint64_t entry;
1146     uint64_t nb_clusters;
1147     int ret;
1148     bool keep_old_clusters = false;
1149 
1150     uint64_t alloc_cluster_offset = 0;
1151 
1152     trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1153                              *bytes);
1154     assert(*bytes > 0);
1155 
1156     /*
1157      * Calculate the number of clusters to look for. We stop at L2 table
1158      * boundaries to keep things simple.
1159      */
1160     nb_clusters =
1161         size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1162 
1163     l2_index = offset_to_l2_index(s, guest_offset);
1164     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1165     assert(nb_clusters <= INT_MAX);
1166 
1167     /* Find L2 entry for the first involved cluster */
1168     ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1169     if (ret < 0) {
1170         return ret;
1171     }
1172 
1173     entry = be64_to_cpu(l2_table[l2_index]);
1174 
1175     /* For the moment, overwrite compressed clusters one by one */
1176     if (entry & QCOW_OFLAG_COMPRESSED) {
1177         nb_clusters = 1;
1178     } else {
1179         nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);
1180     }
1181 
1182     /* This function is only called when there were no non-COW clusters, so if
1183      * we can't find any unallocated or COW clusters either, something is
1184      * wrong with our code. */
1185     assert(nb_clusters > 0);
1186 
1187     if (qcow2_get_cluster_type(entry) == QCOW2_CLUSTER_ZERO_ALLOC &&
1188         (entry & QCOW_OFLAG_COPIED) &&
1189         (!*host_offset ||
1190          start_of_cluster(s, *host_offset) == (entry & L2E_OFFSET_MASK)))
1191     {
1192         /* Try to reuse preallocated zero clusters; contiguous normal clusters
1193          * would be fine, too, but count_cow_clusters() above has limited
1194          * nb_clusters already to a range of COW clusters */
1195         int preallocated_nb_clusters =
1196             count_contiguous_clusters(nb_clusters, s->cluster_size,
1197                                       &l2_table[l2_index], QCOW_OFLAG_COPIED);
1198         assert(preallocated_nb_clusters > 0);
1199 
1200         nb_clusters = preallocated_nb_clusters;
1201         alloc_cluster_offset = entry & L2E_OFFSET_MASK;
1202 
1203         /* We want to reuse these clusters, so qcow2_alloc_cluster_link_l2()
1204          * should not free them. */
1205         keep_old_clusters = true;
1206     }
1207 
1208     qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1209 
1210     if (!alloc_cluster_offset) {
1211         /* Allocate, if necessary at a given offset in the image file */
1212         alloc_cluster_offset = start_of_cluster(s, *host_offset);
1213         ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1214                                       &nb_clusters);
1215         if (ret < 0) {
1216             goto fail;
1217         }
1218 
1219         /* Can't extend contiguous allocation */
1220         if (nb_clusters == 0) {
1221             *bytes = 0;
1222             return 0;
1223         }
1224 
1225         /* !*host_offset would overwrite the image header and is reserved for
1226          * "no host offset preferred". If 0 was a valid host offset, it'd
1227          * trigger the following overlap check; do that now to avoid having an
1228          * invalid value in *host_offset. */
1229         if (!alloc_cluster_offset) {
1230             ret = qcow2_pre_write_overlap_check(bs, 0, alloc_cluster_offset,
1231                                                 nb_clusters * s->cluster_size);
1232             assert(ret < 0);
1233             goto fail;
1234         }
1235     }
1236 
1237     /*
1238      * Save info needed for meta data update.
1239      *
1240      * requested_bytes: Number of bytes from the start of the first
1241      * newly allocated cluster to the end of the (possibly shortened
1242      * before) write request.
1243      *
1244      * avail_bytes: Number of bytes from the start of the first
1245      * newly allocated to the end of the last newly allocated cluster.
1246      *
1247      * nb_bytes: The number of bytes from the start of the first
1248      * newly allocated cluster to the end of the area that the write
1249      * request actually writes to (excluding COW at the end)
1250      */
1251     uint64_t requested_bytes = *bytes + offset_into_cluster(s, guest_offset);
1252     int avail_bytes = MIN(INT_MAX, nb_clusters << s->cluster_bits);
1253     int nb_bytes = MIN(requested_bytes, avail_bytes);
1254     QCowL2Meta *old_m = *m;
1255 
1256     *m = g_malloc0(sizeof(**m));
1257 
1258     **m = (QCowL2Meta) {
1259         .next           = old_m,
1260 
1261         .alloc_offset   = alloc_cluster_offset,
1262         .offset         = start_of_cluster(s, guest_offset),
1263         .nb_clusters    = nb_clusters,
1264 
1265         .keep_old_clusters  = keep_old_clusters,
1266 
1267         .cow_start = {
1268             .offset     = 0,
1269             .nb_bytes   = offset_into_cluster(s, guest_offset),
1270         },
1271         .cow_end = {
1272             .offset     = nb_bytes,
1273             .nb_bytes   = avail_bytes - nb_bytes,
1274         },
1275     };
1276     qemu_co_queue_init(&(*m)->dependent_requests);
1277     QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1278 
1279     *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
1280     *bytes = MIN(*bytes, nb_bytes - offset_into_cluster(s, guest_offset));
1281     assert(*bytes != 0);
1282 
1283     return 1;
1284 
1285 fail:
1286     if (*m && (*m)->nb_clusters > 0) {
1287         QLIST_REMOVE(*m, next_in_flight);
1288     }
1289     return ret;
1290 }
1291 
1292 /*
1293  * alloc_cluster_offset
1294  *
1295  * For a given offset on the virtual disk, find the cluster offset in qcow2
1296  * file. If the offset is not found, allocate a new cluster.
1297  *
1298  * If the cluster was already allocated, m->nb_clusters is set to 0 and
1299  * other fields in m are meaningless.
1300  *
1301  * If the cluster is newly allocated, m->nb_clusters is set to the number of
1302  * contiguous clusters that have been allocated. In this case, the other
1303  * fields of m are valid and contain information about the first allocated
1304  * cluster.
1305  *
1306  * If the request conflicts with another write request in flight, the coroutine
1307  * is queued and will be reentered when the dependency has completed.
1308  *
1309  * Return 0 on success and -errno in error cases
1310  */
1311 int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
1312                                unsigned int *bytes, uint64_t *host_offset,
1313                                QCowL2Meta **m)
1314 {
1315     BDRVQcow2State *s = bs->opaque;
1316     uint64_t start, remaining;
1317     uint64_t cluster_offset;
1318     uint64_t cur_bytes;
1319     int ret;
1320 
1321     trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *bytes);
1322 
1323 again:
1324     start = offset;
1325     remaining = *bytes;
1326     cluster_offset = 0;
1327     *host_offset = 0;
1328     cur_bytes = 0;
1329     *m = NULL;
1330 
1331     while (true) {
1332 
1333         if (!*host_offset) {
1334             *host_offset = start_of_cluster(s, cluster_offset);
1335         }
1336 
1337         assert(remaining >= cur_bytes);
1338 
1339         start           += cur_bytes;
1340         remaining       -= cur_bytes;
1341         cluster_offset  += cur_bytes;
1342 
1343         if (remaining == 0) {
1344             break;
1345         }
1346 
1347         cur_bytes = remaining;
1348 
1349         /*
1350          * Now start gathering as many contiguous clusters as possible:
1351          *
1352          * 1. Check for overlaps with in-flight allocations
1353          *
1354          *      a) Overlap not in the first cluster -> shorten this request and
1355          *         let the caller handle the rest in its next loop iteration.
1356          *
1357          *      b) Real overlaps of two requests. Yield and restart the search
1358          *         for contiguous clusters (the situation could have changed
1359          *         while we were sleeping)
1360          *
1361          *      c) TODO: Request starts in the same cluster as the in-flight
1362          *         allocation ends. Shorten the COW of the in-fight allocation,
1363          *         set cluster_offset to write to the same cluster and set up
1364          *         the right synchronisation between the in-flight request and
1365          *         the new one.
1366          */
1367         ret = handle_dependencies(bs, start, &cur_bytes, m);
1368         if (ret == -EAGAIN) {
1369             /* Currently handle_dependencies() doesn't yield if we already had
1370              * an allocation. If it did, we would have to clean up the L2Meta
1371              * structs before starting over. */
1372             assert(*m == NULL);
1373             goto again;
1374         } else if (ret < 0) {
1375             return ret;
1376         } else if (cur_bytes == 0) {
1377             break;
1378         } else {
1379             /* handle_dependencies() may have decreased cur_bytes (shortened
1380              * the allocations below) so that the next dependency is processed
1381              * correctly during the next loop iteration. */
1382         }
1383 
1384         /*
1385          * 2. Count contiguous COPIED clusters.
1386          */
1387         ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1388         if (ret < 0) {
1389             return ret;
1390         } else if (ret) {
1391             continue;
1392         } else if (cur_bytes == 0) {
1393             break;
1394         }
1395 
1396         /*
1397          * 3. If the request still hasn't completed, allocate new clusters,
1398          *    considering any cluster_offset of steps 1c or 2.
1399          */
1400         ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1401         if (ret < 0) {
1402             return ret;
1403         } else if (ret) {
1404             continue;
1405         } else {
1406             assert(cur_bytes == 0);
1407             break;
1408         }
1409     }
1410 
1411     *bytes -= remaining;
1412     assert(*bytes > 0);
1413     assert(*host_offset != 0);
1414 
1415     return 0;
1416 }
1417 
1418 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1419                              const uint8_t *buf, int buf_size)
1420 {
1421     z_stream strm1, *strm = &strm1;
1422     int ret, out_len;
1423 
1424     memset(strm, 0, sizeof(*strm));
1425 
1426     strm->next_in = (uint8_t *)buf;
1427     strm->avail_in = buf_size;
1428     strm->next_out = out_buf;
1429     strm->avail_out = out_buf_size;
1430 
1431     ret = inflateInit2(strm, -12);
1432     if (ret != Z_OK)
1433         return -1;
1434     ret = inflate(strm, Z_FINISH);
1435     out_len = strm->next_out - out_buf;
1436     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1437         out_len != out_buf_size) {
1438         inflateEnd(strm);
1439         return -1;
1440     }
1441     inflateEnd(strm);
1442     return 0;
1443 }
1444 
1445 int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
1446 {
1447     BDRVQcow2State *s = bs->opaque;
1448     int ret, csize, nb_csectors, sector_offset;
1449     uint64_t coffset;
1450 
1451     coffset = cluster_offset & s->cluster_offset_mask;
1452     if (s->cluster_cache_offset != coffset) {
1453         nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1454         sector_offset = coffset & 511;
1455         csize = nb_csectors * 512 - sector_offset;
1456         BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
1457         ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data,
1458                         nb_csectors);
1459         if (ret < 0) {
1460             return ret;
1461         }
1462         if (decompress_buffer(s->cluster_cache, s->cluster_size,
1463                               s->cluster_data + sector_offset, csize) < 0) {
1464             return -EIO;
1465         }
1466         s->cluster_cache_offset = coffset;
1467     }
1468     return 0;
1469 }
1470 
1471 /*
1472  * This discards as many clusters of nb_clusters as possible at once (i.e.
1473  * all clusters in the same L2 table) and returns the number of discarded
1474  * clusters.
1475  */
1476 static int discard_single_l2(BlockDriverState *bs, uint64_t offset,
1477                              uint64_t nb_clusters, enum qcow2_discard_type type,
1478                              bool full_discard)
1479 {
1480     BDRVQcow2State *s = bs->opaque;
1481     uint64_t *l2_table;
1482     int l2_index;
1483     int ret;
1484     int i;
1485 
1486     ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1487     if (ret < 0) {
1488         return ret;
1489     }
1490 
1491     /* Limit nb_clusters to one L2 table */
1492     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1493     assert(nb_clusters <= INT_MAX);
1494 
1495     for (i = 0; i < nb_clusters; i++) {
1496         uint64_t old_l2_entry;
1497 
1498         old_l2_entry = be64_to_cpu(l2_table[l2_index + i]);
1499 
1500         /*
1501          * If full_discard is false, make sure that a discarded area reads back
1502          * as zeroes for v3 images (we cannot do it for v2 without actually
1503          * writing a zero-filled buffer). We can skip the operation if the
1504          * cluster is already marked as zero, or if it's unallocated and we
1505          * don't have a backing file.
1506          *
1507          * TODO We might want to use bdrv_get_block_status(bs) here, but we're
1508          * holding s->lock, so that doesn't work today.
1509          *
1510          * If full_discard is true, the sector should not read back as zeroes,
1511          * but rather fall through to the backing file.
1512          */
1513         switch (qcow2_get_cluster_type(old_l2_entry)) {
1514         case QCOW2_CLUSTER_UNALLOCATED:
1515             if (full_discard || !bs->backing) {
1516                 continue;
1517             }
1518             break;
1519 
1520         case QCOW2_CLUSTER_ZERO_PLAIN:
1521             if (!full_discard) {
1522                 continue;
1523             }
1524             break;
1525 
1526         case QCOW2_CLUSTER_ZERO_ALLOC:
1527         case QCOW2_CLUSTER_NORMAL:
1528         case QCOW2_CLUSTER_COMPRESSED:
1529             break;
1530 
1531         default:
1532             abort();
1533         }
1534 
1535         /* First remove L2 entries */
1536         qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
1537         if (!full_discard && s->qcow_version >= 3) {
1538             l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1539         } else {
1540             l2_table[l2_index + i] = cpu_to_be64(0);
1541         }
1542 
1543         /* Then decrease the refcount */
1544         qcow2_free_any_clusters(bs, old_l2_entry, 1, type);
1545     }
1546 
1547     qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1548 
1549     return nb_clusters;
1550 }
1551 
1552 int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
1553                           uint64_t bytes, enum qcow2_discard_type type,
1554                           bool full_discard)
1555 {
1556     BDRVQcow2State *s = bs->opaque;
1557     uint64_t end_offset = offset + bytes;
1558     uint64_t nb_clusters;
1559     int64_t cleared;
1560     int ret;
1561 
1562     /* Caller must pass aligned values, except at image end */
1563     assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1564     assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1565            end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1566 
1567     nb_clusters = size_to_clusters(s, bytes);
1568 
1569     s->cache_discards = true;
1570 
1571     /* Each L2 table is handled by its own loop iteration */
1572     while (nb_clusters > 0) {
1573         cleared = discard_single_l2(bs, offset, nb_clusters, type,
1574                                     full_discard);
1575         if (cleared < 0) {
1576             ret = cleared;
1577             goto fail;
1578         }
1579 
1580         nb_clusters -= cleared;
1581         offset += (cleared * s->cluster_size);
1582     }
1583 
1584     ret = 0;
1585 fail:
1586     s->cache_discards = false;
1587     qcow2_process_discards(bs, ret);
1588 
1589     return ret;
1590 }
1591 
1592 /*
1593  * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1594  * all clusters in the same L2 table) and returns the number of zeroed
1595  * clusters.
1596  */
1597 static int zero_single_l2(BlockDriverState *bs, uint64_t offset,
1598                           uint64_t nb_clusters, int flags)
1599 {
1600     BDRVQcow2State *s = bs->opaque;
1601     uint64_t *l2_table;
1602     int l2_index;
1603     int ret;
1604     int i;
1605     bool unmap = !!(flags & BDRV_REQ_MAY_UNMAP);
1606 
1607     ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1608     if (ret < 0) {
1609         return ret;
1610     }
1611 
1612     /* Limit nb_clusters to one L2 table */
1613     nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1614     assert(nb_clusters <= INT_MAX);
1615 
1616     for (i = 0; i < nb_clusters; i++) {
1617         uint64_t old_offset;
1618         QCow2ClusterType cluster_type;
1619 
1620         old_offset = be64_to_cpu(l2_table[l2_index + i]);
1621 
1622         /*
1623          * Minimize L2 changes if the cluster already reads back as
1624          * zeroes with correct allocation.
1625          */
1626         cluster_type = qcow2_get_cluster_type(old_offset);
1627         if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN ||
1628             (cluster_type == QCOW2_CLUSTER_ZERO_ALLOC && !unmap)) {
1629             continue;
1630         }
1631 
1632         qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
1633         if (cluster_type == QCOW2_CLUSTER_COMPRESSED || unmap) {
1634             l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1635             qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
1636         } else {
1637             l2_table[l2_index + i] |= cpu_to_be64(QCOW_OFLAG_ZERO);
1638         }
1639     }
1640 
1641     qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1642 
1643     return nb_clusters;
1644 }
1645 
1646 int qcow2_cluster_zeroize(BlockDriverState *bs, uint64_t offset,
1647                           uint64_t bytes, int flags)
1648 {
1649     BDRVQcow2State *s = bs->opaque;
1650     uint64_t end_offset = offset + bytes;
1651     uint64_t nb_clusters;
1652     int64_t cleared;
1653     int ret;
1654 
1655     /* Caller must pass aligned values, except at image end */
1656     assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1657     assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1658            end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1659 
1660     /* The zero flag is only supported by version 3 and newer */
1661     if (s->qcow_version < 3) {
1662         return -ENOTSUP;
1663     }
1664 
1665     /* Each L2 table is handled by its own loop iteration */
1666     nb_clusters = size_to_clusters(s, bytes);
1667 
1668     s->cache_discards = true;
1669 
1670     while (nb_clusters > 0) {
1671         cleared = zero_single_l2(bs, offset, nb_clusters, flags);
1672         if (cleared < 0) {
1673             ret = cleared;
1674             goto fail;
1675         }
1676 
1677         nb_clusters -= cleared;
1678         offset += (cleared * s->cluster_size);
1679     }
1680 
1681     ret = 0;
1682 fail:
1683     s->cache_discards = false;
1684     qcow2_process_discards(bs, ret);
1685 
1686     return ret;
1687 }
1688 
1689 /*
1690  * Expands all zero clusters in a specific L1 table (or deallocates them, for
1691  * non-backed non-pre-allocated zero clusters).
1692  *
1693  * l1_entries and *visited_l1_entries are used to keep track of progress for
1694  * status_cb(). l1_entries contains the total number of L1 entries and
1695  * *visited_l1_entries counts all visited L1 entries.
1696  */
1697 static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
1698                                       int l1_size, int64_t *visited_l1_entries,
1699                                       int64_t l1_entries,
1700                                       BlockDriverAmendStatusCB *status_cb,
1701                                       void *cb_opaque)
1702 {
1703     BDRVQcow2State *s = bs->opaque;
1704     bool is_active_l1 = (l1_table == s->l1_table);
1705     uint64_t *l2_table = NULL;
1706     int ret;
1707     int i, j;
1708 
1709     if (!is_active_l1) {
1710         /* inactive L2 tables require a buffer to be stored in when loading
1711          * them from disk */
1712         l2_table = qemu_try_blockalign(bs->file->bs, s->cluster_size);
1713         if (l2_table == NULL) {
1714             return -ENOMEM;
1715         }
1716     }
1717 
1718     for (i = 0; i < l1_size; i++) {
1719         uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1720         bool l2_dirty = false;
1721         uint64_t l2_refcount;
1722 
1723         if (!l2_offset) {
1724             /* unallocated */
1725             (*visited_l1_entries)++;
1726             if (status_cb) {
1727                 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
1728             }
1729             continue;
1730         }
1731 
1732         if (offset_into_cluster(s, l2_offset)) {
1733             qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
1734                                     PRIx64 " unaligned (L1 index: %#x)",
1735                                     l2_offset, i);
1736             ret = -EIO;
1737             goto fail;
1738         }
1739 
1740         if (is_active_l1) {
1741             /* get active L2 tables from cache */
1742             ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1743                     (void **)&l2_table);
1744         } else {
1745             /* load inactive L2 tables from disk */
1746             ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1747                             (void *)l2_table, s->cluster_sectors);
1748         }
1749         if (ret < 0) {
1750             goto fail;
1751         }
1752 
1753         ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1754                                  &l2_refcount);
1755         if (ret < 0) {
1756             goto fail;
1757         }
1758 
1759         for (j = 0; j < s->l2_size; j++) {
1760             uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1761             int64_t offset = l2_entry & L2E_OFFSET_MASK;
1762             QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
1763 
1764             if (cluster_type != QCOW2_CLUSTER_ZERO_PLAIN &&
1765                 cluster_type != QCOW2_CLUSTER_ZERO_ALLOC) {
1766                 continue;
1767             }
1768 
1769             if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1770                 if (!bs->backing) {
1771                     /* not backed; therefore we can simply deallocate the
1772                      * cluster */
1773                     l2_table[j] = 0;
1774                     l2_dirty = true;
1775                     continue;
1776                 }
1777 
1778                 offset = qcow2_alloc_clusters(bs, s->cluster_size);
1779                 if (offset < 0) {
1780                     ret = offset;
1781                     goto fail;
1782                 }
1783 
1784                 if (l2_refcount > 1) {
1785                     /* For shared L2 tables, set the refcount accordingly (it is
1786                      * already 1 and needs to be l2_refcount) */
1787                     ret = qcow2_update_cluster_refcount(bs,
1788                             offset >> s->cluster_bits,
1789                             refcount_diff(1, l2_refcount), false,
1790                             QCOW2_DISCARD_OTHER);
1791                     if (ret < 0) {
1792                         qcow2_free_clusters(bs, offset, s->cluster_size,
1793                                             QCOW2_DISCARD_OTHER);
1794                         goto fail;
1795                     }
1796                 }
1797             }
1798 
1799             if (offset_into_cluster(s, offset)) {
1800                 qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "
1801                                         "%#" PRIx64 " unaligned (L2 offset: %#"
1802                                         PRIx64 ", L2 index: %#x)", offset,
1803                                         l2_offset, j);
1804                 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1805                     qcow2_free_clusters(bs, offset, s->cluster_size,
1806                                         QCOW2_DISCARD_ALWAYS);
1807                 }
1808                 ret = -EIO;
1809                 goto fail;
1810             }
1811 
1812             ret = qcow2_pre_write_overlap_check(bs, 0, offset, s->cluster_size);
1813             if (ret < 0) {
1814                 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1815                     qcow2_free_clusters(bs, offset, s->cluster_size,
1816                                         QCOW2_DISCARD_ALWAYS);
1817                 }
1818                 goto fail;
1819             }
1820 
1821             ret = bdrv_pwrite_zeroes(bs->file, offset, s->cluster_size, 0);
1822             if (ret < 0) {
1823                 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1824                     qcow2_free_clusters(bs, offset, s->cluster_size,
1825                                         QCOW2_DISCARD_ALWAYS);
1826                 }
1827                 goto fail;
1828             }
1829 
1830             if (l2_refcount == 1) {
1831                 l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
1832             } else {
1833                 l2_table[j] = cpu_to_be64(offset);
1834             }
1835             l2_dirty = true;
1836         }
1837 
1838         if (is_active_l1) {
1839             if (l2_dirty) {
1840                 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
1841                 qcow2_cache_depends_on_flush(s->l2_table_cache);
1842             }
1843             qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1844         } else {
1845             if (l2_dirty) {
1846                 ret = qcow2_pre_write_overlap_check(bs,
1847                         QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2, l2_offset,
1848                         s->cluster_size);
1849                 if (ret < 0) {
1850                     goto fail;
1851                 }
1852 
1853                 ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1854                                  (void *)l2_table, s->cluster_sectors);
1855                 if (ret < 0) {
1856                     goto fail;
1857                 }
1858             }
1859         }
1860 
1861         (*visited_l1_entries)++;
1862         if (status_cb) {
1863             status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
1864         }
1865     }
1866 
1867     ret = 0;
1868 
1869 fail:
1870     if (l2_table) {
1871         if (!is_active_l1) {
1872             qemu_vfree(l2_table);
1873         } else {
1874             qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1875         }
1876     }
1877     return ret;
1878 }
1879 
1880 /*
1881  * For backed images, expands all zero clusters on the image. For non-backed
1882  * images, deallocates all non-pre-allocated zero clusters (and claims the
1883  * allocation for pre-allocated ones). This is important for downgrading to a
1884  * qcow2 version which doesn't yet support metadata zero clusters.
1885  */
1886 int qcow2_expand_zero_clusters(BlockDriverState *bs,
1887                                BlockDriverAmendStatusCB *status_cb,
1888                                void *cb_opaque)
1889 {
1890     BDRVQcow2State *s = bs->opaque;
1891     uint64_t *l1_table = NULL;
1892     int64_t l1_entries = 0, visited_l1_entries = 0;
1893     int ret;
1894     int i, j;
1895 
1896     if (status_cb) {
1897         l1_entries = s->l1_size;
1898         for (i = 0; i < s->nb_snapshots; i++) {
1899             l1_entries += s->snapshots[i].l1_size;
1900         }
1901     }
1902 
1903     ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
1904                                      &visited_l1_entries, l1_entries,
1905                                      status_cb, cb_opaque);
1906     if (ret < 0) {
1907         goto fail;
1908     }
1909 
1910     /* Inactive L1 tables may point to active L2 tables - therefore it is
1911      * necessary to flush the L2 table cache before trying to access the L2
1912      * tables pointed to by inactive L1 entries (else we might try to expand
1913      * zero clusters that have already been expanded); furthermore, it is also
1914      * necessary to empty the L2 table cache, since it may contain tables which
1915      * are now going to be modified directly on disk, bypassing the cache.
1916      * qcow2_cache_empty() does both for us. */
1917     ret = qcow2_cache_empty(bs, s->l2_table_cache);
1918     if (ret < 0) {
1919         goto fail;
1920     }
1921 
1922     for (i = 0; i < s->nb_snapshots; i++) {
1923         int l1_sectors = DIV_ROUND_UP(s->snapshots[i].l1_size *
1924                                       sizeof(uint64_t), BDRV_SECTOR_SIZE);
1925 
1926         l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);
1927 
1928         ret = bdrv_read(bs->file,
1929                         s->snapshots[i].l1_table_offset / BDRV_SECTOR_SIZE,
1930                         (void *)l1_table, l1_sectors);
1931         if (ret < 0) {
1932             goto fail;
1933         }
1934 
1935         for (j = 0; j < s->snapshots[i].l1_size; j++) {
1936             be64_to_cpus(&l1_table[j]);
1937         }
1938 
1939         ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
1940                                          &visited_l1_entries, l1_entries,
1941                                          status_cb, cb_opaque);
1942         if (ret < 0) {
1943             goto fail;
1944         }
1945     }
1946 
1947     ret = 0;
1948 
1949 fail:
1950     g_free(l1_table);
1951     return ret;
1952 }
1953