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