xref: /openbmc/qemu/block/qcow2-bitmap.c (revision d40d3da0)
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 "block/block_int.h"
33 #include "block/qcow2.h"
34 
35 /* NOTICE: BME here means Bitmaps Extension and used as a namespace for
36  * _internal_ constants. Please do not use this _internal_ abbreviation for
37  * other needs and/or outside of this file. */
38 
39 /* Bitmap directory entry constraints */
40 #define BME_MAX_TABLE_SIZE 0x8000000
41 #define BME_MAX_PHYS_SIZE 0x20000000 /* restrict BdrvDirtyBitmap size in RAM */
42 #define BME_MAX_GRANULARITY_BITS 31
43 #define BME_MIN_GRANULARITY_BITS 9
44 #define BME_MAX_NAME_SIZE 1023
45 
46 #if BME_MAX_TABLE_SIZE * 8ULL > INT_MAX
47 #error In the code bitmap table physical size assumed to fit into int
48 #endif
49 
50 /* Bitmap directory entry flags */
51 #define BME_RESERVED_FLAGS 0xfffffffcU
52 #define BME_FLAG_IN_USE (1U << 0)
53 #define BME_FLAG_AUTO   (1U << 1)
54 
55 /* bits [1, 8] U [56, 63] are reserved */
56 #define BME_TABLE_ENTRY_RESERVED_MASK 0xff000000000001feULL
57 #define BME_TABLE_ENTRY_OFFSET_MASK 0x00fffffffffffe00ULL
58 #define BME_TABLE_ENTRY_FLAG_ALL_ONES (1ULL << 0)
59 
60 typedef struct QEMU_PACKED Qcow2BitmapDirEntry {
61     /* header is 8 byte aligned */
62     uint64_t bitmap_table_offset;
63 
64     uint32_t bitmap_table_size;
65     uint32_t flags;
66 
67     uint8_t type;
68     uint8_t granularity_bits;
69     uint16_t name_size;
70     uint32_t extra_data_size;
71     /* extra data follows  */
72     /* name follows  */
73 } Qcow2BitmapDirEntry;
74 
75 typedef struct Qcow2BitmapTable {
76     uint64_t offset;
77     uint32_t size; /* number of 64bit entries */
78     QSIMPLEQ_ENTRY(Qcow2BitmapTable) entry;
79 } Qcow2BitmapTable;
80 typedef QSIMPLEQ_HEAD(Qcow2BitmapTableList, Qcow2BitmapTable)
81     Qcow2BitmapTableList;
82 
83 typedef struct Qcow2Bitmap {
84     Qcow2BitmapTable table;
85     uint32_t flags;
86     uint8_t granularity_bits;
87     char *name;
88 
89     BdrvDirtyBitmap *dirty_bitmap;
90 
91     QSIMPLEQ_ENTRY(Qcow2Bitmap) entry;
92 } Qcow2Bitmap;
93 typedef QSIMPLEQ_HEAD(Qcow2BitmapList, Qcow2Bitmap) Qcow2BitmapList;
94 
95 typedef enum BitmapType {
96     BT_DIRTY_TRACKING_BITMAP = 1
97 } BitmapType;
98 
99 static inline bool can_write(BlockDriverState *bs)
100 {
101     return !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
102 }
103 
104 static int update_header_sync(BlockDriverState *bs)
105 {
106     int ret;
107 
108     ret = qcow2_update_header(bs);
109     if (ret < 0) {
110         return ret;
111     }
112 
113     return bdrv_flush(bs);
114 }
115 
116 static inline void bitmap_table_to_be(uint64_t *bitmap_table, size_t size)
117 {
118     size_t i;
119 
120     for (i = 0; i < size; ++i) {
121         cpu_to_be64s(&bitmap_table[i]);
122     }
123 }
124 
125 static int check_table_entry(uint64_t entry, int cluster_size)
126 {
127     uint64_t offset;
128 
129     if (entry & BME_TABLE_ENTRY_RESERVED_MASK) {
130         return -EINVAL;
131     }
132 
133     offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
134     if (offset != 0) {
135         /* if offset specified, bit 0 is reserved */
136         if (entry & BME_TABLE_ENTRY_FLAG_ALL_ONES) {
137             return -EINVAL;
138         }
139 
140         if (offset % cluster_size != 0) {
141             return -EINVAL;
142         }
143     }
144 
145     return 0;
146 }
147 
148 static int check_constraints_on_bitmap(BlockDriverState *bs,
149                                        const char *name,
150                                        uint32_t granularity,
151                                        Error **errp)
152 {
153     BDRVQcow2State *s = bs->opaque;
154     int granularity_bits = ctz32(granularity);
155     int64_t len = bdrv_getlength(bs);
156 
157     assert(granularity > 0);
158     assert((granularity & (granularity - 1)) == 0);
159 
160     if (len < 0) {
161         error_setg_errno(errp, -len, "Failed to get size of '%s'",
162                          bdrv_get_device_or_node_name(bs));
163         return len;
164     }
165 
166     if (granularity_bits > BME_MAX_GRANULARITY_BITS) {
167         error_setg(errp, "Granularity exceeds maximum (%llu bytes)",
168                    1ULL << BME_MAX_GRANULARITY_BITS);
169         return -EINVAL;
170     }
171     if (granularity_bits < BME_MIN_GRANULARITY_BITS) {
172         error_setg(errp, "Granularity is under minimum (%llu bytes)",
173                    1ULL << BME_MIN_GRANULARITY_BITS);
174         return -EINVAL;
175     }
176 
177     if ((len > (uint64_t)BME_MAX_PHYS_SIZE << granularity_bits) ||
178         (len > (uint64_t)BME_MAX_TABLE_SIZE * s->cluster_size <<
179                granularity_bits))
180     {
181         error_setg(errp, "Too much space will be occupied by the bitmap. "
182                    "Use larger granularity");
183         return -EINVAL;
184     }
185 
186     if (strlen(name) > BME_MAX_NAME_SIZE) {
187         error_setg(errp, "Name length exceeds maximum (%u characters)",
188                    BME_MAX_NAME_SIZE);
189         return -EINVAL;
190     }
191 
192     return 0;
193 }
194 
195 static void clear_bitmap_table(BlockDriverState *bs, uint64_t *bitmap_table,
196                                uint32_t bitmap_table_size)
197 {
198     BDRVQcow2State *s = bs->opaque;
199     int i;
200 
201     for (i = 0; i < bitmap_table_size; ++i) {
202         uint64_t addr = bitmap_table[i] & BME_TABLE_ENTRY_OFFSET_MASK;
203         if (!addr) {
204             continue;
205         }
206 
207         qcow2_free_clusters(bs, addr, s->cluster_size, QCOW2_DISCARD_OTHER);
208         bitmap_table[i] = 0;
209     }
210 }
211 
212 static int bitmap_table_load(BlockDriverState *bs, Qcow2BitmapTable *tb,
213                              uint64_t **bitmap_table)
214 {
215     int ret;
216     BDRVQcow2State *s = bs->opaque;
217     uint32_t i;
218     uint64_t *table;
219 
220     assert(tb->size != 0);
221     table = g_try_new(uint64_t, tb->size);
222     if (table == NULL) {
223         return -ENOMEM;
224     }
225 
226     assert(tb->size <= BME_MAX_TABLE_SIZE);
227     ret = bdrv_pread(bs->file, tb->offset,
228                      table, tb->size * sizeof(uint64_t));
229     if (ret < 0) {
230         goto fail;
231     }
232 
233     for (i = 0; i < tb->size; ++i) {
234         be64_to_cpus(&table[i]);
235         ret = check_table_entry(table[i], s->cluster_size);
236         if (ret < 0) {
237             goto fail;
238         }
239     }
240 
241     *bitmap_table = table;
242     return 0;
243 
244 fail:
245     g_free(table);
246 
247     return ret;
248 }
249 
250 static int free_bitmap_clusters(BlockDriverState *bs, Qcow2BitmapTable *tb)
251 {
252     int ret;
253     uint64_t *bitmap_table;
254 
255     ret = bitmap_table_load(bs, tb, &bitmap_table);
256     if (ret < 0) {
257         assert(bitmap_table == NULL);
258         return ret;
259     }
260 
261     clear_bitmap_table(bs, bitmap_table, tb->size);
262     qcow2_free_clusters(bs, tb->offset, tb->size * sizeof(uint64_t),
263                         QCOW2_DISCARD_OTHER);
264     g_free(bitmap_table);
265 
266     tb->offset = 0;
267     tb->size = 0;
268 
269     return 0;
270 }
271 
272 /* This function returns the number of disk sectors covered by a single qcow2
273  * cluster of bitmap data. */
274 static uint64_t sectors_covered_by_bitmap_cluster(const BDRVQcow2State *s,
275                                                   const BdrvDirtyBitmap *bitmap)
276 {
277     uint32_t sector_granularity =
278             bdrv_dirty_bitmap_granularity(bitmap) >> BDRV_SECTOR_BITS;
279 
280     return (uint64_t)sector_granularity * (s->cluster_size << 3);
281 }
282 
283 /* load_bitmap_data
284  * @bitmap_table entries must satisfy specification constraints.
285  * @bitmap must be cleared */
286 static int load_bitmap_data(BlockDriverState *bs,
287                             const uint64_t *bitmap_table,
288                             uint32_t bitmap_table_size,
289                             BdrvDirtyBitmap *bitmap)
290 {
291     int ret = 0;
292     BDRVQcow2State *s = bs->opaque;
293     uint64_t sector, sbc;
294     uint64_t bm_size = bdrv_dirty_bitmap_size(bitmap);
295     uint8_t *buf = NULL;
296     uint64_t i, tab_size =
297             size_to_clusters(s,
298                 bdrv_dirty_bitmap_serialization_size(bitmap, 0, bm_size));
299 
300     if (tab_size != bitmap_table_size || tab_size > BME_MAX_TABLE_SIZE) {
301         return -EINVAL;
302     }
303 
304     buf = g_malloc(s->cluster_size);
305     sbc = sectors_covered_by_bitmap_cluster(s, bitmap);
306     for (i = 0, sector = 0; i < tab_size; ++i, sector += sbc) {
307         uint64_t count = MIN(bm_size - sector, sbc);
308         uint64_t entry = bitmap_table[i];
309         uint64_t offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
310 
311         assert(check_table_entry(entry, s->cluster_size) == 0);
312 
313         if (offset == 0) {
314             if (entry & BME_TABLE_ENTRY_FLAG_ALL_ONES) {
315                 bdrv_dirty_bitmap_deserialize_ones(bitmap, sector, count,
316                                                    false);
317             } else {
318                 /* No need to deserialize zeros because the dirty bitmap is
319                  * already cleared */
320             }
321         } else {
322             ret = bdrv_pread(bs->file, offset, buf, s->cluster_size);
323             if (ret < 0) {
324                 goto finish;
325             }
326             bdrv_dirty_bitmap_deserialize_part(bitmap, buf, sector, count,
327                                                false);
328         }
329     }
330     ret = 0;
331 
332     bdrv_dirty_bitmap_deserialize_finish(bitmap);
333 
334 finish:
335     g_free(buf);
336 
337     return ret;
338 }
339 
340 static BdrvDirtyBitmap *load_bitmap(BlockDriverState *bs,
341                                     Qcow2Bitmap *bm, Error **errp)
342 {
343     int ret;
344     uint64_t *bitmap_table = NULL;
345     uint32_t granularity;
346     BdrvDirtyBitmap *bitmap = NULL;
347 
348     if (bm->flags & BME_FLAG_IN_USE) {
349         error_setg(errp, "Bitmap '%s' is in use", bm->name);
350         goto fail;
351     }
352 
353     ret = bitmap_table_load(bs, &bm->table, &bitmap_table);
354     if (ret < 0) {
355         error_setg_errno(errp, -ret,
356                          "Could not read bitmap_table table from image for "
357                          "bitmap '%s'", bm->name);
358         goto fail;
359     }
360 
361     granularity = 1U << bm->granularity_bits;
362     bitmap = bdrv_create_dirty_bitmap(bs, granularity, bm->name, errp);
363     if (bitmap == NULL) {
364         goto fail;
365     }
366 
367     ret = load_bitmap_data(bs, bitmap_table, bm->table.size, bitmap);
368     if (ret < 0) {
369         error_setg_errno(errp, -ret, "Could not read bitmap '%s' from image",
370                          bm->name);
371         goto fail;
372     }
373 
374     g_free(bitmap_table);
375     return bitmap;
376 
377 fail:
378     g_free(bitmap_table);
379     if (bitmap != NULL) {
380         bdrv_release_dirty_bitmap(bs, bitmap);
381     }
382 
383     return NULL;
384 }
385 
386 /*
387  * Bitmap List
388  */
389 
390 /*
391  * Bitmap List private functions
392  * Only Bitmap List knows about bitmap directory structure in Qcow2.
393  */
394 
395 static inline void bitmap_dir_entry_to_cpu(Qcow2BitmapDirEntry *entry)
396 {
397     be64_to_cpus(&entry->bitmap_table_offset);
398     be32_to_cpus(&entry->bitmap_table_size);
399     be32_to_cpus(&entry->flags);
400     be16_to_cpus(&entry->name_size);
401     be32_to_cpus(&entry->extra_data_size);
402 }
403 
404 static inline void bitmap_dir_entry_to_be(Qcow2BitmapDirEntry *entry)
405 {
406     cpu_to_be64s(&entry->bitmap_table_offset);
407     cpu_to_be32s(&entry->bitmap_table_size);
408     cpu_to_be32s(&entry->flags);
409     cpu_to_be16s(&entry->name_size);
410     cpu_to_be32s(&entry->extra_data_size);
411 }
412 
413 static inline int calc_dir_entry_size(size_t name_size, size_t extra_data_size)
414 {
415     return align_offset(sizeof(Qcow2BitmapDirEntry) +
416                         name_size + extra_data_size, 8);
417 }
418 
419 static inline int dir_entry_size(Qcow2BitmapDirEntry *entry)
420 {
421     return calc_dir_entry_size(entry->name_size, entry->extra_data_size);
422 }
423 
424 static inline const char *dir_entry_name_field(Qcow2BitmapDirEntry *entry)
425 {
426     return (const char *)(entry + 1) + entry->extra_data_size;
427 }
428 
429 static inline char *dir_entry_copy_name(Qcow2BitmapDirEntry *entry)
430 {
431     const char *name_field = dir_entry_name_field(entry);
432     return g_strndup(name_field, entry->name_size);
433 }
434 
435 static inline Qcow2BitmapDirEntry *next_dir_entry(Qcow2BitmapDirEntry *entry)
436 {
437     return (Qcow2BitmapDirEntry *)((uint8_t *)entry + dir_entry_size(entry));
438 }
439 
440 static int check_dir_entry(BlockDriverState *bs, Qcow2BitmapDirEntry *entry)
441 {
442     BDRVQcow2State *s = bs->opaque;
443     uint64_t phys_bitmap_bytes;
444     int64_t len;
445 
446     bool fail = (entry->bitmap_table_size == 0) ||
447                 (entry->bitmap_table_offset == 0) ||
448                 (entry->bitmap_table_offset % s->cluster_size) ||
449                 (entry->bitmap_table_size > BME_MAX_TABLE_SIZE) ||
450                 (entry->granularity_bits > BME_MAX_GRANULARITY_BITS) ||
451                 (entry->granularity_bits < BME_MIN_GRANULARITY_BITS) ||
452                 (entry->flags & BME_RESERVED_FLAGS) ||
453                 (entry->name_size > BME_MAX_NAME_SIZE) ||
454                 (entry->type != BT_DIRTY_TRACKING_BITMAP);
455 
456     if (fail) {
457         return -EINVAL;
458     }
459 
460     phys_bitmap_bytes = (uint64_t)entry->bitmap_table_size * s->cluster_size;
461     len = bdrv_getlength(bs);
462 
463     if (len < 0) {
464         return len;
465     }
466 
467     fail = (phys_bitmap_bytes > BME_MAX_PHYS_SIZE) ||
468            (len > ((phys_bitmap_bytes * 8) << entry->granularity_bits));
469 
470     return fail ? -EINVAL : 0;
471 }
472 
473 static inline void bitmap_directory_to_be(uint8_t *dir, size_t size)
474 {
475     uint8_t *end = dir + size;
476     while (dir < end) {
477         Qcow2BitmapDirEntry *e = (Qcow2BitmapDirEntry *)dir;
478         dir += dir_entry_size(e);
479 
480         bitmap_dir_entry_to_be(e);
481     }
482 }
483 
484 /*
485  * Bitmap List public functions
486  */
487 
488 static void bitmap_free(Qcow2Bitmap *bm)
489 {
490     g_free(bm->name);
491     g_free(bm);
492 }
493 
494 static void bitmap_list_free(Qcow2BitmapList *bm_list)
495 {
496     Qcow2Bitmap *bm;
497 
498     if (bm_list == NULL) {
499         return;
500     }
501 
502     while ((bm = QSIMPLEQ_FIRST(bm_list)) != NULL) {
503         QSIMPLEQ_REMOVE_HEAD(bm_list, entry);
504         bitmap_free(bm);
505     }
506 
507     g_free(bm_list);
508 }
509 
510 static Qcow2BitmapList *bitmap_list_new(void)
511 {
512     Qcow2BitmapList *bm_list = g_new(Qcow2BitmapList, 1);
513     QSIMPLEQ_INIT(bm_list);
514 
515     return bm_list;
516 }
517 
518 static uint32_t bitmap_list_count(Qcow2BitmapList *bm_list)
519 {
520     Qcow2Bitmap *bm;
521     uint32_t nb_bitmaps = 0;
522 
523     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
524         nb_bitmaps++;
525     }
526 
527     return nb_bitmaps;
528 }
529 
530 /* bitmap_list_load
531  * Get bitmap list from qcow2 image. Actually reads bitmap directory,
532  * checks it and convert to bitmap list.
533  */
534 static Qcow2BitmapList *bitmap_list_load(BlockDriverState *bs, uint64_t offset,
535                                          uint64_t size, Error **errp)
536 {
537     int ret;
538     BDRVQcow2State *s = bs->opaque;
539     uint8_t *dir, *dir_end;
540     Qcow2BitmapDirEntry *e;
541     uint32_t nb_dir_entries = 0;
542     Qcow2BitmapList *bm_list = NULL;
543 
544     if (size == 0) {
545         error_setg(errp, "Requested bitmap directory size is zero");
546         return NULL;
547     }
548 
549     if (size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
550         error_setg(errp, "Requested bitmap directory size is too big");
551         return NULL;
552     }
553 
554     dir = g_try_malloc(size);
555     if (dir == NULL) {
556         error_setg(errp, "Failed to allocate space for bitmap directory");
557         return NULL;
558     }
559     dir_end = dir + size;
560 
561     ret = bdrv_pread(bs->file, offset, dir, size);
562     if (ret < 0) {
563         error_setg_errno(errp, -ret, "Failed to read bitmap directory");
564         goto fail;
565     }
566 
567     bm_list = bitmap_list_new();
568     for (e = (Qcow2BitmapDirEntry *)dir;
569          e < (Qcow2BitmapDirEntry *)dir_end;
570          e = next_dir_entry(e))
571     {
572         Qcow2Bitmap *bm;
573 
574         if ((uint8_t *)(e + 1) > dir_end) {
575             goto broken_dir;
576         }
577 
578         if (++nb_dir_entries > s->nb_bitmaps) {
579             error_setg(errp, "More bitmaps found than specified in header"
580                        " extension");
581             goto fail;
582         }
583         bitmap_dir_entry_to_cpu(e);
584 
585         if ((uint8_t *)next_dir_entry(e) > dir_end) {
586             goto broken_dir;
587         }
588 
589         if (e->extra_data_size != 0) {
590             error_setg(errp, "Bitmap extra data is not supported");
591             goto fail;
592         }
593 
594         ret = check_dir_entry(bs, e);
595         if (ret < 0) {
596             error_setg(errp, "Bitmap '%.*s' doesn't satisfy the constraints",
597                        e->name_size, dir_entry_name_field(e));
598             goto fail;
599         }
600 
601         bm = g_new(Qcow2Bitmap, 1);
602         bm->table.offset = e->bitmap_table_offset;
603         bm->table.size = e->bitmap_table_size;
604         bm->flags = e->flags;
605         bm->granularity_bits = e->granularity_bits;
606         bm->name = dir_entry_copy_name(e);
607         QSIMPLEQ_INSERT_TAIL(bm_list, bm, entry);
608     }
609 
610     if (nb_dir_entries != s->nb_bitmaps) {
611         error_setg(errp, "Less bitmaps found than specified in header"
612                          " extension");
613         goto fail;
614     }
615 
616     if ((uint8_t *)e != dir_end) {
617         goto broken_dir;
618     }
619 
620     g_free(dir);
621     return bm_list;
622 
623 broken_dir:
624     ret = -EINVAL;
625     error_setg(errp, "Broken bitmap directory");
626 
627 fail:
628     g_free(dir);
629     bitmap_list_free(bm_list);
630 
631     return NULL;
632 }
633 
634 int qcow2_check_bitmaps_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
635                                   void **refcount_table,
636                                   int64_t *refcount_table_size)
637 {
638     int ret;
639     BDRVQcow2State *s = bs->opaque;
640     Qcow2BitmapList *bm_list;
641     Qcow2Bitmap *bm;
642 
643     if (s->nb_bitmaps == 0) {
644         return 0;
645     }
646 
647     ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, refcount_table_size,
648                                    s->bitmap_directory_offset,
649                                    s->bitmap_directory_size);
650     if (ret < 0) {
651         return ret;
652     }
653 
654     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
655                                s->bitmap_directory_size, NULL);
656     if (bm_list == NULL) {
657         res->corruptions++;
658         return -EINVAL;
659     }
660 
661     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
662         uint64_t *bitmap_table = NULL;
663         int i;
664 
665         ret = qcow2_inc_refcounts_imrt(bs, res,
666                                        refcount_table, refcount_table_size,
667                                        bm->table.offset,
668                                        bm->table.size * sizeof(uint64_t));
669         if (ret < 0) {
670             goto out;
671         }
672 
673         ret = bitmap_table_load(bs, &bm->table, &bitmap_table);
674         if (ret < 0) {
675             res->corruptions++;
676             goto out;
677         }
678 
679         for (i = 0; i < bm->table.size; ++i) {
680             uint64_t entry = bitmap_table[i];
681             uint64_t offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
682 
683             if (check_table_entry(entry, s->cluster_size) < 0) {
684                 res->corruptions++;
685                 continue;
686             }
687 
688             if (offset == 0) {
689                 continue;
690             }
691 
692             ret = qcow2_inc_refcounts_imrt(bs, res,
693                                            refcount_table, refcount_table_size,
694                                            offset, s->cluster_size);
695             if (ret < 0) {
696                 g_free(bitmap_table);
697                 goto out;
698             }
699         }
700 
701         g_free(bitmap_table);
702     }
703 
704 out:
705     bitmap_list_free(bm_list);
706 
707     return ret;
708 }
709 
710 /* bitmap_list_store
711  * Store bitmap list to qcow2 image as a bitmap directory.
712  * Everything is checked.
713  */
714 static int bitmap_list_store(BlockDriverState *bs, Qcow2BitmapList *bm_list,
715                              uint64_t *offset, uint64_t *size, bool in_place)
716 {
717     int ret;
718     uint8_t *dir;
719     int64_t dir_offset = 0;
720     uint64_t dir_size = 0;
721     Qcow2Bitmap *bm;
722     Qcow2BitmapDirEntry *e;
723 
724     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
725         dir_size += calc_dir_entry_size(strlen(bm->name), 0);
726     }
727 
728     if (dir_size == 0 || dir_size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
729         return -EINVAL;
730     }
731 
732     if (in_place) {
733         if (*size != dir_size || *offset == 0) {
734             return -EINVAL;
735         }
736 
737         dir_offset = *offset;
738     }
739 
740     dir = g_try_malloc(dir_size);
741     if (dir == NULL) {
742         return -ENOMEM;
743     }
744 
745     e = (Qcow2BitmapDirEntry *)dir;
746     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
747         e->bitmap_table_offset = bm->table.offset;
748         e->bitmap_table_size = bm->table.size;
749         e->flags = bm->flags;
750         e->type = BT_DIRTY_TRACKING_BITMAP;
751         e->granularity_bits = bm->granularity_bits;
752         e->name_size = strlen(bm->name);
753         e->extra_data_size = 0;
754         memcpy(e + 1, bm->name, e->name_size);
755 
756         if (check_dir_entry(bs, e) < 0) {
757             ret = -EINVAL;
758             goto fail;
759         }
760 
761         e = next_dir_entry(e);
762     }
763 
764     bitmap_directory_to_be(dir, dir_size);
765 
766     if (!in_place) {
767         dir_offset = qcow2_alloc_clusters(bs, dir_size);
768         if (dir_offset < 0) {
769             ret = dir_offset;
770             goto fail;
771         }
772     }
773 
774     ret = qcow2_pre_write_overlap_check(bs, 0, dir_offset, dir_size);
775     if (ret < 0) {
776         goto fail;
777     }
778 
779     ret = bdrv_pwrite(bs->file, dir_offset, dir, dir_size);
780     if (ret < 0) {
781         goto fail;
782     }
783 
784     g_free(dir);
785 
786     if (!in_place) {
787         *size = dir_size;
788         *offset = dir_offset;
789     }
790 
791     return 0;
792 
793 fail:
794     g_free(dir);
795 
796     if (!in_place && dir_offset > 0) {
797         qcow2_free_clusters(bs, dir_offset, dir_size, QCOW2_DISCARD_OTHER);
798     }
799 
800     return ret;
801 }
802 
803 /*
804  * Bitmap List end
805  */
806 
807 static int update_ext_header_and_dir_in_place(BlockDriverState *bs,
808                                               Qcow2BitmapList *bm_list)
809 {
810     BDRVQcow2State *s = bs->opaque;
811     int ret;
812 
813     if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS) ||
814         bm_list == NULL || QSIMPLEQ_EMPTY(bm_list) ||
815         bitmap_list_count(bm_list) != s->nb_bitmaps)
816     {
817         return -EINVAL;
818     }
819 
820     s->autoclear_features &= ~(uint64_t)QCOW2_AUTOCLEAR_BITMAPS;
821     ret = update_header_sync(bs);
822     if (ret < 0) {
823         /* Two variants are possible here:
824          * 1. Autoclear flag is dropped, all bitmaps will be lost.
825          * 2. Autoclear flag is not dropped, old state is left.
826          */
827         return ret;
828     }
829 
830     /* autoclear bit is not set, so we can safely update bitmap directory */
831 
832     ret = bitmap_list_store(bs, bm_list, &s->bitmap_directory_offset,
833                             &s->bitmap_directory_size, true);
834     if (ret < 0) {
835         /* autoclear bit is cleared, so all leaked clusters would be removed on
836          * qemu-img check */
837         return ret;
838     }
839 
840     ret = update_header_sync(bs);
841     if (ret < 0) {
842         /* autoclear bit is cleared, so all leaked clusters would be removed on
843          * qemu-img check */
844         return ret;
845     }
846 
847     s->autoclear_features |= QCOW2_AUTOCLEAR_BITMAPS;
848     return update_header_sync(bs);
849     /* If final update_header_sync() fails, two variants are possible:
850      * 1. Autoclear flag is not set, all bitmaps will be lost.
851      * 2. Autoclear flag is set, header and directory are successfully updated.
852      */
853 }
854 
855 static int update_ext_header_and_dir(BlockDriverState *bs,
856                                      Qcow2BitmapList *bm_list)
857 {
858     BDRVQcow2State *s = bs->opaque;
859     int ret;
860     uint64_t new_offset = 0;
861     uint64_t new_size = 0;
862     uint32_t new_nb_bitmaps = 0;
863     uint64_t old_offset = s->bitmap_directory_offset;
864     uint64_t old_size = s->bitmap_directory_size;
865     uint32_t old_nb_bitmaps = s->nb_bitmaps;
866     uint64_t old_autocl = s->autoclear_features;
867 
868     if (bm_list != NULL && !QSIMPLEQ_EMPTY(bm_list)) {
869         new_nb_bitmaps = bitmap_list_count(bm_list);
870 
871         if (new_nb_bitmaps > QCOW2_MAX_BITMAPS) {
872             return -EINVAL;
873         }
874 
875         ret = bitmap_list_store(bs, bm_list, &new_offset, &new_size, false);
876         if (ret < 0) {
877             return ret;
878         }
879 
880         ret = bdrv_flush(bs->file->bs);
881         if (ret < 0) {
882             goto fail;
883         }
884 
885         s->autoclear_features |= QCOW2_AUTOCLEAR_BITMAPS;
886     } else {
887         s->autoclear_features &= ~(uint64_t)QCOW2_AUTOCLEAR_BITMAPS;
888     }
889 
890     s->bitmap_directory_offset = new_offset;
891     s->bitmap_directory_size = new_size;
892     s->nb_bitmaps = new_nb_bitmaps;
893 
894     ret = update_header_sync(bs);
895     if (ret < 0) {
896         goto fail;
897     }
898 
899     if (old_size > 0) {
900         qcow2_free_clusters(bs, old_offset, old_size, QCOW2_DISCARD_OTHER);
901     }
902 
903     return 0;
904 
905 fail:
906     if (new_offset > 0) {
907         qcow2_free_clusters(bs, new_offset, new_size, QCOW2_DISCARD_OTHER);
908     }
909 
910     s->bitmap_directory_offset = old_offset;
911     s->bitmap_directory_size = old_size;
912     s->nb_bitmaps = old_nb_bitmaps;
913     s->autoclear_features = old_autocl;
914 
915     return ret;
916 }
917 
918 /* for g_slist_foreach for GSList of BdrvDirtyBitmap* elements */
919 static void release_dirty_bitmap_helper(gpointer bitmap,
920                                         gpointer bs)
921 {
922     bdrv_release_dirty_bitmap(bs, bitmap);
923 }
924 
925 /* for g_slist_foreach for GSList of BdrvDirtyBitmap* elements */
926 static void set_readonly_helper(gpointer bitmap, gpointer value)
927 {
928     bdrv_dirty_bitmap_set_readonly(bitmap, (bool)value);
929 }
930 
931 /* qcow2_load_autoloading_dirty_bitmaps()
932  * Return value is a hint for caller: true means that the Qcow2 header was
933  * updated. (false doesn't mean that the header should be updated by the
934  * caller, it just means that updating was not needed or the image cannot be
935  * written to).
936  * On failure the function returns false.
937  */
938 bool qcow2_load_autoloading_dirty_bitmaps(BlockDriverState *bs, Error **errp)
939 {
940     BDRVQcow2State *s = bs->opaque;
941     Qcow2BitmapList *bm_list;
942     Qcow2Bitmap *bm;
943     GSList *created_dirty_bitmaps = NULL;
944     bool header_updated = false;
945 
946     if (s->nb_bitmaps == 0) {
947         /* No bitmaps - nothing to do */
948         return false;
949     }
950 
951     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
952                                s->bitmap_directory_size, errp);
953     if (bm_list == NULL) {
954         return false;
955     }
956 
957     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
958         if ((bm->flags & BME_FLAG_AUTO) && !(bm->flags & BME_FLAG_IN_USE)) {
959             BdrvDirtyBitmap *bitmap = load_bitmap(bs, bm, errp);
960             if (bitmap == NULL) {
961                 goto fail;
962             }
963 
964             bdrv_dirty_bitmap_set_persistance(bitmap, true);
965             bdrv_dirty_bitmap_set_autoload(bitmap, true);
966             bm->flags |= BME_FLAG_IN_USE;
967             created_dirty_bitmaps =
968                     g_slist_append(created_dirty_bitmaps, bitmap);
969         }
970     }
971 
972     if (created_dirty_bitmaps != NULL) {
973         if (can_write(bs)) {
974             /* in_use flags must be updated */
975             int ret = update_ext_header_and_dir_in_place(bs, bm_list);
976             if (ret < 0) {
977                 error_setg_errno(errp, -ret, "Can't update bitmap directory");
978                 goto fail;
979             }
980             header_updated = true;
981         } else {
982             g_slist_foreach(created_dirty_bitmaps, set_readonly_helper,
983                             (gpointer)true);
984         }
985     }
986 
987     g_slist_free(created_dirty_bitmaps);
988     bitmap_list_free(bm_list);
989 
990     return header_updated;
991 
992 fail:
993     g_slist_foreach(created_dirty_bitmaps, release_dirty_bitmap_helper, bs);
994     g_slist_free(created_dirty_bitmaps);
995     bitmap_list_free(bm_list);
996 
997     return false;
998 }
999 
1000 int qcow2_reopen_bitmaps_rw(BlockDriverState *bs, Error **errp)
1001 {
1002     BDRVQcow2State *s = bs->opaque;
1003     Qcow2BitmapList *bm_list;
1004     Qcow2Bitmap *bm;
1005     GSList *ro_dirty_bitmaps = NULL;
1006     int ret = 0;
1007 
1008     if (s->nb_bitmaps == 0) {
1009         /* No bitmaps - nothing to do */
1010         return 0;
1011     }
1012 
1013     if (!can_write(bs)) {
1014         error_setg(errp, "Can't write to the image on reopening bitmaps rw");
1015         return -EINVAL;
1016     }
1017 
1018     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1019                                s->bitmap_directory_size, errp);
1020     if (bm_list == NULL) {
1021         return -EINVAL;
1022     }
1023 
1024     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1025         if (!(bm->flags & BME_FLAG_IN_USE)) {
1026             BdrvDirtyBitmap *bitmap = bdrv_find_dirty_bitmap(bs, bm->name);
1027             if (bitmap == NULL) {
1028                 continue;
1029             }
1030 
1031             if (!bdrv_dirty_bitmap_readonly(bitmap)) {
1032                 error_setg(errp, "Bitmap %s is not readonly but not marked"
1033                                  "'IN_USE' in the image. Something went wrong,"
1034                                  "all the bitmaps may be corrupted", bm->name);
1035                 ret = -EINVAL;
1036                 goto out;
1037             }
1038 
1039             bm->flags |= BME_FLAG_IN_USE;
1040             ro_dirty_bitmaps = g_slist_append(ro_dirty_bitmaps, bitmap);
1041         }
1042     }
1043 
1044     if (ro_dirty_bitmaps != NULL) {
1045         /* in_use flags must be updated */
1046         ret = update_ext_header_and_dir_in_place(bs, bm_list);
1047         if (ret < 0) {
1048             error_setg_errno(errp, -ret, "Can't update bitmap directory");
1049             goto out;
1050         }
1051         g_slist_foreach(ro_dirty_bitmaps, set_readonly_helper, false);
1052     }
1053 
1054 out:
1055     g_slist_free(ro_dirty_bitmaps);
1056     bitmap_list_free(bm_list);
1057 
1058     return ret;
1059 }
1060 
1061 /* store_bitmap_data()
1062  * Store bitmap to image, filling bitmap table accordingly.
1063  */
1064 static uint64_t *store_bitmap_data(BlockDriverState *bs,
1065                                    BdrvDirtyBitmap *bitmap,
1066                                    uint32_t *bitmap_table_size, Error **errp)
1067 {
1068     int ret;
1069     BDRVQcow2State *s = bs->opaque;
1070     int64_t sector;
1071     uint64_t sbc;
1072     uint64_t bm_size = bdrv_dirty_bitmap_size(bitmap);
1073     const char *bm_name = bdrv_dirty_bitmap_name(bitmap);
1074     uint8_t *buf = NULL;
1075     BdrvDirtyBitmapIter *dbi;
1076     uint64_t *tb;
1077     uint64_t tb_size =
1078             size_to_clusters(s,
1079                 bdrv_dirty_bitmap_serialization_size(bitmap, 0, bm_size));
1080 
1081     if (tb_size > BME_MAX_TABLE_SIZE ||
1082         tb_size * s->cluster_size > BME_MAX_PHYS_SIZE)
1083     {
1084         error_setg(errp, "Bitmap '%s' is too big", bm_name);
1085         return NULL;
1086     }
1087 
1088     tb = g_try_new0(uint64_t, tb_size);
1089     if (tb == NULL) {
1090         error_setg(errp, "No memory");
1091         return NULL;
1092     }
1093 
1094     dbi = bdrv_dirty_iter_new(bitmap, 0);
1095     buf = g_malloc(s->cluster_size);
1096     sbc = sectors_covered_by_bitmap_cluster(s, bitmap);
1097     assert(DIV_ROUND_UP(bm_size, sbc) == tb_size);
1098 
1099     while ((sector = bdrv_dirty_iter_next(dbi)) != -1) {
1100         uint64_t cluster = sector / sbc;
1101         uint64_t end, write_size;
1102         int64_t off;
1103 
1104         sector = cluster * sbc;
1105         end = MIN(bm_size, sector + sbc);
1106         write_size =
1107             bdrv_dirty_bitmap_serialization_size(bitmap, sector, end - sector);
1108         assert(write_size <= s->cluster_size);
1109 
1110         off = qcow2_alloc_clusters(bs, s->cluster_size);
1111         if (off < 0) {
1112             error_setg_errno(errp, -off,
1113                              "Failed to allocate clusters for bitmap '%s'",
1114                              bm_name);
1115             goto fail;
1116         }
1117         tb[cluster] = off;
1118 
1119         bdrv_dirty_bitmap_serialize_part(bitmap, buf, sector, end - sector);
1120         if (write_size < s->cluster_size) {
1121             memset(buf + write_size, 0, s->cluster_size - write_size);
1122         }
1123 
1124         ret = qcow2_pre_write_overlap_check(bs, 0, off, s->cluster_size);
1125         if (ret < 0) {
1126             error_setg_errno(errp, -ret, "Qcow2 overlap check failed");
1127             goto fail;
1128         }
1129 
1130         ret = bdrv_pwrite(bs->file, off, buf, s->cluster_size);
1131         if (ret < 0) {
1132             error_setg_errno(errp, -ret, "Failed to write bitmap '%s' to file",
1133                              bm_name);
1134             goto fail;
1135         }
1136 
1137         if (end >= bm_size) {
1138             break;
1139         }
1140 
1141         bdrv_set_dirty_iter(dbi, end);
1142     }
1143 
1144     *bitmap_table_size = tb_size;
1145     g_free(buf);
1146     bdrv_dirty_iter_free(dbi);
1147 
1148     return tb;
1149 
1150 fail:
1151     clear_bitmap_table(bs, tb, tb_size);
1152     g_free(buf);
1153     bdrv_dirty_iter_free(dbi);
1154     g_free(tb);
1155 
1156     return NULL;
1157 }
1158 
1159 /* store_bitmap()
1160  * Store bm->dirty_bitmap to qcow2.
1161  * Set bm->table_offset and bm->table_size accordingly.
1162  */
1163 static int store_bitmap(BlockDriverState *bs, Qcow2Bitmap *bm, Error **errp)
1164 {
1165     int ret;
1166     uint64_t *tb;
1167     int64_t tb_offset;
1168     uint32_t tb_size;
1169     BdrvDirtyBitmap *bitmap = bm->dirty_bitmap;
1170     const char *bm_name;
1171 
1172     assert(bitmap != NULL);
1173 
1174     bm_name = bdrv_dirty_bitmap_name(bitmap);
1175 
1176     tb = store_bitmap_data(bs, bitmap, &tb_size, errp);
1177     if (tb == NULL) {
1178         return -EINVAL;
1179     }
1180 
1181     assert(tb_size <= BME_MAX_TABLE_SIZE);
1182     tb_offset = qcow2_alloc_clusters(bs, tb_size * sizeof(tb[0]));
1183     if (tb_offset < 0) {
1184         error_setg_errno(errp, -tb_offset,
1185                          "Failed to allocate clusters for bitmap '%s'",
1186                          bm_name);
1187         ret = tb_offset;
1188         goto fail;
1189     }
1190 
1191     ret = qcow2_pre_write_overlap_check(bs, 0, tb_offset,
1192                                         tb_size * sizeof(tb[0]));
1193     if (ret < 0) {
1194         error_setg_errno(errp, -ret, "Qcow2 overlap check failed");
1195         goto fail;
1196     }
1197 
1198     bitmap_table_to_be(tb, tb_size);
1199     ret = bdrv_pwrite(bs->file, tb_offset, tb, tb_size * sizeof(tb[0]));
1200     if (ret < 0) {
1201         error_setg_errno(errp, -ret, "Failed to write bitmap '%s' to file",
1202                          bm_name);
1203         goto fail;
1204     }
1205 
1206     g_free(tb);
1207 
1208     bm->table.offset = tb_offset;
1209     bm->table.size = tb_size;
1210 
1211     return 0;
1212 
1213 fail:
1214     clear_bitmap_table(bs, tb, tb_size);
1215 
1216     if (tb_offset > 0) {
1217         qcow2_free_clusters(bs, tb_offset, tb_size * sizeof(tb[0]),
1218                             QCOW2_DISCARD_OTHER);
1219     }
1220 
1221     g_free(tb);
1222 
1223     return ret;
1224 }
1225 
1226 static Qcow2Bitmap *find_bitmap_by_name(Qcow2BitmapList *bm_list,
1227                                         const char *name)
1228 {
1229     Qcow2Bitmap *bm;
1230 
1231     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1232         if (strcmp(name, bm->name) == 0) {
1233             return bm;
1234         }
1235     }
1236 
1237     return NULL;
1238 }
1239 
1240 void qcow2_remove_persistent_dirty_bitmap(BlockDriverState *bs,
1241                                           const char *name,
1242                                           Error **errp)
1243 {
1244     int ret;
1245     BDRVQcow2State *s = bs->opaque;
1246     Qcow2Bitmap *bm;
1247     Qcow2BitmapList *bm_list;
1248 
1249     if (s->nb_bitmaps == 0) {
1250         /* Absence of the bitmap is not an error: see explanation above
1251          * bdrv_remove_persistent_dirty_bitmap() definition. */
1252         return;
1253     }
1254 
1255     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1256                                s->bitmap_directory_size, errp);
1257     if (bm_list == NULL) {
1258         return;
1259     }
1260 
1261     bm = find_bitmap_by_name(bm_list, name);
1262     if (bm == NULL) {
1263         goto fail;
1264     }
1265 
1266     QSIMPLEQ_REMOVE(bm_list, bm, Qcow2Bitmap, entry);
1267 
1268     ret = update_ext_header_and_dir(bs, bm_list);
1269     if (ret < 0) {
1270         error_setg_errno(errp, -ret, "Failed to update bitmap extension");
1271         goto fail;
1272     }
1273 
1274     free_bitmap_clusters(bs, &bm->table);
1275 
1276 fail:
1277     bitmap_free(bm);
1278     bitmap_list_free(bm_list);
1279 }
1280 
1281 void qcow2_store_persistent_dirty_bitmaps(BlockDriverState *bs, Error **errp)
1282 {
1283     BdrvDirtyBitmap *bitmap;
1284     BDRVQcow2State *s = bs->opaque;
1285     uint32_t new_nb_bitmaps = s->nb_bitmaps;
1286     uint64_t new_dir_size = s->bitmap_directory_size;
1287     int ret;
1288     Qcow2BitmapList *bm_list;
1289     Qcow2Bitmap *bm;
1290     Qcow2BitmapTableList drop_tables;
1291     Qcow2BitmapTable *tb, *tb_next;
1292 
1293     if (!bdrv_has_changed_persistent_bitmaps(bs)) {
1294         /* nothing to do */
1295         return;
1296     }
1297 
1298     if (!can_write(bs)) {
1299         error_setg(errp, "No write access");
1300         return;
1301     }
1302 
1303     QSIMPLEQ_INIT(&drop_tables);
1304 
1305     if (s->nb_bitmaps == 0) {
1306         bm_list = bitmap_list_new();
1307     } else {
1308         bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1309                                    s->bitmap_directory_size, errp);
1310         if (bm_list == NULL) {
1311             return;
1312         }
1313     }
1314 
1315     /* check constraints and names */
1316     for (bitmap = bdrv_dirty_bitmap_next(bs, NULL); bitmap != NULL;
1317          bitmap = bdrv_dirty_bitmap_next(bs, bitmap))
1318     {
1319         const char *name = bdrv_dirty_bitmap_name(bitmap);
1320         uint32_t granularity = bdrv_dirty_bitmap_granularity(bitmap);
1321         Qcow2Bitmap *bm;
1322 
1323         if (!bdrv_dirty_bitmap_get_persistance(bitmap) ||
1324             bdrv_dirty_bitmap_readonly(bitmap))
1325         {
1326             continue;
1327         }
1328 
1329         if (check_constraints_on_bitmap(bs, name, granularity, errp) < 0) {
1330             error_prepend(errp, "Bitmap '%s' doesn't satisfy the constraints: ",
1331                           name);
1332             goto fail;
1333         }
1334 
1335         bm = find_bitmap_by_name(bm_list, name);
1336         if (bm == NULL) {
1337             if (++new_nb_bitmaps > QCOW2_MAX_BITMAPS) {
1338                 error_setg(errp, "Too many persistent bitmaps");
1339                 goto fail;
1340             }
1341 
1342             new_dir_size += calc_dir_entry_size(strlen(name), 0);
1343             if (new_dir_size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
1344                 error_setg(errp, "Bitmap directory is too large");
1345                 goto fail;
1346             }
1347 
1348             bm = g_new0(Qcow2Bitmap, 1);
1349             bm->name = g_strdup(name);
1350             QSIMPLEQ_INSERT_TAIL(bm_list, bm, entry);
1351         } else {
1352             if (!(bm->flags & BME_FLAG_IN_USE)) {
1353                 error_setg(errp, "Bitmap '%s' already exists in the image",
1354                            name);
1355                 goto fail;
1356             }
1357             tb = g_memdup(&bm->table, sizeof(bm->table));
1358             bm->table.offset = 0;
1359             bm->table.size = 0;
1360             QSIMPLEQ_INSERT_TAIL(&drop_tables, tb, entry);
1361         }
1362         bm->flags = bdrv_dirty_bitmap_get_autoload(bitmap) ? BME_FLAG_AUTO : 0;
1363         bm->granularity_bits = ctz32(bdrv_dirty_bitmap_granularity(bitmap));
1364         bm->dirty_bitmap = bitmap;
1365     }
1366 
1367     /* allocate clusters and store bitmaps */
1368     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1369         if (bm->dirty_bitmap == NULL) {
1370             continue;
1371         }
1372 
1373         ret = store_bitmap(bs, bm, errp);
1374         if (ret < 0) {
1375             goto fail;
1376         }
1377     }
1378 
1379     ret = update_ext_header_and_dir(bs, bm_list);
1380     if (ret < 0) {
1381         error_setg_errno(errp, -ret, "Failed to update bitmap extension");
1382         goto fail;
1383     }
1384 
1385     /* Bitmap directory was successfully updated, so, old data can be dropped.
1386      * TODO it is better to reuse these clusters */
1387     QSIMPLEQ_FOREACH_SAFE(tb, &drop_tables, entry, tb_next) {
1388         free_bitmap_clusters(bs, tb);
1389         g_free(tb);
1390     }
1391 
1392     bitmap_list_free(bm_list);
1393     return;
1394 
1395 fail:
1396     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1397         if (bm->dirty_bitmap == NULL || bm->table.offset == 0) {
1398             continue;
1399         }
1400 
1401         free_bitmap_clusters(bs, &bm->table);
1402     }
1403 
1404     QSIMPLEQ_FOREACH_SAFE(tb, &drop_tables, entry, tb_next) {
1405         g_free(tb);
1406     }
1407 
1408     bitmap_list_free(bm_list);
1409 }
1410 
1411 int qcow2_reopen_bitmaps_ro(BlockDriverState *bs, Error **errp)
1412 {
1413     BdrvDirtyBitmap *bitmap;
1414     Error *local_err = NULL;
1415 
1416     qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
1417     if (local_err != NULL) {
1418         error_propagate(errp, local_err);
1419         return -EINVAL;
1420     }
1421 
1422     for (bitmap = bdrv_dirty_bitmap_next(bs, NULL); bitmap != NULL;
1423          bitmap = bdrv_dirty_bitmap_next(bs, bitmap))
1424     {
1425         if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
1426             bdrv_dirty_bitmap_set_readonly(bitmap, true);
1427         }
1428     }
1429 
1430     return 0;
1431 }
1432 
1433 bool qcow2_can_store_new_dirty_bitmap(BlockDriverState *bs,
1434                                       const char *name,
1435                                       uint32_t granularity,
1436                                       Error **errp)
1437 {
1438     BDRVQcow2State *s = bs->opaque;
1439     bool found;
1440     Qcow2BitmapList *bm_list;
1441 
1442     if (check_constraints_on_bitmap(bs, name, granularity, errp) != 0) {
1443         goto fail;
1444     }
1445 
1446     if (s->nb_bitmaps == 0) {
1447         return true;
1448     }
1449 
1450     if (s->nb_bitmaps >= QCOW2_MAX_BITMAPS) {
1451         error_setg(errp,
1452                    "Maximum number of persistent bitmaps is already reached");
1453         goto fail;
1454     }
1455 
1456     if (s->bitmap_directory_size + calc_dir_entry_size(strlen(name), 0) >
1457         QCOW2_MAX_BITMAP_DIRECTORY_SIZE)
1458     {
1459         error_setg(errp, "Not enough space in the bitmap directory");
1460         goto fail;
1461     }
1462 
1463     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1464                                s->bitmap_directory_size, errp);
1465     if (bm_list == NULL) {
1466         goto fail;
1467     }
1468 
1469     found = find_bitmap_by_name(bm_list, name);
1470     bitmap_list_free(bm_list);
1471     if (found) {
1472         error_setg(errp, "Bitmap with the same name is already stored");
1473         goto fail;
1474     }
1475 
1476     return true;
1477 
1478 fail:
1479     error_prepend(errp, "Can't make bitmap '%s' persistent in '%s': ",
1480                   name, bdrv_get_device_or_node_name(bs));
1481     return false;
1482 }
1483