xref: /openbmc/qemu/block/qcow2-bitmap.c (revision 0fd61a2d)
1 /*
2  * Bitmaps for the QCOW version 2 format
3  *
4  * Copyright (c) 2014-2017 Vladimir Sementsov-Ogievskiy
5  *
6  * This file is derived from qcow2-snapshot.c, original copyright:
7  * Copyright (c) 2004-2006 Fabrice Bellard
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include "qemu/osdep.h"
29 #include "qapi/error.h"
30 #include "qemu/cutils.h"
31 
32 #include "qcow2.h"
33 
34 /* NOTICE: BME here means Bitmaps Extension and used as a namespace for
35  * _internal_ constants. Please do not use this _internal_ abbreviation for
36  * other needs and/or outside of this file. */
37 
38 /* Bitmap directory entry constraints */
39 #define BME_MAX_TABLE_SIZE 0x8000000
40 #define BME_MAX_PHYS_SIZE 0x20000000 /* restrict BdrvDirtyBitmap size in RAM */
41 #define BME_MAX_GRANULARITY_BITS 31
42 #define BME_MIN_GRANULARITY_BITS 9
43 #define BME_MAX_NAME_SIZE 1023
44 
45 #if BME_MAX_TABLE_SIZE * 8ULL > INT_MAX
46 #error In the code bitmap table physical size assumed to fit into int
47 #endif
48 
49 /* Bitmap directory entry flags */
50 #define BME_RESERVED_FLAGS 0xfffffffcU
51 #define BME_FLAG_IN_USE (1U << 0)
52 #define BME_FLAG_AUTO   (1U << 1)
53 
54 /* bits [1, 8] U [56, 63] are reserved */
55 #define BME_TABLE_ENTRY_RESERVED_MASK 0xff000000000001feULL
56 #define BME_TABLE_ENTRY_OFFSET_MASK 0x00fffffffffffe00ULL
57 #define BME_TABLE_ENTRY_FLAG_ALL_ONES (1ULL << 0)
58 
59 typedef struct QEMU_PACKED Qcow2BitmapDirEntry {
60     /* header is 8 byte aligned */
61     uint64_t bitmap_table_offset;
62 
63     uint32_t bitmap_table_size;
64     uint32_t flags;
65 
66     uint8_t type;
67     uint8_t granularity_bits;
68     uint16_t name_size;
69     uint32_t extra_data_size;
70     /* extra data follows  */
71     /* name follows  */
72 } Qcow2BitmapDirEntry;
73 
74 typedef struct Qcow2BitmapTable {
75     uint64_t offset;
76     uint32_t size; /* number of 64bit entries */
77     QSIMPLEQ_ENTRY(Qcow2BitmapTable) entry;
78 } Qcow2BitmapTable;
79 
80 typedef struct Qcow2Bitmap {
81     Qcow2BitmapTable table;
82     uint32_t flags;
83     uint8_t granularity_bits;
84     char *name;
85 
86     BdrvDirtyBitmap *dirty_bitmap;
87 
88     QSIMPLEQ_ENTRY(Qcow2Bitmap) entry;
89 } Qcow2Bitmap;
90 typedef QSIMPLEQ_HEAD(Qcow2BitmapList, Qcow2Bitmap) Qcow2BitmapList;
91 
92 typedef enum BitmapType {
93     BT_DIRTY_TRACKING_BITMAP = 1
94 } BitmapType;
95 
96 static inline bool can_write(BlockDriverState *bs)
97 {
98     return !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
99 }
100 
101 static int update_header_sync(BlockDriverState *bs)
102 {
103     int ret;
104 
105     ret = qcow2_update_header(bs);
106     if (ret < 0) {
107         return ret;
108     }
109 
110     return bdrv_flush(bs->file->bs);
111 }
112 
113 static inline void bitmap_table_to_be(uint64_t *bitmap_table, size_t size)
114 {
115     size_t i;
116 
117     for (i = 0; i < size; ++i) {
118         bitmap_table[i] = cpu_to_be64(bitmap_table[i]);
119     }
120 }
121 
122 static int check_table_entry(uint64_t entry, int cluster_size)
123 {
124     uint64_t offset;
125 
126     if (entry & BME_TABLE_ENTRY_RESERVED_MASK) {
127         return -EINVAL;
128     }
129 
130     offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
131     if (offset != 0) {
132         /* if offset specified, bit 0 is reserved */
133         if (entry & BME_TABLE_ENTRY_FLAG_ALL_ONES) {
134             return -EINVAL;
135         }
136 
137         if (offset % cluster_size != 0) {
138             return -EINVAL;
139         }
140     }
141 
142     return 0;
143 }
144 
145 static int check_constraints_on_bitmap(BlockDriverState *bs,
146                                        const char *name,
147                                        uint32_t granularity,
148                                        Error **errp)
149 {
150     BDRVQcow2State *s = bs->opaque;
151     int granularity_bits = ctz32(granularity);
152     int64_t len = bdrv_getlength(bs);
153 
154     assert(granularity > 0);
155     assert((granularity & (granularity - 1)) == 0);
156 
157     if (len < 0) {
158         error_setg_errno(errp, -len, "Failed to get size of '%s'",
159                          bdrv_get_device_or_node_name(bs));
160         return len;
161     }
162 
163     if (granularity_bits > BME_MAX_GRANULARITY_BITS) {
164         error_setg(errp, "Granularity exceeds maximum (%llu bytes)",
165                    1ULL << BME_MAX_GRANULARITY_BITS);
166         return -EINVAL;
167     }
168     if (granularity_bits < BME_MIN_GRANULARITY_BITS) {
169         error_setg(errp, "Granularity is under minimum (%llu bytes)",
170                    1ULL << BME_MIN_GRANULARITY_BITS);
171         return -EINVAL;
172     }
173 
174     if ((len > (uint64_t)BME_MAX_PHYS_SIZE << granularity_bits) ||
175         (len > (uint64_t)BME_MAX_TABLE_SIZE * s->cluster_size <<
176                granularity_bits))
177     {
178         error_setg(errp, "Too much space will be occupied by the bitmap. "
179                    "Use larger granularity");
180         return -EINVAL;
181     }
182 
183     if (strlen(name) > BME_MAX_NAME_SIZE) {
184         error_setg(errp, "Name length exceeds maximum (%u characters)",
185                    BME_MAX_NAME_SIZE);
186         return -EINVAL;
187     }
188 
189     return 0;
190 }
191 
192 static void clear_bitmap_table(BlockDriverState *bs, uint64_t *bitmap_table,
193                                uint32_t bitmap_table_size)
194 {
195     BDRVQcow2State *s = bs->opaque;
196     int i;
197 
198     for (i = 0; i < bitmap_table_size; ++i) {
199         uint64_t addr = bitmap_table[i] & BME_TABLE_ENTRY_OFFSET_MASK;
200         if (!addr) {
201             continue;
202         }
203 
204         qcow2_free_clusters(bs, addr, s->cluster_size, QCOW2_DISCARD_ALWAYS);
205         bitmap_table[i] = 0;
206     }
207 }
208 
209 static int bitmap_table_load(BlockDriverState *bs, Qcow2BitmapTable *tb,
210                              uint64_t **bitmap_table)
211 {
212     int ret;
213     BDRVQcow2State *s = bs->opaque;
214     uint32_t i;
215     uint64_t *table;
216 
217     assert(tb->size != 0);
218     table = g_try_new(uint64_t, tb->size);
219     if (table == NULL) {
220         return -ENOMEM;
221     }
222 
223     assert(tb->size <= BME_MAX_TABLE_SIZE);
224     ret = bdrv_pread(bs->file, tb->offset,
225                      table, tb->size * sizeof(uint64_t));
226     if (ret < 0) {
227         goto fail;
228     }
229 
230     for (i = 0; i < tb->size; ++i) {
231         table[i] = be64_to_cpu(table[i]);
232         ret = check_table_entry(table[i], s->cluster_size);
233         if (ret < 0) {
234             goto fail;
235         }
236     }
237 
238     *bitmap_table = table;
239     return 0;
240 
241 fail:
242     g_free(table);
243 
244     return ret;
245 }
246 
247 static int free_bitmap_clusters(BlockDriverState *bs, Qcow2BitmapTable *tb)
248 {
249     int ret;
250     uint64_t *bitmap_table;
251 
252     ret = bitmap_table_load(bs, tb, &bitmap_table);
253     if (ret < 0) {
254         return ret;
255     }
256 
257     clear_bitmap_table(bs, bitmap_table, tb->size);
258     qcow2_free_clusters(bs, tb->offset, tb->size * sizeof(uint64_t),
259                         QCOW2_DISCARD_OTHER);
260     g_free(bitmap_table);
261 
262     tb->offset = 0;
263     tb->size = 0;
264 
265     return 0;
266 }
267 
268 /* Return the disk size covered by a single qcow2 cluster of bitmap data. */
269 static uint64_t bytes_covered_by_bitmap_cluster(const BDRVQcow2State *s,
270                                                 const BdrvDirtyBitmap *bitmap)
271 {
272     uint64_t granularity = bdrv_dirty_bitmap_granularity(bitmap);
273     uint64_t limit = granularity * (s->cluster_size << 3);
274 
275     assert(QEMU_IS_ALIGNED(limit,
276                            bdrv_dirty_bitmap_serialization_align(bitmap)));
277     return limit;
278 }
279 
280 /* load_bitmap_data
281  * @bitmap_table entries must satisfy specification constraints.
282  * @bitmap must be cleared */
283 static int load_bitmap_data(BlockDriverState *bs,
284                             const uint64_t *bitmap_table,
285                             uint32_t bitmap_table_size,
286                             BdrvDirtyBitmap *bitmap)
287 {
288     int ret = 0;
289     BDRVQcow2State *s = bs->opaque;
290     uint64_t offset, limit;
291     uint64_t bm_size = bdrv_dirty_bitmap_size(bitmap);
292     uint8_t *buf = NULL;
293     uint64_t i, tab_size =
294             size_to_clusters(s,
295                 bdrv_dirty_bitmap_serialization_size(bitmap, 0, bm_size));
296 
297     if (tab_size != bitmap_table_size || tab_size > BME_MAX_TABLE_SIZE) {
298         return -EINVAL;
299     }
300 
301     buf = g_malloc(s->cluster_size);
302     limit = bytes_covered_by_bitmap_cluster(s, bitmap);
303     for (i = 0, offset = 0; i < tab_size; ++i, offset += limit) {
304         uint64_t count = MIN(bm_size - offset, limit);
305         uint64_t entry = bitmap_table[i];
306         uint64_t data_offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
307 
308         assert(check_table_entry(entry, s->cluster_size) == 0);
309 
310         if (data_offset == 0) {
311             if (entry & BME_TABLE_ENTRY_FLAG_ALL_ONES) {
312                 bdrv_dirty_bitmap_deserialize_ones(bitmap, offset, count,
313                                                    false);
314             } else {
315                 /* No need to deserialize zeros because the dirty bitmap is
316                  * already cleared */
317             }
318         } else {
319             ret = bdrv_pread(bs->file, data_offset, buf, s->cluster_size);
320             if (ret < 0) {
321                 goto finish;
322             }
323             bdrv_dirty_bitmap_deserialize_part(bitmap, buf, offset, count,
324                                                false);
325         }
326     }
327     ret = 0;
328 
329     bdrv_dirty_bitmap_deserialize_finish(bitmap);
330 
331 finish:
332     g_free(buf);
333 
334     return ret;
335 }
336 
337 static BdrvDirtyBitmap *load_bitmap(BlockDriverState *bs,
338                                     Qcow2Bitmap *bm, Error **errp)
339 {
340     int ret;
341     uint64_t *bitmap_table = NULL;
342     uint32_t granularity;
343     BdrvDirtyBitmap *bitmap = NULL;
344 
345     granularity = 1U << bm->granularity_bits;
346     bitmap = bdrv_create_dirty_bitmap(bs, granularity, bm->name, errp);
347     if (bitmap == NULL) {
348         goto fail;
349     }
350 
351     if (bm->flags & BME_FLAG_IN_USE) {
352         /* Data is unusable, skip loading it */
353         return bitmap;
354     }
355 
356     ret = bitmap_table_load(bs, &bm->table, &bitmap_table);
357     if (ret < 0) {
358         error_setg_errno(errp, -ret,
359                          "Could not read bitmap_table table from image for "
360                          "bitmap '%s'", bm->name);
361         goto fail;
362     }
363 
364     ret = load_bitmap_data(bs, bitmap_table, bm->table.size, bitmap);
365     if (ret < 0) {
366         error_setg_errno(errp, -ret, "Could not read bitmap '%s' from image",
367                          bm->name);
368         goto fail;
369     }
370 
371     g_free(bitmap_table);
372     return bitmap;
373 
374 fail:
375     g_free(bitmap_table);
376     if (bitmap != NULL) {
377         bdrv_release_dirty_bitmap(bitmap);
378     }
379 
380     return NULL;
381 }
382 
383 /*
384  * Bitmap List
385  */
386 
387 /*
388  * Bitmap List private functions
389  * Only Bitmap List knows about bitmap directory structure in Qcow2.
390  */
391 
392 static inline void bitmap_dir_entry_to_cpu(Qcow2BitmapDirEntry *entry)
393 {
394     entry->bitmap_table_offset = be64_to_cpu(entry->bitmap_table_offset);
395     entry->bitmap_table_size = be32_to_cpu(entry->bitmap_table_size);
396     entry->flags = be32_to_cpu(entry->flags);
397     entry->name_size = be16_to_cpu(entry->name_size);
398     entry->extra_data_size = be32_to_cpu(entry->extra_data_size);
399 }
400 
401 static inline void bitmap_dir_entry_to_be(Qcow2BitmapDirEntry *entry)
402 {
403     entry->bitmap_table_offset = cpu_to_be64(entry->bitmap_table_offset);
404     entry->bitmap_table_size = cpu_to_be32(entry->bitmap_table_size);
405     entry->flags = cpu_to_be32(entry->flags);
406     entry->name_size = cpu_to_be16(entry->name_size);
407     entry->extra_data_size = cpu_to_be32(entry->extra_data_size);
408 }
409 
410 static inline int calc_dir_entry_size(size_t name_size, size_t extra_data_size)
411 {
412     int size = sizeof(Qcow2BitmapDirEntry) + name_size + extra_data_size;
413     return ROUND_UP(size, 8);
414 }
415 
416 static inline int dir_entry_size(Qcow2BitmapDirEntry *entry)
417 {
418     return calc_dir_entry_size(entry->name_size, entry->extra_data_size);
419 }
420 
421 static inline const char *dir_entry_name_field(Qcow2BitmapDirEntry *entry)
422 {
423     return (const char *)(entry + 1) + entry->extra_data_size;
424 }
425 
426 static inline char *dir_entry_copy_name(Qcow2BitmapDirEntry *entry)
427 {
428     const char *name_field = dir_entry_name_field(entry);
429     return g_strndup(name_field, entry->name_size);
430 }
431 
432 static inline Qcow2BitmapDirEntry *next_dir_entry(Qcow2BitmapDirEntry *entry)
433 {
434     return (Qcow2BitmapDirEntry *)((uint8_t *)entry + dir_entry_size(entry));
435 }
436 
437 static int check_dir_entry(BlockDriverState *bs, Qcow2BitmapDirEntry *entry)
438 {
439     BDRVQcow2State *s = bs->opaque;
440     uint64_t phys_bitmap_bytes;
441     int64_t len;
442 
443     bool fail = (entry->bitmap_table_size == 0) ||
444                 (entry->bitmap_table_offset == 0) ||
445                 (entry->bitmap_table_offset % s->cluster_size) ||
446                 (entry->bitmap_table_size > BME_MAX_TABLE_SIZE) ||
447                 (entry->granularity_bits > BME_MAX_GRANULARITY_BITS) ||
448                 (entry->granularity_bits < BME_MIN_GRANULARITY_BITS) ||
449                 (entry->flags & BME_RESERVED_FLAGS) ||
450                 (entry->name_size > BME_MAX_NAME_SIZE) ||
451                 (entry->type != BT_DIRTY_TRACKING_BITMAP);
452 
453     if (fail) {
454         return -EINVAL;
455     }
456 
457     phys_bitmap_bytes = (uint64_t)entry->bitmap_table_size * s->cluster_size;
458     len = bdrv_getlength(bs);
459 
460     if (len < 0) {
461         return len;
462     }
463 
464     if (phys_bitmap_bytes > BME_MAX_PHYS_SIZE) {
465         return -EINVAL;
466     }
467 
468     if (!(entry->flags & BME_FLAG_IN_USE) &&
469         (len > ((phys_bitmap_bytes * 8) << entry->granularity_bits)))
470     {
471         /*
472          * We've loaded a valid bitmap (IN_USE not set) or we are going to
473          * store a valid bitmap, but the allocated bitmap table size is not
474          * enough to store this bitmap.
475          *
476          * Note, that it's OK to have an invalid bitmap with invalid size due
477          * to a bitmap that was not correctly saved after image resize.
478          */
479         return -EINVAL;
480     }
481 
482     return 0;
483 }
484 
485 static inline void bitmap_directory_to_be(uint8_t *dir, size_t size)
486 {
487     uint8_t *end = dir + size;
488     while (dir < end) {
489         Qcow2BitmapDirEntry *e = (Qcow2BitmapDirEntry *)dir;
490         dir += dir_entry_size(e);
491 
492         bitmap_dir_entry_to_be(e);
493     }
494 }
495 
496 /*
497  * Bitmap List public functions
498  */
499 
500 static void bitmap_free(Qcow2Bitmap *bm)
501 {
502     if (bm == NULL) {
503         return;
504     }
505 
506     g_free(bm->name);
507     g_free(bm);
508 }
509 
510 static void bitmap_list_free(Qcow2BitmapList *bm_list)
511 {
512     Qcow2Bitmap *bm;
513 
514     if (bm_list == NULL) {
515         return;
516     }
517 
518     while ((bm = QSIMPLEQ_FIRST(bm_list)) != NULL) {
519         QSIMPLEQ_REMOVE_HEAD(bm_list, entry);
520         bitmap_free(bm);
521     }
522 
523     g_free(bm_list);
524 }
525 
526 static Qcow2BitmapList *bitmap_list_new(void)
527 {
528     Qcow2BitmapList *bm_list = g_new(Qcow2BitmapList, 1);
529     QSIMPLEQ_INIT(bm_list);
530 
531     return bm_list;
532 }
533 
534 static uint32_t bitmap_list_count(Qcow2BitmapList *bm_list)
535 {
536     Qcow2Bitmap *bm;
537     uint32_t nb_bitmaps = 0;
538 
539     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
540         nb_bitmaps++;
541     }
542 
543     return nb_bitmaps;
544 }
545 
546 /* bitmap_list_load
547  * Get bitmap list from qcow2 image. Actually reads bitmap directory,
548  * checks it and convert to bitmap list.
549  */
550 static Qcow2BitmapList *bitmap_list_load(BlockDriverState *bs, uint64_t offset,
551                                          uint64_t size, Error **errp)
552 {
553     int ret;
554     BDRVQcow2State *s = bs->opaque;
555     uint8_t *dir, *dir_end;
556     Qcow2BitmapDirEntry *e;
557     uint32_t nb_dir_entries = 0;
558     Qcow2BitmapList *bm_list = NULL;
559 
560     if (size == 0) {
561         error_setg(errp, "Requested bitmap directory size is zero");
562         return NULL;
563     }
564 
565     if (size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
566         error_setg(errp, "Requested bitmap directory size is too big");
567         return NULL;
568     }
569 
570     dir = g_try_malloc(size);
571     if (dir == NULL) {
572         error_setg(errp, "Failed to allocate space for bitmap directory");
573         return NULL;
574     }
575     dir_end = dir + size;
576 
577     ret = bdrv_pread(bs->file, offset, dir, size);
578     if (ret < 0) {
579         error_setg_errno(errp, -ret, "Failed to read bitmap directory");
580         goto fail;
581     }
582 
583     bm_list = bitmap_list_new();
584     for (e = (Qcow2BitmapDirEntry *)dir;
585          e < (Qcow2BitmapDirEntry *)dir_end;
586          e = next_dir_entry(e))
587     {
588         Qcow2Bitmap *bm;
589 
590         if ((uint8_t *)(e + 1) > dir_end) {
591             goto broken_dir;
592         }
593 
594         if (++nb_dir_entries > s->nb_bitmaps) {
595             error_setg(errp, "More bitmaps found than specified in header"
596                        " extension");
597             goto fail;
598         }
599         bitmap_dir_entry_to_cpu(e);
600 
601         if ((uint8_t *)next_dir_entry(e) > dir_end) {
602             goto broken_dir;
603         }
604 
605         if (e->extra_data_size != 0) {
606             error_setg(errp, "Bitmap extra data is not supported");
607             goto fail;
608         }
609 
610         ret = check_dir_entry(bs, e);
611         if (ret < 0) {
612             error_setg(errp, "Bitmap '%.*s' doesn't satisfy the constraints",
613                        e->name_size, dir_entry_name_field(e));
614             goto fail;
615         }
616 
617         bm = g_new0(Qcow2Bitmap, 1);
618         bm->table.offset = e->bitmap_table_offset;
619         bm->table.size = e->bitmap_table_size;
620         bm->flags = e->flags;
621         bm->granularity_bits = e->granularity_bits;
622         bm->name = dir_entry_copy_name(e);
623         QSIMPLEQ_INSERT_TAIL(bm_list, bm, entry);
624     }
625 
626     if (nb_dir_entries != s->nb_bitmaps) {
627         error_setg(errp, "Less bitmaps found than specified in header"
628                          " extension");
629         goto fail;
630     }
631 
632     if ((uint8_t *)e != dir_end) {
633         goto broken_dir;
634     }
635 
636     g_free(dir);
637     return bm_list;
638 
639 broken_dir:
640     ret = -EINVAL;
641     error_setg(errp, "Broken bitmap directory");
642 
643 fail:
644     g_free(dir);
645     bitmap_list_free(bm_list);
646 
647     return NULL;
648 }
649 
650 int qcow2_check_bitmaps_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
651                                   void **refcount_table,
652                                   int64_t *refcount_table_size)
653 {
654     int ret;
655     BDRVQcow2State *s = bs->opaque;
656     Qcow2BitmapList *bm_list;
657     Qcow2Bitmap *bm;
658 
659     if (s->nb_bitmaps == 0) {
660         return 0;
661     }
662 
663     ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, refcount_table_size,
664                                    s->bitmap_directory_offset,
665                                    s->bitmap_directory_size);
666     if (ret < 0) {
667         return ret;
668     }
669 
670     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
671                                s->bitmap_directory_size, NULL);
672     if (bm_list == NULL) {
673         res->corruptions++;
674         return -EINVAL;
675     }
676 
677     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
678         uint64_t *bitmap_table = NULL;
679         int i;
680 
681         ret = qcow2_inc_refcounts_imrt(bs, res,
682                                        refcount_table, refcount_table_size,
683                                        bm->table.offset,
684                                        bm->table.size * sizeof(uint64_t));
685         if (ret < 0) {
686             goto out;
687         }
688 
689         ret = bitmap_table_load(bs, &bm->table, &bitmap_table);
690         if (ret < 0) {
691             res->corruptions++;
692             goto out;
693         }
694 
695         for (i = 0; i < bm->table.size; ++i) {
696             uint64_t entry = bitmap_table[i];
697             uint64_t offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
698 
699             if (check_table_entry(entry, s->cluster_size) < 0) {
700                 res->corruptions++;
701                 continue;
702             }
703 
704             if (offset == 0) {
705                 continue;
706             }
707 
708             ret = qcow2_inc_refcounts_imrt(bs, res,
709                                            refcount_table, refcount_table_size,
710                                            offset, s->cluster_size);
711             if (ret < 0) {
712                 g_free(bitmap_table);
713                 goto out;
714             }
715         }
716 
717         g_free(bitmap_table);
718     }
719 
720 out:
721     bitmap_list_free(bm_list);
722 
723     return ret;
724 }
725 
726 /* bitmap_list_store
727  * Store bitmap list to qcow2 image as a bitmap directory.
728  * Everything is checked.
729  */
730 static int bitmap_list_store(BlockDriverState *bs, Qcow2BitmapList *bm_list,
731                              uint64_t *offset, uint64_t *size, bool in_place)
732 {
733     int ret;
734     uint8_t *dir;
735     int64_t dir_offset = 0;
736     uint64_t dir_size = 0;
737     Qcow2Bitmap *bm;
738     Qcow2BitmapDirEntry *e;
739 
740     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
741         dir_size += calc_dir_entry_size(strlen(bm->name), 0);
742     }
743 
744     if (dir_size == 0 || dir_size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
745         return -EINVAL;
746     }
747 
748     if (in_place) {
749         if (*size != dir_size || *offset == 0) {
750             return -EINVAL;
751         }
752 
753         dir_offset = *offset;
754     }
755 
756     dir = g_try_malloc0(dir_size);
757     if (dir == NULL) {
758         return -ENOMEM;
759     }
760 
761     e = (Qcow2BitmapDirEntry *)dir;
762     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
763         e->bitmap_table_offset = bm->table.offset;
764         e->bitmap_table_size = bm->table.size;
765         e->flags = bm->flags;
766         e->type = BT_DIRTY_TRACKING_BITMAP;
767         e->granularity_bits = bm->granularity_bits;
768         e->name_size = strlen(bm->name);
769         e->extra_data_size = 0;
770         memcpy(e + 1, bm->name, e->name_size);
771 
772         if (check_dir_entry(bs, e) < 0) {
773             ret = -EINVAL;
774             goto fail;
775         }
776 
777         e = next_dir_entry(e);
778     }
779 
780     bitmap_directory_to_be(dir, dir_size);
781 
782     if (!in_place) {
783         dir_offset = qcow2_alloc_clusters(bs, dir_size);
784         if (dir_offset < 0) {
785             ret = dir_offset;
786             goto fail;
787         }
788     }
789 
790     /* Actually, even in in-place case ignoring QCOW2_OL_BITMAP_DIRECTORY is not
791      * necessary, because we drop QCOW2_AUTOCLEAR_BITMAPS when updating bitmap
792      * directory in-place (actually, turn-off the extension), which is checked
793      * in qcow2_check_metadata_overlap() */
794     ret = qcow2_pre_write_overlap_check(
795             bs, in_place ? QCOW2_OL_BITMAP_DIRECTORY : 0, dir_offset, dir_size,
796             false);
797     if (ret < 0) {
798         goto fail;
799     }
800 
801     ret = bdrv_pwrite(bs->file, dir_offset, dir, dir_size);
802     if (ret < 0) {
803         goto fail;
804     }
805 
806     g_free(dir);
807 
808     if (!in_place) {
809         *size = dir_size;
810         *offset = dir_offset;
811     }
812 
813     return 0;
814 
815 fail:
816     g_free(dir);
817 
818     if (!in_place && dir_offset > 0) {
819         qcow2_free_clusters(bs, dir_offset, dir_size, QCOW2_DISCARD_OTHER);
820     }
821 
822     return ret;
823 }
824 
825 /*
826  * Bitmap List end
827  */
828 
829 static int update_ext_header_and_dir_in_place(BlockDriverState *bs,
830                                               Qcow2BitmapList *bm_list)
831 {
832     BDRVQcow2State *s = bs->opaque;
833     int ret;
834 
835     if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS) ||
836         bm_list == NULL || QSIMPLEQ_EMPTY(bm_list) ||
837         bitmap_list_count(bm_list) != s->nb_bitmaps)
838     {
839         return -EINVAL;
840     }
841 
842     s->autoclear_features &= ~(uint64_t)QCOW2_AUTOCLEAR_BITMAPS;
843     ret = update_header_sync(bs);
844     if (ret < 0) {
845         /* Two variants are possible here:
846          * 1. Autoclear flag is dropped, all bitmaps will be lost.
847          * 2. Autoclear flag is not dropped, old state is left.
848          */
849         return ret;
850     }
851 
852     /* autoclear bit is not set, so we can safely update bitmap directory */
853 
854     ret = bitmap_list_store(bs, bm_list, &s->bitmap_directory_offset,
855                             &s->bitmap_directory_size, true);
856     if (ret < 0) {
857         /* autoclear bit is cleared, so all leaked clusters would be removed on
858          * qemu-img check */
859         return ret;
860     }
861 
862     ret = update_header_sync(bs);
863     if (ret < 0) {
864         /* autoclear bit is cleared, so all leaked clusters would be removed on
865          * qemu-img check */
866         return ret;
867     }
868 
869     s->autoclear_features |= QCOW2_AUTOCLEAR_BITMAPS;
870     return update_header_sync(bs);
871     /* If final update_header_sync() fails, two variants are possible:
872      * 1. Autoclear flag is not set, all bitmaps will be lost.
873      * 2. Autoclear flag is set, header and directory are successfully updated.
874      */
875 }
876 
877 static int update_ext_header_and_dir(BlockDriverState *bs,
878                                      Qcow2BitmapList *bm_list)
879 {
880     BDRVQcow2State *s = bs->opaque;
881     int ret;
882     uint64_t new_offset = 0;
883     uint64_t new_size = 0;
884     uint32_t new_nb_bitmaps = 0;
885     uint64_t old_offset = s->bitmap_directory_offset;
886     uint64_t old_size = s->bitmap_directory_size;
887     uint32_t old_nb_bitmaps = s->nb_bitmaps;
888     uint64_t old_autocl = s->autoclear_features;
889 
890     if (bm_list != NULL && !QSIMPLEQ_EMPTY(bm_list)) {
891         new_nb_bitmaps = bitmap_list_count(bm_list);
892 
893         if (new_nb_bitmaps > QCOW2_MAX_BITMAPS) {
894             return -EINVAL;
895         }
896 
897         ret = bitmap_list_store(bs, bm_list, &new_offset, &new_size, false);
898         if (ret < 0) {
899             return ret;
900         }
901 
902         ret = qcow2_flush_caches(bs);
903         if (ret < 0) {
904             goto fail;
905         }
906 
907         s->autoclear_features |= QCOW2_AUTOCLEAR_BITMAPS;
908     } else {
909         s->autoclear_features &= ~(uint64_t)QCOW2_AUTOCLEAR_BITMAPS;
910     }
911 
912     s->bitmap_directory_offset = new_offset;
913     s->bitmap_directory_size = new_size;
914     s->nb_bitmaps = new_nb_bitmaps;
915 
916     ret = update_header_sync(bs);
917     if (ret < 0) {
918         goto fail;
919     }
920 
921     if (old_size > 0) {
922         qcow2_free_clusters(bs, old_offset, old_size, QCOW2_DISCARD_OTHER);
923     }
924 
925     return 0;
926 
927 fail:
928     if (new_offset > 0) {
929         qcow2_free_clusters(bs, new_offset, new_size, QCOW2_DISCARD_OTHER);
930     }
931 
932     s->bitmap_directory_offset = old_offset;
933     s->bitmap_directory_size = old_size;
934     s->nb_bitmaps = old_nb_bitmaps;
935     s->autoclear_features = old_autocl;
936 
937     return ret;
938 }
939 
940 /* for g_slist_foreach for GSList of BdrvDirtyBitmap* elements */
941 static void release_dirty_bitmap_helper(gpointer bitmap,
942                                         gpointer bs)
943 {
944     bdrv_release_dirty_bitmap(bitmap);
945 }
946 
947 /* for g_slist_foreach for GSList of BdrvDirtyBitmap* elements */
948 static void set_readonly_helper(gpointer bitmap, gpointer value)
949 {
950     bdrv_dirty_bitmap_set_readonly(bitmap, (bool)value);
951 }
952 
953 /* qcow2_load_dirty_bitmaps()
954  * Return value is a hint for caller: true means that the Qcow2 header was
955  * updated. (false doesn't mean that the header should be updated by the
956  * caller, it just means that updating was not needed or the image cannot be
957  * written to).
958  * On failure the function returns false.
959  */
960 bool qcow2_load_dirty_bitmaps(BlockDriverState *bs, Error **errp)
961 {
962     BDRVQcow2State *s = bs->opaque;
963     Qcow2BitmapList *bm_list;
964     Qcow2Bitmap *bm;
965     GSList *created_dirty_bitmaps = NULL;
966     bool header_updated = false;
967     bool needs_update = false;
968 
969     if (s->nb_bitmaps == 0) {
970         /* No bitmaps - nothing to do */
971         return false;
972     }
973 
974     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
975                                s->bitmap_directory_size, errp);
976     if (bm_list == NULL) {
977         return false;
978     }
979 
980     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
981         BdrvDirtyBitmap *bitmap = load_bitmap(bs, bm, errp);
982         if (bitmap == NULL) {
983             goto fail;
984         }
985 
986         bdrv_dirty_bitmap_set_persistence(bitmap, true);
987         if (bm->flags & BME_FLAG_IN_USE) {
988             bdrv_dirty_bitmap_set_inconsistent(bitmap);
989         } else {
990             /* NB: updated flags only get written if can_write(bs) is true. */
991             bm->flags |= BME_FLAG_IN_USE;
992             needs_update = true;
993         }
994         if (!(bm->flags & BME_FLAG_AUTO)) {
995             bdrv_disable_dirty_bitmap(bitmap);
996         }
997         created_dirty_bitmaps =
998             g_slist_append(created_dirty_bitmaps, bitmap);
999     }
1000 
1001     if (needs_update && can_write(bs)) {
1002         /* in_use flags must be updated */
1003         int ret = update_ext_header_and_dir_in_place(bs, bm_list);
1004         if (ret < 0) {
1005             error_setg_errno(errp, -ret, "Can't update bitmap directory");
1006             goto fail;
1007         }
1008         header_updated = true;
1009     }
1010 
1011     if (!can_write(bs)) {
1012         g_slist_foreach(created_dirty_bitmaps, set_readonly_helper,
1013                         (gpointer)true);
1014     }
1015 
1016     g_slist_free(created_dirty_bitmaps);
1017     bitmap_list_free(bm_list);
1018 
1019     return header_updated;
1020 
1021 fail:
1022     g_slist_foreach(created_dirty_bitmaps, release_dirty_bitmap_helper, bs);
1023     g_slist_free(created_dirty_bitmaps);
1024     bitmap_list_free(bm_list);
1025 
1026     return false;
1027 }
1028 
1029 
1030 static Qcow2BitmapInfoFlagsList *get_bitmap_info_flags(uint32_t flags)
1031 {
1032     Qcow2BitmapInfoFlagsList *list = NULL;
1033     Qcow2BitmapInfoFlagsList **plist = &list;
1034     int i;
1035 
1036     static const struct {
1037         int bme;  /* Bitmap directory entry flags */
1038         int info; /* The flags to report to the user */
1039     } map[] = {
1040         { BME_FLAG_IN_USE, QCOW2_BITMAP_INFO_FLAGS_IN_USE },
1041         { BME_FLAG_AUTO,   QCOW2_BITMAP_INFO_FLAGS_AUTO },
1042     };
1043 
1044     int map_size = ARRAY_SIZE(map);
1045 
1046     for (i = 0; i < map_size; ++i) {
1047         if (flags & map[i].bme) {
1048             Qcow2BitmapInfoFlagsList *entry =
1049                 g_new0(Qcow2BitmapInfoFlagsList, 1);
1050             entry->value = map[i].info;
1051             *plist = entry;
1052             plist = &entry->next;
1053             flags &= ~map[i].bme;
1054         }
1055     }
1056     /* Check if the BME_* mapping above is complete */
1057     assert(!flags);
1058 
1059     return list;
1060 }
1061 
1062 /*
1063  * qcow2_get_bitmap_info_list()
1064  * Returns a list of QCOW2 bitmap details.
1065  * In case of no bitmaps, the function returns NULL and
1066  * the @errp parameter is not set.
1067  * When bitmap information can not be obtained, the function returns
1068  * NULL and the @errp parameter is set.
1069  */
1070 Qcow2BitmapInfoList *qcow2_get_bitmap_info_list(BlockDriverState *bs,
1071                                                 Error **errp)
1072 {
1073     BDRVQcow2State *s = bs->opaque;
1074     Qcow2BitmapList *bm_list;
1075     Qcow2Bitmap *bm;
1076     Qcow2BitmapInfoList *list = NULL;
1077     Qcow2BitmapInfoList **plist = &list;
1078 
1079     if (s->nb_bitmaps == 0) {
1080         return NULL;
1081     }
1082 
1083     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1084                                s->bitmap_directory_size, errp);
1085     if (bm_list == NULL) {
1086         return NULL;
1087     }
1088 
1089     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1090         Qcow2BitmapInfo *info = g_new0(Qcow2BitmapInfo, 1);
1091         Qcow2BitmapInfoList *obj = g_new0(Qcow2BitmapInfoList, 1);
1092         info->granularity = 1U << bm->granularity_bits;
1093         info->name = g_strdup(bm->name);
1094         info->flags = get_bitmap_info_flags(bm->flags & ~BME_RESERVED_FLAGS);
1095         obj->value = info;
1096         *plist = obj;
1097         plist = &obj->next;
1098     }
1099 
1100     bitmap_list_free(bm_list);
1101 
1102     return list;
1103 }
1104 
1105 int qcow2_reopen_bitmaps_rw(BlockDriverState *bs, Error **errp)
1106 {
1107     BDRVQcow2State *s = bs->opaque;
1108     Qcow2BitmapList *bm_list;
1109     Qcow2Bitmap *bm;
1110     GSList *ro_dirty_bitmaps = NULL;
1111     int ret = -EINVAL;
1112     bool need_header_update = false;
1113 
1114     if (s->nb_bitmaps == 0) {
1115         /* No bitmaps - nothing to do */
1116         return 0;
1117     }
1118 
1119     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1120                                s->bitmap_directory_size, errp);
1121     if (bm_list == NULL) {
1122         return -EINVAL;
1123     }
1124 
1125     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1126         BdrvDirtyBitmap *bitmap = bdrv_find_dirty_bitmap(bs, bm->name);
1127 
1128         if (!bitmap) {
1129             error_setg(errp, "Unexpected bitmap '%s' in image '%s'",
1130                        bm->name, bs->filename);
1131             goto out;
1132         }
1133 
1134         if (!(bm->flags & BME_FLAG_IN_USE)) {
1135             if (!bdrv_dirty_bitmap_readonly(bitmap)) {
1136                 error_setg(errp, "Corruption: bitmap '%s' is not marked IN_USE "
1137                            "in the image '%s' and not marked readonly in RAM",
1138                            bm->name, bs->filename);
1139                 goto out;
1140             }
1141             if (bdrv_dirty_bitmap_inconsistent(bitmap)) {
1142                 error_setg(errp, "Corruption: bitmap '%s' is inconsistent but "
1143                            "is not marked IN_USE in the image '%s'", bm->name,
1144                            bs->filename);
1145                 goto out;
1146             }
1147 
1148             bm->flags |= BME_FLAG_IN_USE;
1149             need_header_update = true;
1150         } else {
1151             /*
1152              * What if flags already has BME_FLAG_IN_USE ?
1153              *
1154              * 1. if we are reopening RW -> RW it's OK, of course.
1155              * 2. if we are reopening RO -> RW:
1156              *   2.1 if @bitmap is inconsistent, it's OK. It means that it was
1157              *       inconsistent (IN_USE) when we loaded it
1158              *   2.2 if @bitmap is not inconsistent. This seems to be impossible
1159              *       and implies third party interaction. Let's error-out for
1160              *       safety.
1161              */
1162             if (bdrv_dirty_bitmap_readonly(bitmap) &&
1163                 !bdrv_dirty_bitmap_inconsistent(bitmap))
1164             {
1165                 error_setg(errp, "Corruption: bitmap '%s' is marked IN_USE "
1166                            "in the image '%s' but it is readonly and "
1167                            "consistent in RAM",
1168                            bm->name, bs->filename);
1169                 goto out;
1170             }
1171         }
1172 
1173         if (bdrv_dirty_bitmap_readonly(bitmap)) {
1174             ro_dirty_bitmaps = g_slist_append(ro_dirty_bitmaps, bitmap);
1175         }
1176     }
1177 
1178     if (need_header_update) {
1179         if (!can_write(bs->file->bs) || !(bs->file->perm & BLK_PERM_WRITE)) {
1180             error_setg(errp, "Failed to reopen bitmaps rw: no write access "
1181                        "the protocol file");
1182             goto out;
1183         }
1184 
1185         /* in_use flags must be updated */
1186         ret = update_ext_header_and_dir_in_place(bs, bm_list);
1187         if (ret < 0) {
1188             error_setg_errno(errp, -ret, "Cannot update bitmap directory");
1189             goto out;
1190         }
1191     }
1192 
1193     g_slist_foreach(ro_dirty_bitmaps, set_readonly_helper, false);
1194     ret = 0;
1195 
1196 out:
1197     g_slist_free(ro_dirty_bitmaps);
1198     bitmap_list_free(bm_list);
1199 
1200     return ret;
1201 }
1202 
1203 /* Checks to see if it's safe to resize bitmaps */
1204 int qcow2_truncate_bitmaps_check(BlockDriverState *bs, Error **errp)
1205 {
1206     BDRVQcow2State *s = bs->opaque;
1207     Qcow2BitmapList *bm_list;
1208     Qcow2Bitmap *bm;
1209     int ret = 0;
1210 
1211     if (s->nb_bitmaps == 0) {
1212         return 0;
1213     }
1214 
1215     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1216                                s->bitmap_directory_size, errp);
1217     if (bm_list == NULL) {
1218         return -EINVAL;
1219     }
1220 
1221     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1222         BdrvDirtyBitmap *bitmap = bdrv_find_dirty_bitmap(bs, bm->name);
1223         if (bitmap == NULL) {
1224             /*
1225              * We rely on all bitmaps being in-memory to be able to resize them,
1226              * Otherwise, we'd need to resize them on disk explicitly
1227              */
1228             error_setg(errp, "Cannot resize qcow2 with persistent bitmaps that "
1229                        "were not loaded into memory");
1230             ret = -ENOTSUP;
1231             goto out;
1232         }
1233 
1234         /*
1235          * The checks against readonly and busy are redundant, but certainly
1236          * do no harm. checks against inconsistent are crucial:
1237          */
1238         if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_DEFAULT, errp)) {
1239             ret = -ENOTSUP;
1240             goto out;
1241         }
1242     }
1243 
1244 out:
1245     bitmap_list_free(bm_list);
1246     return ret;
1247 }
1248 
1249 /* store_bitmap_data()
1250  * Store bitmap to image, filling bitmap table accordingly.
1251  */
1252 static uint64_t *store_bitmap_data(BlockDriverState *bs,
1253                                    BdrvDirtyBitmap *bitmap,
1254                                    uint32_t *bitmap_table_size, Error **errp)
1255 {
1256     int ret;
1257     BDRVQcow2State *s = bs->opaque;
1258     int64_t offset;
1259     uint64_t limit;
1260     uint64_t bm_size = bdrv_dirty_bitmap_size(bitmap);
1261     const char *bm_name = bdrv_dirty_bitmap_name(bitmap);
1262     uint8_t *buf = NULL;
1263     BdrvDirtyBitmapIter *dbi;
1264     uint64_t *tb;
1265     uint64_t tb_size =
1266             size_to_clusters(s,
1267                 bdrv_dirty_bitmap_serialization_size(bitmap, 0, bm_size));
1268 
1269     if (tb_size > BME_MAX_TABLE_SIZE ||
1270         tb_size * s->cluster_size > BME_MAX_PHYS_SIZE)
1271     {
1272         error_setg(errp, "Bitmap '%s' is too big", bm_name);
1273         return NULL;
1274     }
1275 
1276     tb = g_try_new0(uint64_t, tb_size);
1277     if (tb == NULL) {
1278         error_setg(errp, "No memory");
1279         return NULL;
1280     }
1281 
1282     dbi = bdrv_dirty_iter_new(bitmap);
1283     buf = g_malloc(s->cluster_size);
1284     limit = bytes_covered_by_bitmap_cluster(s, bitmap);
1285     assert(DIV_ROUND_UP(bm_size, limit) == tb_size);
1286 
1287     while ((offset = bdrv_dirty_iter_next(dbi)) >= 0) {
1288         uint64_t cluster = offset / limit;
1289         uint64_t end, write_size;
1290         int64_t off;
1291 
1292         /*
1293          * We found the first dirty offset, but want to write out the
1294          * entire cluster of the bitmap that includes that offset,
1295          * including any leading zero bits.
1296          */
1297         offset = QEMU_ALIGN_DOWN(offset, limit);
1298         end = MIN(bm_size, offset + limit);
1299         write_size = bdrv_dirty_bitmap_serialization_size(bitmap, offset,
1300                                                           end - offset);
1301         assert(write_size <= s->cluster_size);
1302 
1303         off = qcow2_alloc_clusters(bs, s->cluster_size);
1304         if (off < 0) {
1305             error_setg_errno(errp, -off,
1306                              "Failed to allocate clusters for bitmap '%s'",
1307                              bm_name);
1308             goto fail;
1309         }
1310         tb[cluster] = off;
1311 
1312         bdrv_dirty_bitmap_serialize_part(bitmap, buf, offset, end - offset);
1313         if (write_size < s->cluster_size) {
1314             memset(buf + write_size, 0, s->cluster_size - write_size);
1315         }
1316 
1317         ret = qcow2_pre_write_overlap_check(bs, 0, off, s->cluster_size, false);
1318         if (ret < 0) {
1319             error_setg_errno(errp, -ret, "Qcow2 overlap check failed");
1320             goto fail;
1321         }
1322 
1323         ret = bdrv_pwrite(bs->file, off, buf, s->cluster_size);
1324         if (ret < 0) {
1325             error_setg_errno(errp, -ret, "Failed to write bitmap '%s' to file",
1326                              bm_name);
1327             goto fail;
1328         }
1329 
1330         if (end >= bm_size) {
1331             break;
1332         }
1333 
1334         bdrv_set_dirty_iter(dbi, end);
1335     }
1336 
1337     *bitmap_table_size = tb_size;
1338     g_free(buf);
1339     bdrv_dirty_iter_free(dbi);
1340 
1341     return tb;
1342 
1343 fail:
1344     clear_bitmap_table(bs, tb, tb_size);
1345     g_free(buf);
1346     bdrv_dirty_iter_free(dbi);
1347     g_free(tb);
1348 
1349     return NULL;
1350 }
1351 
1352 /* store_bitmap()
1353  * Store bm->dirty_bitmap to qcow2.
1354  * Set bm->table_offset and bm->table_size accordingly.
1355  */
1356 static int store_bitmap(BlockDriverState *bs, Qcow2Bitmap *bm, Error **errp)
1357 {
1358     int ret;
1359     uint64_t *tb;
1360     int64_t tb_offset;
1361     uint32_t tb_size;
1362     BdrvDirtyBitmap *bitmap = bm->dirty_bitmap;
1363     const char *bm_name;
1364 
1365     assert(bitmap != NULL);
1366 
1367     bm_name = bdrv_dirty_bitmap_name(bitmap);
1368 
1369     tb = store_bitmap_data(bs, bitmap, &tb_size, errp);
1370     if (tb == NULL) {
1371         return -EINVAL;
1372     }
1373 
1374     assert(tb_size <= BME_MAX_TABLE_SIZE);
1375     tb_offset = qcow2_alloc_clusters(bs, tb_size * sizeof(tb[0]));
1376     if (tb_offset < 0) {
1377         error_setg_errno(errp, -tb_offset,
1378                          "Failed to allocate clusters for bitmap '%s'",
1379                          bm_name);
1380         ret = tb_offset;
1381         goto fail;
1382     }
1383 
1384     ret = qcow2_pre_write_overlap_check(bs, 0, tb_offset,
1385                                         tb_size * sizeof(tb[0]), false);
1386     if (ret < 0) {
1387         error_setg_errno(errp, -ret, "Qcow2 overlap check failed");
1388         goto fail;
1389     }
1390 
1391     bitmap_table_to_be(tb, tb_size);
1392     ret = bdrv_pwrite(bs->file, tb_offset, tb, tb_size * sizeof(tb[0]));
1393     if (ret < 0) {
1394         error_setg_errno(errp, -ret, "Failed to write bitmap '%s' to file",
1395                          bm_name);
1396         goto fail;
1397     }
1398 
1399     g_free(tb);
1400 
1401     bm->table.offset = tb_offset;
1402     bm->table.size = tb_size;
1403 
1404     return 0;
1405 
1406 fail:
1407     clear_bitmap_table(bs, tb, tb_size);
1408 
1409     if (tb_offset > 0) {
1410         qcow2_free_clusters(bs, tb_offset, tb_size * sizeof(tb[0]),
1411                             QCOW2_DISCARD_OTHER);
1412     }
1413 
1414     g_free(tb);
1415 
1416     return ret;
1417 }
1418 
1419 static Qcow2Bitmap *find_bitmap_by_name(Qcow2BitmapList *bm_list,
1420                                         const char *name)
1421 {
1422     Qcow2Bitmap *bm;
1423 
1424     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1425         if (strcmp(name, bm->name) == 0) {
1426             return bm;
1427         }
1428     }
1429 
1430     return NULL;
1431 }
1432 
1433 int coroutine_fn qcow2_co_remove_persistent_dirty_bitmap(BlockDriverState *bs,
1434                                                          const char *name,
1435                                                          Error **errp)
1436 {
1437     int ret;
1438     BDRVQcow2State *s = bs->opaque;
1439     Qcow2Bitmap *bm = NULL;
1440     Qcow2BitmapList *bm_list;
1441 
1442     if (s->nb_bitmaps == 0) {
1443         /* Absence of the bitmap is not an error: see explanation above
1444          * bdrv_remove_persistent_dirty_bitmap() definition. */
1445         return 0;
1446     }
1447 
1448     qemu_co_mutex_lock(&s->lock);
1449 
1450     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1451                                s->bitmap_directory_size, errp);
1452     if (bm_list == NULL) {
1453         ret = -EIO;
1454         goto out;
1455     }
1456 
1457     bm = find_bitmap_by_name(bm_list, name);
1458     if (bm == NULL) {
1459         ret = -EINVAL;
1460         goto out;
1461     }
1462 
1463     QSIMPLEQ_REMOVE(bm_list, bm, Qcow2Bitmap, entry);
1464 
1465     ret = update_ext_header_and_dir(bs, bm_list);
1466     if (ret < 0) {
1467         error_setg_errno(errp, -ret, "Failed to update bitmap extension");
1468         goto out;
1469     }
1470 
1471     free_bitmap_clusters(bs, &bm->table);
1472 
1473 out:
1474     qemu_co_mutex_unlock(&s->lock);
1475 
1476     bitmap_free(bm);
1477     bitmap_list_free(bm_list);
1478 
1479     return ret;
1480 }
1481 
1482 /*
1483  * qcow2_store_persistent_dirty_bitmaps
1484  *
1485  * Stores persistent BdrvDirtyBitmap objects.
1486  *
1487  * @release_stored: if true, release BdrvDirtyBitmap's after storing to the
1488  * image. This is used in two cases, both via qcow2_inactivate:
1489  * 1. bdrv_close: It's correct to remove bitmaps on close.
1490  * 2. migration: If bitmaps are migrated through migration channel via
1491  *    'dirty-bitmaps' migration capability they are not handled by this code.
1492  *    Otherwise, it's OK to drop BdrvDirtyBitmap's and reload them on
1493  *    invalidation.
1494  *
1495  * Anyway, it's correct to remove BdrvDirtyBitmap's on inactivation, as
1496  * inactivation means that we lose control on disk, and therefore on bitmaps,
1497  * we should sync them and do not touch more.
1498  *
1499  * Contrariwise, we don't want to release any bitmaps on just reopen-to-ro,
1500  * when we need to store them, as image is still under our control, and it's
1501  * good to keep all the bitmaps in read-only mode. Moreover, keeping them
1502  * read-only is correct because this is what would happen if we opened the node
1503  * readonly to begin with, and whether we opened directly or reopened to that
1504  * state shouldn't matter for the state we get afterward.
1505  */
1506 void qcow2_store_persistent_dirty_bitmaps(BlockDriverState *bs,
1507                                           bool release_stored, Error **errp)
1508 {
1509     BdrvDirtyBitmap *bitmap;
1510     BDRVQcow2State *s = bs->opaque;
1511     uint32_t new_nb_bitmaps = s->nb_bitmaps;
1512     uint64_t new_dir_size = s->bitmap_directory_size;
1513     int ret;
1514     Qcow2BitmapList *bm_list;
1515     Qcow2Bitmap *bm;
1516     QSIMPLEQ_HEAD(, Qcow2BitmapTable) drop_tables;
1517     Qcow2BitmapTable *tb, *tb_next;
1518     bool need_write = false;
1519 
1520     QSIMPLEQ_INIT(&drop_tables);
1521 
1522     if (s->nb_bitmaps == 0) {
1523         bm_list = bitmap_list_new();
1524     } else {
1525         bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1526                                    s->bitmap_directory_size, errp);
1527         if (bm_list == NULL) {
1528             return;
1529         }
1530     }
1531 
1532     /* check constraints and names */
1533     FOR_EACH_DIRTY_BITMAP(bs, bitmap) {
1534         const char *name = bdrv_dirty_bitmap_name(bitmap);
1535         uint32_t granularity = bdrv_dirty_bitmap_granularity(bitmap);
1536         Qcow2Bitmap *bm;
1537 
1538         if (!bdrv_dirty_bitmap_get_persistence(bitmap) ||
1539             bdrv_dirty_bitmap_readonly(bitmap) ||
1540             bdrv_dirty_bitmap_inconsistent(bitmap)) {
1541             continue;
1542         }
1543 
1544         need_write = true;
1545 
1546         if (check_constraints_on_bitmap(bs, name, granularity, errp) < 0) {
1547             error_prepend(errp, "Bitmap '%s' doesn't satisfy the constraints: ",
1548                           name);
1549             goto fail;
1550         }
1551 
1552         bm = find_bitmap_by_name(bm_list, name);
1553         if (bm == NULL) {
1554             if (++new_nb_bitmaps > QCOW2_MAX_BITMAPS) {
1555                 error_setg(errp, "Too many persistent bitmaps");
1556                 goto fail;
1557             }
1558 
1559             new_dir_size += calc_dir_entry_size(strlen(name), 0);
1560             if (new_dir_size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
1561                 error_setg(errp, "Bitmap directory is too large");
1562                 goto fail;
1563             }
1564 
1565             bm = g_new0(Qcow2Bitmap, 1);
1566             bm->name = g_strdup(name);
1567             QSIMPLEQ_INSERT_TAIL(bm_list, bm, entry);
1568         } else {
1569             if (!(bm->flags & BME_FLAG_IN_USE)) {
1570                 error_setg(errp, "Bitmap '%s' already exists in the image",
1571                            name);
1572                 goto fail;
1573             }
1574             tb = g_memdup(&bm->table, sizeof(bm->table));
1575             bm->table.offset = 0;
1576             bm->table.size = 0;
1577             QSIMPLEQ_INSERT_TAIL(&drop_tables, tb, entry);
1578         }
1579         bm->flags = bdrv_dirty_bitmap_enabled(bitmap) ? BME_FLAG_AUTO : 0;
1580         bm->granularity_bits = ctz32(bdrv_dirty_bitmap_granularity(bitmap));
1581         bm->dirty_bitmap = bitmap;
1582     }
1583 
1584     if (!need_write) {
1585         goto success;
1586     }
1587 
1588     if (!can_write(bs)) {
1589         error_setg(errp, "No write access");
1590         goto fail;
1591     }
1592 
1593     /* allocate clusters and store bitmaps */
1594     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1595         if (bm->dirty_bitmap == NULL) {
1596             continue;
1597         }
1598 
1599         ret = store_bitmap(bs, bm, errp);
1600         if (ret < 0) {
1601             goto fail;
1602         }
1603     }
1604 
1605     ret = update_ext_header_and_dir(bs, bm_list);
1606     if (ret < 0) {
1607         error_setg_errno(errp, -ret, "Failed to update bitmap extension");
1608         goto fail;
1609     }
1610 
1611     /* Bitmap directory was successfully updated, so, old data can be dropped.
1612      * TODO it is better to reuse these clusters */
1613     QSIMPLEQ_FOREACH_SAFE(tb, &drop_tables, entry, tb_next) {
1614         free_bitmap_clusters(bs, tb);
1615         g_free(tb);
1616     }
1617 
1618     if (release_stored) {
1619         QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1620             if (bm->dirty_bitmap == NULL) {
1621                 continue;
1622             }
1623 
1624             bdrv_release_dirty_bitmap(bm->dirty_bitmap);
1625         }
1626     }
1627 
1628 success:
1629     bitmap_list_free(bm_list);
1630     return;
1631 
1632 fail:
1633     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1634         if (bm->dirty_bitmap == NULL || bm->table.offset == 0) {
1635             continue;
1636         }
1637 
1638         free_bitmap_clusters(bs, &bm->table);
1639     }
1640 
1641     QSIMPLEQ_FOREACH_SAFE(tb, &drop_tables, entry, tb_next) {
1642         g_free(tb);
1643     }
1644 
1645     bitmap_list_free(bm_list);
1646 }
1647 
1648 int qcow2_reopen_bitmaps_ro(BlockDriverState *bs, Error **errp)
1649 {
1650     BdrvDirtyBitmap *bitmap;
1651     Error *local_err = NULL;
1652 
1653     qcow2_store_persistent_dirty_bitmaps(bs, false, &local_err);
1654     if (local_err != NULL) {
1655         error_propagate(errp, local_err);
1656         return -EINVAL;
1657     }
1658 
1659     FOR_EACH_DIRTY_BITMAP(bs, bitmap) {
1660         if (bdrv_dirty_bitmap_get_persistence(bitmap)) {
1661             bdrv_dirty_bitmap_set_readonly(bitmap, true);
1662         }
1663     }
1664 
1665     return 0;
1666 }
1667 
1668 bool coroutine_fn qcow2_co_can_store_new_dirty_bitmap(BlockDriverState *bs,
1669                                                       const char *name,
1670                                                       uint32_t granularity,
1671                                                       Error **errp)
1672 {
1673     BDRVQcow2State *s = bs->opaque;
1674     bool found;
1675     Qcow2BitmapList *bm_list;
1676 
1677     if (s->qcow_version < 3) {
1678         /* Without autoclear_features, we would always have to assume
1679          * that a program without persistent dirty bitmap support has
1680          * accessed this qcow2 file when opening it, and would thus
1681          * have to drop all dirty bitmaps (defeating their purpose).
1682          */
1683         error_setg(errp, "Cannot store dirty bitmaps in qcow2 v2 files");
1684         goto fail;
1685     }
1686 
1687     if (check_constraints_on_bitmap(bs, name, granularity, errp) != 0) {
1688         goto fail;
1689     }
1690 
1691     if (s->nb_bitmaps == 0) {
1692         return true;
1693     }
1694 
1695     if (s->nb_bitmaps >= QCOW2_MAX_BITMAPS) {
1696         error_setg(errp,
1697                    "Maximum number of persistent bitmaps is already reached");
1698         goto fail;
1699     }
1700 
1701     if (s->bitmap_directory_size + calc_dir_entry_size(strlen(name), 0) >
1702         QCOW2_MAX_BITMAP_DIRECTORY_SIZE)
1703     {
1704         error_setg(errp, "Not enough space in the bitmap directory");
1705         goto fail;
1706     }
1707 
1708     qemu_co_mutex_lock(&s->lock);
1709     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1710                                s->bitmap_directory_size, errp);
1711     qemu_co_mutex_unlock(&s->lock);
1712     if (bm_list == NULL) {
1713         goto fail;
1714     }
1715 
1716     found = find_bitmap_by_name(bm_list, name);
1717     bitmap_list_free(bm_list);
1718     if (found) {
1719         error_setg(errp, "Bitmap with the same name is already stored");
1720         goto fail;
1721     }
1722 
1723     return true;
1724 
1725 fail:
1726     error_prepend(errp, "Can't make bitmap '%s' persistent in '%s': ",
1727                   name, bdrv_get_device_or_node_name(bs));
1728     return false;
1729 }
1730