xref: /openbmc/qemu/block/qcow2-bitmap.c (revision 47451466)
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 "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->file->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         return ret;
258     }
259 
260     clear_bitmap_table(bs, bitmap_table, tb->size);
261     qcow2_free_clusters(bs, tb->offset, tb->size * sizeof(uint64_t),
262                         QCOW2_DISCARD_OTHER);
263     g_free(bitmap_table);
264 
265     tb->offset = 0;
266     tb->size = 0;
267 
268     return 0;
269 }
270 
271 /* Return the disk size covered by a single qcow2 cluster of bitmap data. */
272 static uint64_t bytes_covered_by_bitmap_cluster(const BDRVQcow2State *s,
273                                                 const BdrvDirtyBitmap *bitmap)
274 {
275     uint64_t granularity = bdrv_dirty_bitmap_granularity(bitmap);
276     uint64_t limit = granularity * (s->cluster_size << 3);
277 
278     assert(QEMU_IS_ALIGNED(limit,
279                            bdrv_dirty_bitmap_serialization_align(bitmap)));
280     return limit;
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 offset, limit;
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     limit = bytes_covered_by_bitmap_cluster(s, bitmap);
306     for (i = 0, offset = 0; i < tab_size; ++i, offset += limit) {
307         uint64_t count = MIN(bm_size - offset, limit);
308         uint64_t entry = bitmap_table[i];
309         uint64_t data_offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
310 
311         assert(check_table_entry(entry, s->cluster_size) == 0);
312 
313         if (data_offset == 0) {
314             if (entry & BME_TABLE_ENTRY_FLAG_ALL_ONES) {
315                 bdrv_dirty_bitmap_deserialize_ones(bitmap, offset, 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, data_offset, buf, s->cluster_size);
323             if (ret < 0) {
324                 goto finish;
325             }
326             bdrv_dirty_bitmap_deserialize_part(bitmap, buf, offset, 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     int size = sizeof(Qcow2BitmapDirEntry) + name_size + extra_data_size;
416     return ROUND_UP(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     if (bm == NULL) {
491         return;
492     }
493 
494     g_free(bm->name);
495     g_free(bm);
496 }
497 
498 static void bitmap_list_free(Qcow2BitmapList *bm_list)
499 {
500     Qcow2Bitmap *bm;
501 
502     if (bm_list == NULL) {
503         return;
504     }
505 
506     while ((bm = QSIMPLEQ_FIRST(bm_list)) != NULL) {
507         QSIMPLEQ_REMOVE_HEAD(bm_list, entry);
508         bitmap_free(bm);
509     }
510 
511     g_free(bm_list);
512 }
513 
514 static Qcow2BitmapList *bitmap_list_new(void)
515 {
516     Qcow2BitmapList *bm_list = g_new(Qcow2BitmapList, 1);
517     QSIMPLEQ_INIT(bm_list);
518 
519     return bm_list;
520 }
521 
522 static uint32_t bitmap_list_count(Qcow2BitmapList *bm_list)
523 {
524     Qcow2Bitmap *bm;
525     uint32_t nb_bitmaps = 0;
526 
527     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
528         nb_bitmaps++;
529     }
530 
531     return nb_bitmaps;
532 }
533 
534 /* bitmap_list_load
535  * Get bitmap list from qcow2 image. Actually reads bitmap directory,
536  * checks it and convert to bitmap list.
537  */
538 static Qcow2BitmapList *bitmap_list_load(BlockDriverState *bs, uint64_t offset,
539                                          uint64_t size, Error **errp)
540 {
541     int ret;
542     BDRVQcow2State *s = bs->opaque;
543     uint8_t *dir, *dir_end;
544     Qcow2BitmapDirEntry *e;
545     uint32_t nb_dir_entries = 0;
546     Qcow2BitmapList *bm_list = NULL;
547 
548     if (size == 0) {
549         error_setg(errp, "Requested bitmap directory size is zero");
550         return NULL;
551     }
552 
553     if (size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
554         error_setg(errp, "Requested bitmap directory size is too big");
555         return NULL;
556     }
557 
558     dir = g_try_malloc(size);
559     if (dir == NULL) {
560         error_setg(errp, "Failed to allocate space for bitmap directory");
561         return NULL;
562     }
563     dir_end = dir + size;
564 
565     ret = bdrv_pread(bs->file, offset, dir, size);
566     if (ret < 0) {
567         error_setg_errno(errp, -ret, "Failed to read bitmap directory");
568         goto fail;
569     }
570 
571     bm_list = bitmap_list_new();
572     for (e = (Qcow2BitmapDirEntry *)dir;
573          e < (Qcow2BitmapDirEntry *)dir_end;
574          e = next_dir_entry(e))
575     {
576         Qcow2Bitmap *bm;
577 
578         if ((uint8_t *)(e + 1) > dir_end) {
579             goto broken_dir;
580         }
581 
582         if (++nb_dir_entries > s->nb_bitmaps) {
583             error_setg(errp, "More bitmaps found than specified in header"
584                        " extension");
585             goto fail;
586         }
587         bitmap_dir_entry_to_cpu(e);
588 
589         if ((uint8_t *)next_dir_entry(e) > dir_end) {
590             goto broken_dir;
591         }
592 
593         if (e->extra_data_size != 0) {
594             error_setg(errp, "Bitmap extra data is not supported");
595             goto fail;
596         }
597 
598         ret = check_dir_entry(bs, e);
599         if (ret < 0) {
600             error_setg(errp, "Bitmap '%.*s' doesn't satisfy the constraints",
601                        e->name_size, dir_entry_name_field(e));
602             goto fail;
603         }
604 
605         bm = g_new0(Qcow2Bitmap, 1);
606         bm->table.offset = e->bitmap_table_offset;
607         bm->table.size = e->bitmap_table_size;
608         bm->flags = e->flags;
609         bm->granularity_bits = e->granularity_bits;
610         bm->name = dir_entry_copy_name(e);
611         QSIMPLEQ_INSERT_TAIL(bm_list, bm, entry);
612     }
613 
614     if (nb_dir_entries != s->nb_bitmaps) {
615         error_setg(errp, "Less bitmaps found than specified in header"
616                          " extension");
617         goto fail;
618     }
619 
620     if ((uint8_t *)e != dir_end) {
621         goto broken_dir;
622     }
623 
624     g_free(dir);
625     return bm_list;
626 
627 broken_dir:
628     ret = -EINVAL;
629     error_setg(errp, "Broken bitmap directory");
630 
631 fail:
632     g_free(dir);
633     bitmap_list_free(bm_list);
634 
635     return NULL;
636 }
637 
638 int qcow2_check_bitmaps_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
639                                   void **refcount_table,
640                                   int64_t *refcount_table_size)
641 {
642     int ret;
643     BDRVQcow2State *s = bs->opaque;
644     Qcow2BitmapList *bm_list;
645     Qcow2Bitmap *bm;
646 
647     if (s->nb_bitmaps == 0) {
648         return 0;
649     }
650 
651     ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, refcount_table_size,
652                                    s->bitmap_directory_offset,
653                                    s->bitmap_directory_size);
654     if (ret < 0) {
655         return ret;
656     }
657 
658     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
659                                s->bitmap_directory_size, NULL);
660     if (bm_list == NULL) {
661         res->corruptions++;
662         return -EINVAL;
663     }
664 
665     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
666         uint64_t *bitmap_table = NULL;
667         int i;
668 
669         ret = qcow2_inc_refcounts_imrt(bs, res,
670                                        refcount_table, refcount_table_size,
671                                        bm->table.offset,
672                                        bm->table.size * sizeof(uint64_t));
673         if (ret < 0) {
674             goto out;
675         }
676 
677         ret = bitmap_table_load(bs, &bm->table, &bitmap_table);
678         if (ret < 0) {
679             res->corruptions++;
680             goto out;
681         }
682 
683         for (i = 0; i < bm->table.size; ++i) {
684             uint64_t entry = bitmap_table[i];
685             uint64_t offset = entry & BME_TABLE_ENTRY_OFFSET_MASK;
686 
687             if (check_table_entry(entry, s->cluster_size) < 0) {
688                 res->corruptions++;
689                 continue;
690             }
691 
692             if (offset == 0) {
693                 continue;
694             }
695 
696             ret = qcow2_inc_refcounts_imrt(bs, res,
697                                            refcount_table, refcount_table_size,
698                                            offset, s->cluster_size);
699             if (ret < 0) {
700                 g_free(bitmap_table);
701                 goto out;
702             }
703         }
704 
705         g_free(bitmap_table);
706     }
707 
708 out:
709     bitmap_list_free(bm_list);
710 
711     return ret;
712 }
713 
714 /* bitmap_list_store
715  * Store bitmap list to qcow2 image as a bitmap directory.
716  * Everything is checked.
717  */
718 static int bitmap_list_store(BlockDriverState *bs, Qcow2BitmapList *bm_list,
719                              uint64_t *offset, uint64_t *size, bool in_place)
720 {
721     int ret;
722     uint8_t *dir;
723     int64_t dir_offset = 0;
724     uint64_t dir_size = 0;
725     Qcow2Bitmap *bm;
726     Qcow2BitmapDirEntry *e;
727 
728     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
729         dir_size += calc_dir_entry_size(strlen(bm->name), 0);
730     }
731 
732     if (dir_size == 0 || dir_size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
733         return -EINVAL;
734     }
735 
736     if (in_place) {
737         if (*size != dir_size || *offset == 0) {
738             return -EINVAL;
739         }
740 
741         dir_offset = *offset;
742     }
743 
744     dir = g_try_malloc(dir_size);
745     if (dir == NULL) {
746         return -ENOMEM;
747     }
748 
749     e = (Qcow2BitmapDirEntry *)dir;
750     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
751         e->bitmap_table_offset = bm->table.offset;
752         e->bitmap_table_size = bm->table.size;
753         e->flags = bm->flags;
754         e->type = BT_DIRTY_TRACKING_BITMAP;
755         e->granularity_bits = bm->granularity_bits;
756         e->name_size = strlen(bm->name);
757         e->extra_data_size = 0;
758         memcpy(e + 1, bm->name, e->name_size);
759 
760         if (check_dir_entry(bs, e) < 0) {
761             ret = -EINVAL;
762             goto fail;
763         }
764 
765         e = next_dir_entry(e);
766     }
767 
768     bitmap_directory_to_be(dir, dir_size);
769 
770     if (!in_place) {
771         dir_offset = qcow2_alloc_clusters(bs, dir_size);
772         if (dir_offset < 0) {
773             ret = dir_offset;
774             goto fail;
775         }
776     }
777 
778     ret = qcow2_pre_write_overlap_check(bs, 0, dir_offset, dir_size);
779     if (ret < 0) {
780         goto fail;
781     }
782 
783     ret = bdrv_pwrite(bs->file, dir_offset, dir, dir_size);
784     if (ret < 0) {
785         goto fail;
786     }
787 
788     g_free(dir);
789 
790     if (!in_place) {
791         *size = dir_size;
792         *offset = dir_offset;
793     }
794 
795     return 0;
796 
797 fail:
798     g_free(dir);
799 
800     if (!in_place && dir_offset > 0) {
801         qcow2_free_clusters(bs, dir_offset, dir_size, QCOW2_DISCARD_OTHER);
802     }
803 
804     return ret;
805 }
806 
807 /*
808  * Bitmap List end
809  */
810 
811 static int update_ext_header_and_dir_in_place(BlockDriverState *bs,
812                                               Qcow2BitmapList *bm_list)
813 {
814     BDRVQcow2State *s = bs->opaque;
815     int ret;
816 
817     if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS) ||
818         bm_list == NULL || QSIMPLEQ_EMPTY(bm_list) ||
819         bitmap_list_count(bm_list) != s->nb_bitmaps)
820     {
821         return -EINVAL;
822     }
823 
824     s->autoclear_features &= ~(uint64_t)QCOW2_AUTOCLEAR_BITMAPS;
825     ret = update_header_sync(bs);
826     if (ret < 0) {
827         /* Two variants are possible here:
828          * 1. Autoclear flag is dropped, all bitmaps will be lost.
829          * 2. Autoclear flag is not dropped, old state is left.
830          */
831         return ret;
832     }
833 
834     /* autoclear bit is not set, so we can safely update bitmap directory */
835 
836     ret = bitmap_list_store(bs, bm_list, &s->bitmap_directory_offset,
837                             &s->bitmap_directory_size, true);
838     if (ret < 0) {
839         /* autoclear bit is cleared, so all leaked clusters would be removed on
840          * qemu-img check */
841         return ret;
842     }
843 
844     ret = update_header_sync(bs);
845     if (ret < 0) {
846         /* autoclear bit is cleared, so all leaked clusters would be removed on
847          * qemu-img check */
848         return ret;
849     }
850 
851     s->autoclear_features |= QCOW2_AUTOCLEAR_BITMAPS;
852     return update_header_sync(bs);
853     /* If final update_header_sync() fails, two variants are possible:
854      * 1. Autoclear flag is not set, all bitmaps will be lost.
855      * 2. Autoclear flag is set, header and directory are successfully updated.
856      */
857 }
858 
859 static int update_ext_header_and_dir(BlockDriverState *bs,
860                                      Qcow2BitmapList *bm_list)
861 {
862     BDRVQcow2State *s = bs->opaque;
863     int ret;
864     uint64_t new_offset = 0;
865     uint64_t new_size = 0;
866     uint32_t new_nb_bitmaps = 0;
867     uint64_t old_offset = s->bitmap_directory_offset;
868     uint64_t old_size = s->bitmap_directory_size;
869     uint32_t old_nb_bitmaps = s->nb_bitmaps;
870     uint64_t old_autocl = s->autoclear_features;
871 
872     if (bm_list != NULL && !QSIMPLEQ_EMPTY(bm_list)) {
873         new_nb_bitmaps = bitmap_list_count(bm_list);
874 
875         if (new_nb_bitmaps > QCOW2_MAX_BITMAPS) {
876             return -EINVAL;
877         }
878 
879         ret = bitmap_list_store(bs, bm_list, &new_offset, &new_size, false);
880         if (ret < 0) {
881             return ret;
882         }
883 
884         ret = qcow2_flush_caches(bs);
885         if (ret < 0) {
886             goto fail;
887         }
888 
889         s->autoclear_features |= QCOW2_AUTOCLEAR_BITMAPS;
890     } else {
891         s->autoclear_features &= ~(uint64_t)QCOW2_AUTOCLEAR_BITMAPS;
892     }
893 
894     s->bitmap_directory_offset = new_offset;
895     s->bitmap_directory_size = new_size;
896     s->nb_bitmaps = new_nb_bitmaps;
897 
898     ret = update_header_sync(bs);
899     if (ret < 0) {
900         goto fail;
901     }
902 
903     if (old_size > 0) {
904         qcow2_free_clusters(bs, old_offset, old_size, QCOW2_DISCARD_OTHER);
905     }
906 
907     return 0;
908 
909 fail:
910     if (new_offset > 0) {
911         qcow2_free_clusters(bs, new_offset, new_size, QCOW2_DISCARD_OTHER);
912     }
913 
914     s->bitmap_directory_offset = old_offset;
915     s->bitmap_directory_size = old_size;
916     s->nb_bitmaps = old_nb_bitmaps;
917     s->autoclear_features = old_autocl;
918 
919     return ret;
920 }
921 
922 /* for g_slist_foreach for GSList of BdrvDirtyBitmap* elements */
923 static void release_dirty_bitmap_helper(gpointer bitmap,
924                                         gpointer bs)
925 {
926     bdrv_release_dirty_bitmap(bs, bitmap);
927 }
928 
929 /* for g_slist_foreach for GSList of BdrvDirtyBitmap* elements */
930 static void set_readonly_helper(gpointer bitmap, gpointer value)
931 {
932     bdrv_dirty_bitmap_set_readonly(bitmap, (bool)value);
933 }
934 
935 /* qcow2_load_dirty_bitmaps()
936  * Return value is a hint for caller: true means that the Qcow2 header was
937  * updated. (false doesn't mean that the header should be updated by the
938  * caller, it just means that updating was not needed or the image cannot be
939  * written to).
940  * On failure the function returns false.
941  */
942 bool qcow2_load_dirty_bitmaps(BlockDriverState *bs, Error **errp)
943 {
944     BDRVQcow2State *s = bs->opaque;
945     Qcow2BitmapList *bm_list;
946     Qcow2Bitmap *bm;
947     GSList *created_dirty_bitmaps = NULL;
948     bool header_updated = false;
949 
950     if (s->nb_bitmaps == 0) {
951         /* No bitmaps - nothing to do */
952         return false;
953     }
954 
955     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
956                                s->bitmap_directory_size, errp);
957     if (bm_list == NULL) {
958         return false;
959     }
960 
961     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
962         if (!(bm->flags & BME_FLAG_IN_USE)) {
963             BdrvDirtyBitmap *bitmap = load_bitmap(bs, bm, errp);
964             if (bitmap == NULL) {
965                 goto fail;
966             }
967 
968             if (!(bm->flags & BME_FLAG_AUTO)) {
969                 bdrv_disable_dirty_bitmap(bitmap);
970             }
971             bdrv_dirty_bitmap_set_persistance(bitmap, true);
972             bm->flags |= BME_FLAG_IN_USE;
973             created_dirty_bitmaps =
974                     g_slist_append(created_dirty_bitmaps, bitmap);
975         }
976     }
977 
978     if (created_dirty_bitmaps != NULL) {
979         if (can_write(bs)) {
980             /* in_use flags must be updated */
981             int ret = update_ext_header_and_dir_in_place(bs, bm_list);
982             if (ret < 0) {
983                 error_setg_errno(errp, -ret, "Can't update bitmap directory");
984                 goto fail;
985             }
986             header_updated = true;
987         } else {
988             g_slist_foreach(created_dirty_bitmaps, set_readonly_helper,
989                             (gpointer)true);
990         }
991     }
992 
993     g_slist_free(created_dirty_bitmaps);
994     bitmap_list_free(bm_list);
995 
996     return header_updated;
997 
998 fail:
999     g_slist_foreach(created_dirty_bitmaps, release_dirty_bitmap_helper, bs);
1000     g_slist_free(created_dirty_bitmaps);
1001     bitmap_list_free(bm_list);
1002 
1003     return false;
1004 }
1005 
1006 int qcow2_reopen_bitmaps_rw_hint(BlockDriverState *bs, bool *header_updated,
1007                                  Error **errp)
1008 {
1009     BDRVQcow2State *s = bs->opaque;
1010     Qcow2BitmapList *bm_list;
1011     Qcow2Bitmap *bm;
1012     GSList *ro_dirty_bitmaps = NULL;
1013     int ret = 0;
1014 
1015     if (header_updated != NULL) {
1016         *header_updated = false;
1017     }
1018 
1019     if (s->nb_bitmaps == 0) {
1020         /* No bitmaps - nothing to do */
1021         return 0;
1022     }
1023 
1024     if (!can_write(bs)) {
1025         error_setg(errp, "Can't write to the image on reopening bitmaps rw");
1026         return -EINVAL;
1027     }
1028 
1029     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1030                                s->bitmap_directory_size, errp);
1031     if (bm_list == NULL) {
1032         return -EINVAL;
1033     }
1034 
1035     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1036         if (!(bm->flags & BME_FLAG_IN_USE)) {
1037             BdrvDirtyBitmap *bitmap = bdrv_find_dirty_bitmap(bs, bm->name);
1038             if (bitmap == NULL) {
1039                 continue;
1040             }
1041 
1042             if (!bdrv_dirty_bitmap_readonly(bitmap)) {
1043                 error_setg(errp, "Bitmap %s is not readonly but not marked"
1044                                  "'IN_USE' in the image. Something went wrong,"
1045                                  "all the bitmaps may be corrupted", bm->name);
1046                 ret = -EINVAL;
1047                 goto out;
1048             }
1049 
1050             bm->flags |= BME_FLAG_IN_USE;
1051             ro_dirty_bitmaps = g_slist_append(ro_dirty_bitmaps, bitmap);
1052         }
1053     }
1054 
1055     if (ro_dirty_bitmaps != NULL) {
1056         /* in_use flags must be updated */
1057         ret = update_ext_header_and_dir_in_place(bs, bm_list);
1058         if (ret < 0) {
1059             error_setg_errno(errp, -ret, "Can't update bitmap directory");
1060             goto out;
1061         }
1062         if (header_updated != NULL) {
1063             *header_updated = true;
1064         }
1065         g_slist_foreach(ro_dirty_bitmaps, set_readonly_helper, false);
1066     }
1067 
1068 out:
1069     g_slist_free(ro_dirty_bitmaps);
1070     bitmap_list_free(bm_list);
1071 
1072     return ret;
1073 }
1074 
1075 int qcow2_reopen_bitmaps_rw(BlockDriverState *bs, Error **errp)
1076 {
1077     return qcow2_reopen_bitmaps_rw_hint(bs, NULL, errp);
1078 }
1079 
1080 /* store_bitmap_data()
1081  * Store bitmap to image, filling bitmap table accordingly.
1082  */
1083 static uint64_t *store_bitmap_data(BlockDriverState *bs,
1084                                    BdrvDirtyBitmap *bitmap,
1085                                    uint32_t *bitmap_table_size, Error **errp)
1086 {
1087     int ret;
1088     BDRVQcow2State *s = bs->opaque;
1089     int64_t offset;
1090     uint64_t limit;
1091     uint64_t bm_size = bdrv_dirty_bitmap_size(bitmap);
1092     const char *bm_name = bdrv_dirty_bitmap_name(bitmap);
1093     uint8_t *buf = NULL;
1094     BdrvDirtyBitmapIter *dbi;
1095     uint64_t *tb;
1096     uint64_t tb_size =
1097             size_to_clusters(s,
1098                 bdrv_dirty_bitmap_serialization_size(bitmap, 0, bm_size));
1099 
1100     if (tb_size > BME_MAX_TABLE_SIZE ||
1101         tb_size * s->cluster_size > BME_MAX_PHYS_SIZE)
1102     {
1103         error_setg(errp, "Bitmap '%s' is too big", bm_name);
1104         return NULL;
1105     }
1106 
1107     tb = g_try_new0(uint64_t, tb_size);
1108     if (tb == NULL) {
1109         error_setg(errp, "No memory");
1110         return NULL;
1111     }
1112 
1113     dbi = bdrv_dirty_iter_new(bitmap);
1114     buf = g_malloc(s->cluster_size);
1115     limit = bytes_covered_by_bitmap_cluster(s, bitmap);
1116     assert(DIV_ROUND_UP(bm_size, limit) == tb_size);
1117 
1118     while ((offset = bdrv_dirty_iter_next(dbi)) >= 0) {
1119         uint64_t cluster = offset / limit;
1120         uint64_t end, write_size;
1121         int64_t off;
1122 
1123         /*
1124          * We found the first dirty offset, but want to write out the
1125          * entire cluster of the bitmap that includes that offset,
1126          * including any leading zero bits.
1127          */
1128         offset = QEMU_ALIGN_DOWN(offset, limit);
1129         end = MIN(bm_size, offset + limit);
1130         write_size = bdrv_dirty_bitmap_serialization_size(bitmap, offset,
1131                                                           end - offset);
1132         assert(write_size <= s->cluster_size);
1133 
1134         off = qcow2_alloc_clusters(bs, s->cluster_size);
1135         if (off < 0) {
1136             error_setg_errno(errp, -off,
1137                              "Failed to allocate clusters for bitmap '%s'",
1138                              bm_name);
1139             goto fail;
1140         }
1141         tb[cluster] = off;
1142 
1143         bdrv_dirty_bitmap_serialize_part(bitmap, buf, offset, end - offset);
1144         if (write_size < s->cluster_size) {
1145             memset(buf + write_size, 0, s->cluster_size - write_size);
1146         }
1147 
1148         ret = qcow2_pre_write_overlap_check(bs, 0, off, s->cluster_size);
1149         if (ret < 0) {
1150             error_setg_errno(errp, -ret, "Qcow2 overlap check failed");
1151             goto fail;
1152         }
1153 
1154         ret = bdrv_pwrite(bs->file, off, buf, s->cluster_size);
1155         if (ret < 0) {
1156             error_setg_errno(errp, -ret, "Failed to write bitmap '%s' to file",
1157                              bm_name);
1158             goto fail;
1159         }
1160 
1161         if (end >= bm_size) {
1162             break;
1163         }
1164 
1165         bdrv_set_dirty_iter(dbi, end);
1166     }
1167 
1168     *bitmap_table_size = tb_size;
1169     g_free(buf);
1170     bdrv_dirty_iter_free(dbi);
1171 
1172     return tb;
1173 
1174 fail:
1175     clear_bitmap_table(bs, tb, tb_size);
1176     g_free(buf);
1177     bdrv_dirty_iter_free(dbi);
1178     g_free(tb);
1179 
1180     return NULL;
1181 }
1182 
1183 /* store_bitmap()
1184  * Store bm->dirty_bitmap to qcow2.
1185  * Set bm->table_offset and bm->table_size accordingly.
1186  */
1187 static int store_bitmap(BlockDriverState *bs, Qcow2Bitmap *bm, Error **errp)
1188 {
1189     int ret;
1190     uint64_t *tb;
1191     int64_t tb_offset;
1192     uint32_t tb_size;
1193     BdrvDirtyBitmap *bitmap = bm->dirty_bitmap;
1194     const char *bm_name;
1195 
1196     assert(bitmap != NULL);
1197 
1198     bm_name = bdrv_dirty_bitmap_name(bitmap);
1199 
1200     tb = store_bitmap_data(bs, bitmap, &tb_size, errp);
1201     if (tb == NULL) {
1202         return -EINVAL;
1203     }
1204 
1205     assert(tb_size <= BME_MAX_TABLE_SIZE);
1206     tb_offset = qcow2_alloc_clusters(bs, tb_size * sizeof(tb[0]));
1207     if (tb_offset < 0) {
1208         error_setg_errno(errp, -tb_offset,
1209                          "Failed to allocate clusters for bitmap '%s'",
1210                          bm_name);
1211         ret = tb_offset;
1212         goto fail;
1213     }
1214 
1215     ret = qcow2_pre_write_overlap_check(bs, 0, tb_offset,
1216                                         tb_size * sizeof(tb[0]));
1217     if (ret < 0) {
1218         error_setg_errno(errp, -ret, "Qcow2 overlap check failed");
1219         goto fail;
1220     }
1221 
1222     bitmap_table_to_be(tb, tb_size);
1223     ret = bdrv_pwrite(bs->file, tb_offset, tb, tb_size * sizeof(tb[0]));
1224     if (ret < 0) {
1225         error_setg_errno(errp, -ret, "Failed to write bitmap '%s' to file",
1226                          bm_name);
1227         goto fail;
1228     }
1229 
1230     g_free(tb);
1231 
1232     bm->table.offset = tb_offset;
1233     bm->table.size = tb_size;
1234 
1235     return 0;
1236 
1237 fail:
1238     clear_bitmap_table(bs, tb, tb_size);
1239 
1240     if (tb_offset > 0) {
1241         qcow2_free_clusters(bs, tb_offset, tb_size * sizeof(tb[0]),
1242                             QCOW2_DISCARD_OTHER);
1243     }
1244 
1245     g_free(tb);
1246 
1247     return ret;
1248 }
1249 
1250 static Qcow2Bitmap *find_bitmap_by_name(Qcow2BitmapList *bm_list,
1251                                         const char *name)
1252 {
1253     Qcow2Bitmap *bm;
1254 
1255     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1256         if (strcmp(name, bm->name) == 0) {
1257             return bm;
1258         }
1259     }
1260 
1261     return NULL;
1262 }
1263 
1264 void qcow2_remove_persistent_dirty_bitmap(BlockDriverState *bs,
1265                                           const char *name,
1266                                           Error **errp)
1267 {
1268     int ret;
1269     BDRVQcow2State *s = bs->opaque;
1270     Qcow2Bitmap *bm;
1271     Qcow2BitmapList *bm_list;
1272 
1273     if (s->nb_bitmaps == 0) {
1274         /* Absence of the bitmap is not an error: see explanation above
1275          * bdrv_remove_persistent_dirty_bitmap() definition. */
1276         return;
1277     }
1278 
1279     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1280                                s->bitmap_directory_size, errp);
1281     if (bm_list == NULL) {
1282         return;
1283     }
1284 
1285     bm = find_bitmap_by_name(bm_list, name);
1286     if (bm == NULL) {
1287         goto fail;
1288     }
1289 
1290     QSIMPLEQ_REMOVE(bm_list, bm, Qcow2Bitmap, entry);
1291 
1292     ret = update_ext_header_and_dir(bs, bm_list);
1293     if (ret < 0) {
1294         error_setg_errno(errp, -ret, "Failed to update bitmap extension");
1295         goto fail;
1296     }
1297 
1298     free_bitmap_clusters(bs, &bm->table);
1299 
1300 fail:
1301     bitmap_free(bm);
1302     bitmap_list_free(bm_list);
1303 }
1304 
1305 void qcow2_store_persistent_dirty_bitmaps(BlockDriverState *bs, Error **errp)
1306 {
1307     BdrvDirtyBitmap *bitmap;
1308     BDRVQcow2State *s = bs->opaque;
1309     uint32_t new_nb_bitmaps = s->nb_bitmaps;
1310     uint64_t new_dir_size = s->bitmap_directory_size;
1311     int ret;
1312     Qcow2BitmapList *bm_list;
1313     Qcow2Bitmap *bm;
1314     Qcow2BitmapTableList drop_tables;
1315     Qcow2BitmapTable *tb, *tb_next;
1316 
1317     if (!bdrv_has_changed_persistent_bitmaps(bs)) {
1318         /* nothing to do */
1319         return;
1320     }
1321 
1322     if (!can_write(bs)) {
1323         error_setg(errp, "No write access");
1324         return;
1325     }
1326 
1327     QSIMPLEQ_INIT(&drop_tables);
1328 
1329     if (s->nb_bitmaps == 0) {
1330         bm_list = bitmap_list_new();
1331     } else {
1332         bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1333                                    s->bitmap_directory_size, errp);
1334         if (bm_list == NULL) {
1335             return;
1336         }
1337     }
1338 
1339     /* check constraints and names */
1340     for (bitmap = bdrv_dirty_bitmap_next(bs, NULL); bitmap != NULL;
1341          bitmap = bdrv_dirty_bitmap_next(bs, bitmap))
1342     {
1343         const char *name = bdrv_dirty_bitmap_name(bitmap);
1344         uint32_t granularity = bdrv_dirty_bitmap_granularity(bitmap);
1345         Qcow2Bitmap *bm;
1346 
1347         if (!bdrv_dirty_bitmap_get_persistance(bitmap) ||
1348             bdrv_dirty_bitmap_readonly(bitmap))
1349         {
1350             continue;
1351         }
1352 
1353         if (check_constraints_on_bitmap(bs, name, granularity, errp) < 0) {
1354             error_prepend(errp, "Bitmap '%s' doesn't satisfy the constraints: ",
1355                           name);
1356             goto fail;
1357         }
1358 
1359         bm = find_bitmap_by_name(bm_list, name);
1360         if (bm == NULL) {
1361             if (++new_nb_bitmaps > QCOW2_MAX_BITMAPS) {
1362                 error_setg(errp, "Too many persistent bitmaps");
1363                 goto fail;
1364             }
1365 
1366             new_dir_size += calc_dir_entry_size(strlen(name), 0);
1367             if (new_dir_size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
1368                 error_setg(errp, "Bitmap directory is too large");
1369                 goto fail;
1370             }
1371 
1372             bm = g_new0(Qcow2Bitmap, 1);
1373             bm->name = g_strdup(name);
1374             QSIMPLEQ_INSERT_TAIL(bm_list, bm, entry);
1375         } else {
1376             if (!(bm->flags & BME_FLAG_IN_USE)) {
1377                 error_setg(errp, "Bitmap '%s' already exists in the image",
1378                            name);
1379                 goto fail;
1380             }
1381             tb = g_memdup(&bm->table, sizeof(bm->table));
1382             bm->table.offset = 0;
1383             bm->table.size = 0;
1384             QSIMPLEQ_INSERT_TAIL(&drop_tables, tb, entry);
1385         }
1386         bm->flags = bdrv_dirty_bitmap_enabled(bitmap) ? BME_FLAG_AUTO : 0;
1387         bm->granularity_bits = ctz32(bdrv_dirty_bitmap_granularity(bitmap));
1388         bm->dirty_bitmap = bitmap;
1389     }
1390 
1391     /* allocate clusters and store bitmaps */
1392     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1393         if (bm->dirty_bitmap == NULL) {
1394             continue;
1395         }
1396 
1397         ret = store_bitmap(bs, bm, errp);
1398         if (ret < 0) {
1399             goto fail;
1400         }
1401     }
1402 
1403     ret = update_ext_header_and_dir(bs, bm_list);
1404     if (ret < 0) {
1405         error_setg_errno(errp, -ret, "Failed to update bitmap extension");
1406         goto fail;
1407     }
1408 
1409     /* Bitmap directory was successfully updated, so, old data can be dropped.
1410      * TODO it is better to reuse these clusters */
1411     QSIMPLEQ_FOREACH_SAFE(tb, &drop_tables, entry, tb_next) {
1412         free_bitmap_clusters(bs, tb);
1413         g_free(tb);
1414     }
1415 
1416     bitmap_list_free(bm_list);
1417     return;
1418 
1419 fail:
1420     QSIMPLEQ_FOREACH(bm, bm_list, entry) {
1421         if (bm->dirty_bitmap == NULL || bm->table.offset == 0) {
1422             continue;
1423         }
1424 
1425         free_bitmap_clusters(bs, &bm->table);
1426     }
1427 
1428     QSIMPLEQ_FOREACH_SAFE(tb, &drop_tables, entry, tb_next) {
1429         g_free(tb);
1430     }
1431 
1432     bitmap_list_free(bm_list);
1433 }
1434 
1435 int qcow2_reopen_bitmaps_ro(BlockDriverState *bs, Error **errp)
1436 {
1437     BdrvDirtyBitmap *bitmap;
1438     Error *local_err = NULL;
1439 
1440     qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
1441     if (local_err != NULL) {
1442         error_propagate(errp, local_err);
1443         return -EINVAL;
1444     }
1445 
1446     for (bitmap = bdrv_dirty_bitmap_next(bs, NULL); bitmap != NULL;
1447          bitmap = bdrv_dirty_bitmap_next(bs, bitmap))
1448     {
1449         if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
1450             bdrv_dirty_bitmap_set_readonly(bitmap, true);
1451         }
1452     }
1453 
1454     return 0;
1455 }
1456 
1457 bool qcow2_can_store_new_dirty_bitmap(BlockDriverState *bs,
1458                                       const char *name,
1459                                       uint32_t granularity,
1460                                       Error **errp)
1461 {
1462     BDRVQcow2State *s = bs->opaque;
1463     bool found;
1464     Qcow2BitmapList *bm_list;
1465 
1466     if (s->qcow_version < 3) {
1467         /* Without autoclear_features, we would always have to assume
1468          * that a program without persistent dirty bitmap support has
1469          * accessed this qcow2 file when opening it, and would thus
1470          * have to drop all dirty bitmaps (defeating their purpose).
1471          */
1472         error_setg(errp, "Cannot store dirty bitmaps in qcow2 v2 files");
1473         goto fail;
1474     }
1475 
1476     if (check_constraints_on_bitmap(bs, name, granularity, errp) != 0) {
1477         goto fail;
1478     }
1479 
1480     if (s->nb_bitmaps == 0) {
1481         return true;
1482     }
1483 
1484     if (s->nb_bitmaps >= QCOW2_MAX_BITMAPS) {
1485         error_setg(errp,
1486                    "Maximum number of persistent bitmaps is already reached");
1487         goto fail;
1488     }
1489 
1490     if (s->bitmap_directory_size + calc_dir_entry_size(strlen(name), 0) >
1491         QCOW2_MAX_BITMAP_DIRECTORY_SIZE)
1492     {
1493         error_setg(errp, "Not enough space in the bitmap directory");
1494         goto fail;
1495     }
1496 
1497     bm_list = bitmap_list_load(bs, s->bitmap_directory_offset,
1498                                s->bitmap_directory_size, errp);
1499     if (bm_list == NULL) {
1500         goto fail;
1501     }
1502 
1503     found = find_bitmap_by_name(bm_list, name);
1504     bitmap_list_free(bm_list);
1505     if (found) {
1506         error_setg(errp, "Bitmap with the same name is already stored");
1507         goto fail;
1508     }
1509 
1510     return true;
1511 
1512 fail:
1513     error_prepend(errp, "Can't make bitmap '%s' persistent in '%s': ",
1514                   name, bdrv_get_device_or_node_name(bs));
1515     return false;
1516 }
1517