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