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