OSDN Git Service

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