xref: /linux/drivers/md/md-bitmap.c (revision effd0cf5f52618e00aa67f01eb2a909d8742186a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * bitmap.c two-level bitmap (C) Peter T. Breuer (ptb@ot.uc3m.es) 2003
4  *
5  * bitmap_create  - sets up the bitmap structure
6  * bitmap_destroy - destroys the bitmap structure
7  *
8  * additions, Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.:
9  * - added disk storage for bitmap
10  * - changes to allow various bitmap chunk sizes
11  */
12 
13 /*
14  * Still to do:
15  *
16  * flush after percent set rather than just time based. (maybe both).
17  */
18 
19 #include <linux/blkdev.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/slab.h>
23 #include <linux/init.h>
24 #include <linux/timer.h>
25 #include <linux/sched.h>
26 #include <linux/list.h>
27 #include <linux/file.h>
28 #include <linux/mount.h>
29 #include <linux/buffer_head.h>
30 #include <linux/seq_file.h>
31 #include <trace/events/block.h>
32 
33 #include "md.h"
34 #include "md-bitmap.h"
35 #include "md-cluster.h"
36 
37 /*
38  * in-memory bitmap:
39  *
40  * Use 16 bit block counters to track pending writes to each "chunk".
41  * The 2 high order bits are special-purpose, the first is a flag indicating
42  * whether a resync is needed.  The second is a flag indicating whether a
43  * resync is active.
44  * This means that the counter is actually 14 bits:
45  *
46  * +--------+--------+------------------------------------------------+
47  * | resync | resync |               counter                          |
48  * | needed | active |                                                |
49  * |  (0-1) |  (0-1) |              (0-16383)                         |
50  * +--------+--------+------------------------------------------------+
51  *
52  * The "resync needed" bit is set when:
53  *    a '1' bit is read from storage at startup.
54  *    a write request fails on some drives
55  *    a resync is aborted on a chunk with 'resync active' set
56  * It is cleared (and resync-active set) when a resync starts across all drives
57  * of the chunk.
58  *
59  *
60  * The "resync active" bit is set when:
61  *    a resync is started on all drives, and resync_needed is set.
62  *       resync_needed will be cleared (as long as resync_active wasn't already set).
63  * It is cleared when a resync completes.
64  *
65  * The counter counts pending write requests, plus the on-disk bit.
66  * When the counter is '1' and the resync bits are clear, the on-disk
67  * bit can be cleared as well, thus setting the counter to 0.
68  * When we set a bit, or in the counter (to start a write), if the fields is
69  * 0, we first set the disk bit and set the counter to 1.
70  *
71  * If the counter is 0, the on-disk bit is clear and the stripe is clean
72  * Anything that dirties the stripe pushes the counter to 2 (at least)
73  * and sets the on-disk bit (lazily).
74  * If a periodic sweep find the counter at 2, it is decremented to 1.
75  * If the sweep find the counter at 1, the on-disk bit is cleared and the
76  * counter goes to zero.
77  *
78  * Also, we'll hijack the "map" pointer itself and use it as two 16 bit block
79  * counters as a fallback when "page" memory cannot be allocated:
80  *
81  * Normal case (page memory allocated):
82  *
83  *     page pointer (32-bit)
84  *
85  *     [ ] ------+
86  *               |
87  *               +-------> [   ][   ]..[   ] (4096 byte page == 2048 counters)
88  *                          c1   c2    c2048
89  *
90  * Hijacked case (page memory allocation failed):
91  *
92  *     hijacked page pointer (32-bit)
93  *
94  *     [		  ][		  ] (no page memory allocated)
95  *      counter #1 (16-bit) counter #2 (16-bit)
96  *
97  */
98 
99 typedef __u16 bitmap_counter_t;
100 
101 #define PAGE_BITS (PAGE_SIZE << 3)
102 #define PAGE_BIT_SHIFT (PAGE_SHIFT + 3)
103 
104 #define COUNTER_BITS 16
105 #define COUNTER_BIT_SHIFT 4
106 #define COUNTER_BYTE_SHIFT (COUNTER_BIT_SHIFT - 3)
107 
108 #define NEEDED_MASK ((bitmap_counter_t) (1 << (COUNTER_BITS - 1)))
109 #define RESYNC_MASK ((bitmap_counter_t) (1 << (COUNTER_BITS - 2)))
110 #define COUNTER_MAX ((bitmap_counter_t) RESYNC_MASK - 1)
111 
112 #define NEEDED(x) (((bitmap_counter_t) x) & NEEDED_MASK)
113 #define RESYNC(x) (((bitmap_counter_t) x) & RESYNC_MASK)
114 #define COUNTER(x) (((bitmap_counter_t) x) & COUNTER_MAX)
115 
116 /* how many counters per page? */
117 #define PAGE_COUNTER_RATIO (PAGE_BITS / COUNTER_BITS)
118 /* same, except a shift value for more efficient bitops */
119 #define PAGE_COUNTER_SHIFT (PAGE_BIT_SHIFT - COUNTER_BIT_SHIFT)
120 /* same, except a mask value for more efficient bitops */
121 #define PAGE_COUNTER_MASK  (PAGE_COUNTER_RATIO - 1)
122 
123 #define BITMAP_BLOCK_SHIFT 9
124 
125 /*
126  * bitmap structures:
127  */
128 
129 /* the in-memory bitmap is represented by bitmap_pages */
130 struct bitmap_page {
131 	/*
132 	 * map points to the actual memory page
133 	 */
134 	char *map;
135 	/*
136 	 * in emergencies (when map cannot be alloced), hijack the map
137 	 * pointer and use it as two counters itself
138 	 */
139 	unsigned int hijacked:1;
140 	/*
141 	 * If any counter in this page is '1' or '2' - and so could be
142 	 * cleared then that page is marked as 'pending'
143 	 */
144 	unsigned int pending:1;
145 	/*
146 	 * count of dirty bits on the page
147 	 */
148 	unsigned int  count:30;
149 };
150 
151 /* the main bitmap structure - one per mddev */
152 struct bitmap {
153 
154 	struct bitmap_counts {
155 		spinlock_t lock;
156 		struct bitmap_page *bp;
157 		/* total number of pages in the bitmap */
158 		unsigned long pages;
159 		/* number of pages not yet allocated */
160 		unsigned long missing_pages;
161 		/* chunksize = 2^chunkshift (for bitops) */
162 		unsigned long chunkshift;
163 		/* total number of data chunks for the array */
164 		unsigned long chunks;
165 	} counts;
166 
167 	struct mddev *mddev; /* the md device that the bitmap is for */
168 
169 	__u64	events_cleared;
170 	int need_sync;
171 
172 	struct bitmap_storage {
173 		/* backing disk file */
174 		struct file *file;
175 		/* cached copy of the bitmap file superblock */
176 		struct page *sb_page;
177 		unsigned long sb_index;
178 		/* list of cache pages for the file */
179 		struct page **filemap;
180 		/* attributes associated filemap pages */
181 		unsigned long *filemap_attr;
182 		/* number of pages in the file */
183 		unsigned long file_pages;
184 		/* total bytes in the bitmap */
185 		unsigned long bytes;
186 	} storage;
187 
188 	unsigned long flags;
189 
190 	int allclean;
191 
192 	atomic_t behind_writes;
193 	/* highest actual value at runtime */
194 	unsigned long behind_writes_used;
195 
196 	/*
197 	 * the bitmap daemon - periodically wakes up and sweeps the bitmap
198 	 * file, cleaning up bits and flushing out pages to disk as necessary
199 	 */
200 	unsigned long daemon_lastrun; /* jiffies of last run */
201 	/*
202 	 * when we lasted called end_sync to update bitmap with resync
203 	 * progress.
204 	 */
205 	unsigned long last_end_sync;
206 
207 	/* pending writes to the bitmap file */
208 	atomic_t pending_writes;
209 	wait_queue_head_t write_wait;
210 	wait_queue_head_t overflow_wait;
211 	wait_queue_head_t behind_wait;
212 
213 	struct kernfs_node *sysfs_can_clear;
214 	/* slot offset for clustered env */
215 	int cluster_slot;
216 };
217 
218 static struct workqueue_struct *md_bitmap_wq;
219 static struct attribute_group md_bitmap_internal_group;
220 
221 static int __bitmap_resize(struct bitmap *bitmap, sector_t blocks,
222 			   int chunksize, bool init);
223 
224 static inline char *bmname(struct bitmap *bitmap)
225 {
226 	return bitmap->mddev ? mdname(bitmap->mddev) : "mdX";
227 }
228 
229 static bool bitmap_enabled(void *data, bool flush)
230 {
231 	struct bitmap *bitmap = data;
232 
233 	if (!flush)
234 		return true;
235 
236 	/*
237 	 * If caller want to flush bitmap pages to underlying disks, check if
238 	 * there are cached pages in filemap.
239 	 */
240 	return !test_bit(BITMAP_STALE, &bitmap->flags) &&
241 	       bitmap->storage.filemap != NULL;
242 }
243 
244 /*
245  * check a page and, if necessary, allocate it (or hijack it if the alloc fails)
246  *
247  * 1) check to see if this page is allocated, if it's not then try to alloc
248  * 2) if the alloc fails, set the page's hijacked flag so we'll use the
249  *    page pointer directly as a counter
250  *
251  * if we find our page, we increment the page's refcount so that it stays
252  * allocated while we're using it
253  */
254 static int md_bitmap_checkpage(struct bitmap_counts *bitmap,
255 			       unsigned long page, int create, int no_hijack)
256 __releases(bitmap->lock)
257 __acquires(bitmap->lock)
258 {
259 	unsigned char *mappage;
260 
261 	WARN_ON_ONCE(page >= bitmap->pages);
262 	if (bitmap->bp[page].hijacked) /* it's hijacked, don't try to alloc */
263 		return 0;
264 
265 	if (bitmap->bp[page].map) /* page is already allocated, just return */
266 		return 0;
267 
268 	if (!create)
269 		return -ENOENT;
270 
271 	/* this page has not been allocated yet */
272 
273 	spin_unlock_irq(&bitmap->lock);
274 	/* It is possible that this is being called inside a
275 	 * prepare_to_wait/finish_wait loop from raid5c:make_request().
276 	 * In general it is not permitted to sleep in that context as it
277 	 * can cause the loop to spin freely.
278 	 * That doesn't apply here as we can only reach this point
279 	 * once with any loop.
280 	 * When this function completes, either bp[page].map or
281 	 * bp[page].hijacked.  In either case, this function will
282 	 * abort before getting to this point again.  So there is
283 	 * no risk of a free-spin, and so it is safe to assert
284 	 * that sleeping here is allowed.
285 	 */
286 	sched_annotate_sleep();
287 	mappage = kzalloc(PAGE_SIZE, GFP_NOIO);
288 	spin_lock_irq(&bitmap->lock);
289 
290 	if (mappage == NULL) {
291 		pr_debug("md/bitmap: map page allocation failed, hijacking\n");
292 		/* We don't support hijack for cluster raid */
293 		if (no_hijack)
294 			return -ENOMEM;
295 		/* failed - set the hijacked flag so that we can use the
296 		 * pointer as a counter */
297 		if (!bitmap->bp[page].map)
298 			bitmap->bp[page].hijacked = 1;
299 	} else if (bitmap->bp[page].map ||
300 		   bitmap->bp[page].hijacked) {
301 		/* somebody beat us to getting the page */
302 		kfree(mappage);
303 	} else {
304 
305 		/* no page was in place and we have one, so install it */
306 
307 		bitmap->bp[page].map = mappage;
308 		bitmap->missing_pages--;
309 	}
310 	return 0;
311 }
312 
313 /* if page is completely empty, put it back on the free list, or dealloc it */
314 /* if page was hijacked, unmark the flag so it might get alloced next time */
315 /* Note: lock should be held when calling this */
316 static void md_bitmap_checkfree(struct bitmap_counts *bitmap, unsigned long page)
317 {
318 	char *ptr;
319 
320 	if (bitmap->bp[page].count) /* page is still busy */
321 		return;
322 
323 	/* page is no longer in use, it can be released */
324 
325 	if (bitmap->bp[page].hijacked) { /* page was hijacked, undo this now */
326 		bitmap->bp[page].hijacked = 0;
327 		bitmap->bp[page].map = NULL;
328 	} else {
329 		/* normal case, free the page */
330 		ptr = bitmap->bp[page].map;
331 		bitmap->bp[page].map = NULL;
332 		bitmap->missing_pages++;
333 		kfree(ptr);
334 	}
335 }
336 
337 /*
338  * bitmap file handling - read and write the bitmap file and its superblock
339  */
340 
341 /*
342  * basic page I/O operations
343  */
344 
345 /* IO operations when bitmap is stored near all superblocks */
346 
347 /* choose a good rdev and read the page from there */
348 static int read_sb_page(struct mddev *mddev, loff_t offset,
349 		struct page *page, unsigned long index, int size)
350 {
351 
352 	sector_t sector = mddev->bitmap_info.offset + offset +
353 		index * (PAGE_SIZE / SECTOR_SIZE);
354 	struct md_rdev *rdev;
355 
356 	rdev_for_each(rdev, mddev) {
357 		u32 iosize = roundup(size, bdev_logical_block_size(rdev->bdev));
358 
359 		if (!test_bit(In_sync, &rdev->flags) ||
360 		    test_bit(Faulty, &rdev->flags) ||
361 		    test_bit(Bitmap_sync, &rdev->flags))
362 			continue;
363 
364 		if (sync_page_io(rdev, sector, iosize, page, REQ_OP_READ, true))
365 			return 0;
366 	}
367 	return -EIO;
368 }
369 
370 static struct md_rdev *next_active_rdev(struct md_rdev *rdev, struct mddev *mddev)
371 {
372 	/* Iterate the disks of an mddev, using rcu to protect access to the
373 	 * linked list, and raising the refcount of devices we return to ensure
374 	 * they don't disappear while in use.
375 	 * As devices are only added or removed when raid_disk is < 0 and
376 	 * nr_pending is 0 and In_sync is clear, the entries we return will
377 	 * still be in the same position on the list when we re-enter
378 	 * list_for_each_entry_continue_rcu.
379 	 *
380 	 * Note that if entered with 'rdev == NULL' to start at the
381 	 * beginning, we temporarily assign 'rdev' to an address which
382 	 * isn't really an rdev, but which can be used by
383 	 * list_for_each_entry_continue_rcu() to find the first entry.
384 	 */
385 	rcu_read_lock();
386 	if (rdev == NULL)
387 		/* start at the beginning */
388 		rdev = list_entry(&mddev->disks, struct md_rdev, same_set);
389 	else {
390 		/* release the previous rdev and start from there. */
391 		rdev_dec_pending(rdev, mddev);
392 	}
393 	list_for_each_entry_continue_rcu(rdev, &mddev->disks, same_set) {
394 		if (rdev->raid_disk >= 0 &&
395 		    !test_bit(Faulty, &rdev->flags)) {
396 			/* this is a usable devices */
397 			atomic_inc(&rdev->nr_pending);
398 			rcu_read_unlock();
399 			return rdev;
400 		}
401 	}
402 	rcu_read_unlock();
403 	return NULL;
404 }
405 
406 static unsigned int optimal_io_size(struct block_device *bdev,
407 				    unsigned int last_page_size,
408 				    unsigned int io_size)
409 {
410 	if (bdev_io_opt(bdev) > bdev_logical_block_size(bdev))
411 		return roundup(last_page_size, bdev_io_opt(bdev));
412 	return io_size;
413 }
414 
415 static unsigned int bitmap_io_size(unsigned int io_size, unsigned int opt_size,
416 				   loff_t start, loff_t boundary)
417 {
418 	if (io_size != opt_size &&
419 	    start + opt_size / SECTOR_SIZE <= boundary)
420 		return opt_size;
421 	if (start + io_size / SECTOR_SIZE <= boundary)
422 		return io_size;
423 
424 	/* Overflows boundary */
425 	return 0;
426 }
427 
428 static int __write_sb_page(struct md_rdev *rdev, struct bitmap *bitmap,
429 			   unsigned long pg_index, struct page *page)
430 {
431 	struct block_device *bdev;
432 	struct mddev *mddev = bitmap->mddev;
433 	struct bitmap_storage *store = &bitmap->storage;
434 	unsigned long num_pages = bitmap->storage.file_pages;
435 	unsigned int bitmap_limit = (num_pages - pg_index % num_pages) << PAGE_SHIFT;
436 	loff_t sboff, offset = mddev->bitmap_info.offset;
437 	sector_t ps = pg_index * PAGE_SIZE / SECTOR_SIZE;
438 	unsigned int size = PAGE_SIZE;
439 	unsigned int opt_size = PAGE_SIZE;
440 	sector_t doff;
441 
442 	bdev = (rdev->meta_bdev) ? rdev->meta_bdev : rdev->bdev;
443 	/* we compare length (page numbers), not page offset. */
444 	if ((pg_index - store->sb_index) == num_pages - 1) {
445 		unsigned int last_page_size = store->bytes & (PAGE_SIZE - 1);
446 
447 		if (last_page_size == 0)
448 			last_page_size = PAGE_SIZE;
449 		size = roundup(last_page_size, bdev_logical_block_size(bdev));
450 		opt_size = optimal_io_size(bdev, last_page_size, size);
451 	}
452 
453 	sboff = rdev->sb_start + offset;
454 	doff = rdev->data_offset;
455 
456 	/* Just make sure we aren't corrupting data or metadata */
457 	if (mddev->external) {
458 		/* Bitmap could be anywhere. */
459 		if (sboff + ps > doff &&
460 		    sboff < (doff + mddev->dev_sectors + PAGE_SIZE / SECTOR_SIZE))
461 			return -EINVAL;
462 	} else if (offset < 0) {
463 		/* DATA  BITMAP METADATA  */
464 		size = bitmap_io_size(size, opt_size, offset + ps, 0);
465 		if (size == 0)
466 			/* bitmap runs in to metadata */
467 			return -EINVAL;
468 
469 		if (doff + mddev->dev_sectors > sboff)
470 			/* data runs in to bitmap */
471 			return -EINVAL;
472 	} else if (rdev->sb_start < rdev->data_offset) {
473 		/* METADATA BITMAP DATA */
474 		size = bitmap_io_size(size, opt_size, sboff + ps, doff);
475 		if (size == 0)
476 			/* bitmap runs in to data */
477 			return -EINVAL;
478 	}
479 
480 	md_write_metadata(mddev, rdev, sboff + ps, (int)min(size, bitmap_limit),
481 			  page, 0);
482 	return 0;
483 }
484 
485 static void write_sb_page(struct bitmap *bitmap, unsigned long pg_index,
486 			  struct page *page, bool wait)
487 {
488 	struct mddev *mddev = bitmap->mddev;
489 
490 	do {
491 		struct md_rdev *rdev = NULL;
492 
493 		while ((rdev = next_active_rdev(rdev, mddev)) != NULL) {
494 			if (__write_sb_page(rdev, bitmap, pg_index, page) < 0) {
495 				set_bit(BITMAP_WRITE_ERROR, &bitmap->flags);
496 				return;
497 			}
498 		}
499 	} while (wait && md_super_wait(mddev) < 0);
500 }
501 
502 static void md_bitmap_file_kick(struct bitmap *bitmap);
503 
504 #ifdef CONFIG_MD_BITMAP_FILE
505 static void end_bitmap_write(struct bio *bio)
506 {
507 	struct buffer_head *bh;
508 	bool uptodate = bio_endio_bh(bio, &bh);
509 	struct bitmap *bitmap = bh->b_private;
510 
511 	if (!uptodate)
512 		set_bit(BITMAP_WRITE_ERROR, &bitmap->flags);
513 	if (atomic_dec_and_test(&bitmap->pending_writes))
514 		wake_up(&bitmap->write_wait);
515 }
516 
517 static void write_file_page(struct bitmap *bitmap, struct page *page, int wait)
518 {
519 	struct folio *folio = page_folio(page);
520 	struct buffer_head *bh = folio_buffers(folio);
521 
522 	while (bh && bh->b_blocknr) {
523 		atomic_inc(&bitmap->pending_writes);
524 		set_buffer_locked(bh);
525 		set_buffer_mapped(bh);
526 		bh_submit(bh, REQ_OP_WRITE | REQ_SYNC, end_bitmap_write);
527 		bh = bh->b_this_page;
528 	}
529 
530 	if (wait)
531 		wait_event(bitmap->write_wait,
532 			   atomic_read(&bitmap->pending_writes) == 0);
533 }
534 
535 static void free_buffers(struct page *page)
536 {
537 	struct folio *folio = page_folio(page);
538 	struct buffer_head *bh = folio_detach_private(folio);
539 
540 	while (bh) {
541 		struct buffer_head *next = bh->b_this_page;
542 		free_buffer_head(bh);
543 		bh = next;
544 	}
545 	folio_put(folio);
546 }
547 
548 /* read a page from a file.
549  * We both read the page, and attach buffers to the page to record the
550  * address of each block (using bmap).  These addresses will be used
551  * to write the block later, completely bypassing the filesystem.
552  * This usage is similar to how swap files are handled, and allows us
553  * to write to a file with no concerns of memory allocation failing.
554  */
555 static int read_file_page(struct file *file, unsigned long index,
556 		struct bitmap *bitmap, unsigned long count, struct page *page)
557 {
558 	int ret = 0;
559 	struct inode *inode = file_inode(file);
560 	struct folio *folio = page_folio(page);
561 	struct buffer_head *bh;
562 	sector_t block, blk_cur;
563 	unsigned long blocksize = i_blocksize(inode);
564 
565 	pr_debug("read bitmap file (%dB @ %llu)\n", (int)PAGE_SIZE,
566 		 (unsigned long long)index << PAGE_SHIFT);
567 
568 	bh = folio_alloc_buffers(folio, blocksize, GFP_NOFS | __GFP_ACCOUNT);
569 	if (!bh) {
570 		ret = -ENOMEM;
571 		goto out;
572 	}
573 	folio_attach_private(folio, bh);
574 	blk_cur = index << (PAGE_SHIFT - inode->i_blkbits);
575 	while (bh) {
576 		block = blk_cur;
577 
578 		if (count == 0)
579 			bh->b_blocknr = 0;
580 		else {
581 			ret = bmap(inode, &block);
582 			if (ret || !block) {
583 				ret = -EINVAL;
584 				bh->b_blocknr = 0;
585 				goto out;
586 			}
587 
588 			bh->b_blocknr = block;
589 			bh->b_bdev = inode->i_sb->s_bdev;
590 			if (count < blocksize)
591 				count = 0;
592 			else
593 				count -= blocksize;
594 
595 			bh->b_private = bitmap;
596 			atomic_inc(&bitmap->pending_writes);
597 			set_buffer_locked(bh);
598 			set_buffer_mapped(bh);
599 			bh_submit(bh, REQ_OP_READ, end_bitmap_write);
600 		}
601 		blk_cur++;
602 		bh = bh->b_this_page;
603 	}
604 
605 	wait_event(bitmap->write_wait,
606 		   atomic_read(&bitmap->pending_writes)==0);
607 	if (test_bit(BITMAP_WRITE_ERROR, &bitmap->flags))
608 		ret = -EIO;
609 out:
610 	if (ret)
611 		pr_err("md: bitmap read error: (%dB @ %llu): %d\n",
612 		       (int)PAGE_SIZE,
613 		       (unsigned long long)index << PAGE_SHIFT,
614 		       ret);
615 	return ret;
616 }
617 #else /* CONFIG_MD_BITMAP_FILE */
618 static void write_file_page(struct bitmap *bitmap, struct page *page, int wait)
619 {
620 }
621 static int read_file_page(struct file *file, unsigned long index,
622 		struct bitmap *bitmap, unsigned long count, struct page *page)
623 {
624 	return -EIO;
625 }
626 static void free_buffers(struct page *page)
627 {
628 	put_page(page);
629 }
630 #endif /* CONFIG_MD_BITMAP_FILE */
631 
632 /*
633  * bitmap file superblock operations
634  */
635 
636 /*
637  * write out a page to a file
638  */
639 static void filemap_write_page(struct bitmap *bitmap, unsigned long pg_index,
640 			       bool wait)
641 {
642 	struct bitmap_storage *store = &bitmap->storage;
643 	struct page *page = store->filemap[pg_index];
644 
645 	if (mddev_is_clustered(bitmap->mddev)) {
646 		/* go to node bitmap area starting point */
647 		pg_index += store->sb_index;
648 	}
649 
650 	if (store->file)
651 		write_file_page(bitmap, page, wait);
652 	else
653 		write_sb_page(bitmap, pg_index, page, wait);
654 }
655 
656 /*
657  * md_bitmap_wait_writes() should be called before writing any bitmap
658  * blocks, to ensure previous writes, particularly from
659  * md_bitmap_daemon_work(), have completed.
660  */
661 static void md_bitmap_wait_writes(struct bitmap *bitmap)
662 {
663 	if (bitmap->storage.file)
664 		wait_event(bitmap->write_wait,
665 			   atomic_read(&bitmap->pending_writes)==0);
666 	else
667 		/* Note that we ignore the return value.  The writes
668 		 * might have failed, but that would just mean that
669 		 * some bits which should be cleared haven't been,
670 		 * which is safe.  The relevant bitmap blocks will
671 		 * probably get written again, but there is no great
672 		 * loss if they aren't.
673 		 */
674 		md_super_wait(bitmap->mddev);
675 }
676 
677 
678 /* update the event counter and sync the superblock to disk */
679 static void bitmap_update_sb(void *data)
680 {
681 	bitmap_super_t *sb;
682 	struct bitmap *bitmap = data;
683 
684 	if (!bitmap || !bitmap->mddev) /* no bitmap for this array */
685 		return;
686 	if (bitmap->mddev->bitmap_info.external)
687 		return;
688 	if (!bitmap->storage.sb_page) /* no superblock */
689 		return;
690 	sb = kmap_local_page(bitmap->storage.sb_page);
691 	sb->events = cpu_to_le64(bitmap->mddev->events);
692 	if (bitmap->mddev->events < bitmap->events_cleared)
693 		/* rocking back to read-only */
694 		bitmap->events_cleared = bitmap->mddev->events;
695 	sb->events_cleared = cpu_to_le64(bitmap->events_cleared);
696 	/*
697 	 * clear BITMAP_WRITE_ERROR bit to protect against the case that
698 	 * a bitmap write error occurred but the later writes succeeded.
699 	 */
700 	sb->state = cpu_to_le32(bitmap->flags & ~BIT(BITMAP_WRITE_ERROR));
701 	/* Just in case these have been changed via sysfs: */
702 	sb->daemon_sleep = cpu_to_le32(bitmap->mddev->bitmap_info.daemon_sleep/HZ);
703 	sb->write_behind = cpu_to_le32(bitmap->mddev->bitmap_info.max_write_behind);
704 	/* This might have been changed by a reshape */
705 	sb->sync_size = cpu_to_le64(bitmap->mddev->resync_max_sectors);
706 	sb->chunksize = cpu_to_le32(bitmap->mddev->bitmap_info.chunksize);
707 	sb->nodes = cpu_to_le32(bitmap->mddev->bitmap_info.nodes);
708 	sb->sectors_reserved = cpu_to_le32(bitmap->mddev->
709 					   bitmap_info.space);
710 	kunmap_local(sb);
711 
712 	if (bitmap->storage.file)
713 		write_file_page(bitmap, bitmap->storage.sb_page, 1);
714 	else
715 		write_sb_page(bitmap, bitmap->storage.sb_index,
716 			      bitmap->storage.sb_page, 1);
717 }
718 
719 static void bitmap_print_sb(struct bitmap *bitmap)
720 {
721 	bitmap_super_t *sb;
722 
723 	if (!bitmap || !bitmap->storage.sb_page)
724 		return;
725 	sb = kmap_local_page(bitmap->storage.sb_page);
726 	pr_debug("%s: bitmap file superblock:\n", bmname(bitmap));
727 	pr_debug("         magic: %08x\n", le32_to_cpu(sb->magic));
728 	pr_debug("       version: %u\n", le32_to_cpu(sb->version));
729 	pr_debug("          uuid: %08x.%08x.%08x.%08x\n",
730 		 le32_to_cpu(*(__le32 *)(sb->uuid+0)),
731 		 le32_to_cpu(*(__le32 *)(sb->uuid+4)),
732 		 le32_to_cpu(*(__le32 *)(sb->uuid+8)),
733 		 le32_to_cpu(*(__le32 *)(sb->uuid+12)));
734 	pr_debug("        events: %llu\n",
735 		 (unsigned long long) le64_to_cpu(sb->events));
736 	pr_debug("events cleared: %llu\n",
737 		 (unsigned long long) le64_to_cpu(sb->events_cleared));
738 	pr_debug("         state: %08x\n", le32_to_cpu(sb->state));
739 	pr_debug("     chunksize: %u B\n", le32_to_cpu(sb->chunksize));
740 	pr_debug("  daemon sleep: %us\n", le32_to_cpu(sb->daemon_sleep));
741 	pr_debug("     sync size: %llu KB\n",
742 		 (unsigned long long)le64_to_cpu(sb->sync_size)/2);
743 	pr_debug("max write behind: %u\n", le32_to_cpu(sb->write_behind));
744 	kunmap_local(sb);
745 }
746 
747 /*
748  * bitmap_new_disk_sb
749  * @bitmap
750  *
751  * This function is somewhat the reverse of bitmap_read_sb.  bitmap_read_sb
752  * reads and verifies the on-disk bitmap superblock and populates bitmap_info.
753  * This function verifies 'bitmap_info' and populates the on-disk bitmap
754  * structure, which is to be written to disk.
755  *
756  * Returns: 0 on success, -Exxx on error
757  */
758 static int md_bitmap_new_disk_sb(struct bitmap *bitmap)
759 {
760 	bitmap_super_t *sb;
761 	unsigned long chunksize, daemon_sleep, write_behind;
762 
763 	bitmap->storage.sb_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
764 	if (bitmap->storage.sb_page == NULL)
765 		return -ENOMEM;
766 	bitmap->storage.sb_index = 0;
767 
768 	sb = kmap_local_page(bitmap->storage.sb_page);
769 
770 	sb->magic = cpu_to_le32(BITMAP_MAGIC);
771 	sb->version = cpu_to_le32(BITMAP_MAJOR_HI);
772 
773 	chunksize = bitmap->mddev->bitmap_info.chunksize;
774 	BUG_ON(!chunksize);
775 	if (!is_power_of_2(chunksize)) {
776 		kunmap_local(sb);
777 		pr_warn("bitmap chunksize not a power of 2\n");
778 		return -EINVAL;
779 	}
780 	sb->chunksize = cpu_to_le32(chunksize);
781 
782 	daemon_sleep = bitmap->mddev->bitmap_info.daemon_sleep;
783 	if (!daemon_sleep || (daemon_sleep > MAX_SCHEDULE_TIMEOUT)) {
784 		pr_debug("Choosing daemon_sleep default (5 sec)\n");
785 		daemon_sleep = 5 * HZ;
786 	}
787 	sb->daemon_sleep = cpu_to_le32(daemon_sleep);
788 	bitmap->mddev->bitmap_info.daemon_sleep = daemon_sleep;
789 
790 	/*
791 	 * FIXME: write_behind for RAID1.  If not specified, what
792 	 * is a good choice?  We choose COUNTER_MAX / 2 arbitrarily.
793 	 */
794 	write_behind = bitmap->mddev->bitmap_info.max_write_behind;
795 	if (write_behind > COUNTER_MAX / 2)
796 		write_behind = COUNTER_MAX / 2;
797 	sb->write_behind = cpu_to_le32(write_behind);
798 	bitmap->mddev->bitmap_info.max_write_behind = write_behind;
799 
800 	/* keep the array size field of the bitmap superblock up to date */
801 	sb->sync_size = cpu_to_le64(bitmap->mddev->resync_max_sectors);
802 
803 	memcpy(sb->uuid, bitmap->mddev->uuid, 16);
804 
805 	set_bit(BITMAP_STALE, &bitmap->flags);
806 	sb->state = cpu_to_le32(bitmap->flags);
807 	bitmap->events_cleared = bitmap->mddev->events;
808 	sb->events_cleared = cpu_to_le64(bitmap->mddev->events);
809 	bitmap->mddev->bitmap_info.nodes = 0;
810 
811 	kunmap_local(sb);
812 
813 	return 0;
814 }
815 
816 /* read the superblock from the bitmap file and initialize some bitmap fields */
817 static int md_bitmap_read_sb(struct bitmap *bitmap)
818 {
819 	char *reason = NULL;
820 	bitmap_super_t *sb;
821 	unsigned long chunksize, daemon_sleep, write_behind;
822 	unsigned long long events;
823 	int nodes = 0;
824 	unsigned long sectors_reserved = 0;
825 	int err = -EINVAL;
826 	struct page *sb_page;
827 	loff_t offset = 0;
828 
829 	if (!bitmap->storage.file && !bitmap->mddev->bitmap_info.offset) {
830 		chunksize = 128 * 1024 * 1024;
831 		daemon_sleep = 5 * HZ;
832 		write_behind = 0;
833 		set_bit(BITMAP_STALE, &bitmap->flags);
834 		err = 0;
835 		goto out_no_sb;
836 	}
837 	/* page 0 is the superblock, read it... */
838 	sb_page = alloc_page(GFP_KERNEL);
839 	if (!sb_page)
840 		return -ENOMEM;
841 	bitmap->storage.sb_page = sb_page;
842 
843 re_read:
844 	/* If cluster_slot is set, the cluster is setup */
845 	if (bitmap->cluster_slot >= 0) {
846 		sector_t bm_blocks = bitmap->mddev->resync_max_sectors;
847 
848 		bm_blocks = DIV_ROUND_UP_SECTOR_T(bm_blocks,
849 			   (bitmap->mddev->bitmap_info.chunksize >> 9));
850 		/* bits to bytes */
851 		bm_blocks = ((bm_blocks+7) >> 3) + sizeof(bitmap_super_t);
852 		/* to 4k blocks */
853 		bm_blocks = DIV_ROUND_UP_SECTOR_T(bm_blocks, 4096);
854 		offset = bitmap->cluster_slot * (bm_blocks << 3);
855 		pr_debug("%s:%d bm slot: %d offset: %llu\n", __func__, __LINE__,
856 			bitmap->cluster_slot, offset);
857 	}
858 
859 	if (bitmap->storage.file) {
860 		loff_t isize = i_size_read(bitmap->storage.file->f_mapping->host);
861 		int bytes = isize > PAGE_SIZE ? PAGE_SIZE : isize;
862 
863 		err = read_file_page(bitmap->storage.file, 0,
864 				bitmap, bytes, sb_page);
865 	} else {
866 		err = read_sb_page(bitmap->mddev, offset, sb_page, 0,
867 				   sizeof(bitmap_super_t));
868 	}
869 	if (err)
870 		return err;
871 
872 	err = -EINVAL;
873 	sb = kmap_local_page(sb_page);
874 
875 	chunksize = le32_to_cpu(sb->chunksize);
876 	daemon_sleep = le32_to_cpu(sb->daemon_sleep) * HZ;
877 	write_behind = le32_to_cpu(sb->write_behind);
878 	sectors_reserved = le32_to_cpu(sb->sectors_reserved);
879 
880 	/* verify that the bitmap-specific fields are valid */
881 	if (sb->magic != cpu_to_le32(BITMAP_MAGIC))
882 		reason = "bad magic";
883 	else if (le32_to_cpu(sb->version) < BITMAP_MAJOR_LO ||
884 		 le32_to_cpu(sb->version) > BITMAP_MAJOR_CLUSTERED)
885 		reason = "unrecognized superblock version";
886 	else if (chunksize < 512)
887 		reason = "bitmap chunksize too small";
888 	else if (!is_power_of_2(chunksize))
889 		reason = "bitmap chunksize not a power of 2";
890 	else if (daemon_sleep < 1 || daemon_sleep > MAX_SCHEDULE_TIMEOUT)
891 		reason = "daemon sleep period out of range";
892 	else if (write_behind > COUNTER_MAX)
893 		reason = "write-behind limit out of range (0 - 16383)";
894 	if (reason) {
895 		pr_warn("%s: invalid bitmap file superblock: %s\n",
896 			bmname(bitmap), reason);
897 		goto out;
898 	}
899 
900 	/*
901 	 * Setup nodes/clustername only if bitmap version is
902 	 * cluster-compatible
903 	 */
904 	if (sb->version == cpu_to_le32(BITMAP_MAJOR_CLUSTERED)) {
905 		nodes = le32_to_cpu(sb->nodes);
906 		strscpy(bitmap->mddev->bitmap_info.cluster_name,
907 				sb->cluster_name, 64);
908 	}
909 
910 	/* keep the array size field of the bitmap superblock up to date */
911 	sb->sync_size = cpu_to_le64(bitmap->mddev->resync_max_sectors);
912 
913 	if (bitmap->mddev->persistent) {
914 		/*
915 		 * We have a persistent array superblock, so compare the
916 		 * bitmap's UUID and event counter to the mddev's
917 		 */
918 		if (memcmp(sb->uuid, bitmap->mddev->uuid, 16)) {
919 			pr_warn("%s: bitmap superblock UUID mismatch\n",
920 				bmname(bitmap));
921 			goto out;
922 		}
923 		events = le64_to_cpu(sb->events);
924 		if (!nodes && (events < bitmap->mddev->events)) {
925 			pr_warn("%s: bitmap file is out of date (%llu < %llu) -- forcing full recovery\n",
926 				bmname(bitmap), events,
927 				(unsigned long long) bitmap->mddev->events);
928 			set_bit(BITMAP_STALE, &bitmap->flags);
929 		}
930 	}
931 
932 	/* assign fields using values from superblock */
933 	bitmap->flags |= le32_to_cpu(sb->state);
934 	if (le32_to_cpu(sb->version) == BITMAP_MAJOR_HOSTENDIAN)
935 		set_bit(BITMAP_HOSTENDIAN, &bitmap->flags);
936 	bitmap->events_cleared = le64_to_cpu(sb->events_cleared);
937 	err = 0;
938 
939 out:
940 	kunmap_local(sb);
941 	if (err == 0 && nodes && (bitmap->cluster_slot < 0)) {
942 		/* Assigning chunksize is required for "re_read" */
943 		bitmap->mddev->bitmap_info.chunksize = chunksize;
944 		err = md_setup_cluster(bitmap->mddev, nodes);
945 		if (err) {
946 			pr_warn("%s: Could not setup cluster service (%d)\n",
947 				bmname(bitmap), err);
948 			goto out_no_sb;
949 		}
950 		bitmap->cluster_slot = bitmap->mddev->cluster_ops->slot_number(bitmap->mddev);
951 		goto re_read;
952 	}
953 
954 out_no_sb:
955 	if (err == 0) {
956 		if (test_bit(BITMAP_STALE, &bitmap->flags))
957 			bitmap->events_cleared = bitmap->mddev->events;
958 		bitmap->mddev->bitmap_info.chunksize = chunksize;
959 		bitmap->mddev->bitmap_info.daemon_sleep = daemon_sleep;
960 		bitmap->mddev->bitmap_info.max_write_behind = write_behind;
961 		bitmap->mddev->bitmap_info.nodes = nodes;
962 		if (bitmap->mddev->bitmap_info.space == 0 ||
963 			bitmap->mddev->bitmap_info.space > sectors_reserved)
964 			bitmap->mddev->bitmap_info.space = sectors_reserved;
965 	} else {
966 		bitmap_print_sb(bitmap);
967 		if (bitmap->cluster_slot < 0)
968 			md_cluster_stop(bitmap->mddev);
969 	}
970 	return err;
971 }
972 
973 /*
974  * general bitmap file operations
975  */
976 
977 /*
978  * on-disk bitmap:
979  *
980  * Use one bit per "chunk" (block set). We do the disk I/O on the bitmap
981  * file a page at a time. There's a superblock at the start of the file.
982  */
983 /* calculate the index of the page that contains this bit */
984 static inline unsigned long file_page_index(struct bitmap_storage *store,
985 					    unsigned long chunk)
986 {
987 	if (store->sb_page)
988 		chunk += sizeof(bitmap_super_t) << 3;
989 	return chunk >> PAGE_BIT_SHIFT;
990 }
991 
992 /* calculate the (bit) offset of this bit within a page */
993 static inline unsigned long file_page_offset(struct bitmap_storage *store,
994 					     unsigned long chunk)
995 {
996 	if (store->sb_page)
997 		chunk += sizeof(bitmap_super_t) << 3;
998 	return chunk & (PAGE_BITS - 1);
999 }
1000 
1001 /*
1002  * return a pointer to the page in the filemap that contains the given bit
1003  *
1004  */
1005 static inline struct page *filemap_get_page(struct bitmap_storage *store,
1006 					    unsigned long chunk)
1007 {
1008 	if (file_page_index(store, chunk) >= store->file_pages)
1009 		return NULL;
1010 	return store->filemap[file_page_index(store, chunk)];
1011 }
1012 
1013 static int md_bitmap_storage_alloc(struct bitmap_storage *store,
1014 				   unsigned long chunks, int with_super,
1015 				   int slot_number)
1016 {
1017 	int pnum, offset = 0;
1018 	unsigned long num_pages;
1019 	unsigned long bytes;
1020 
1021 	bytes = DIV_ROUND_UP(chunks, 8);
1022 	if (with_super)
1023 		bytes += sizeof(bitmap_super_t);
1024 
1025 	num_pages = DIV_ROUND_UP(bytes, PAGE_SIZE);
1026 	offset = slot_number * num_pages;
1027 
1028 	store->filemap = kmalloc_objs(struct page *, num_pages);
1029 	if (!store->filemap)
1030 		return -ENOMEM;
1031 
1032 	if (with_super && !store->sb_page) {
1033 		store->sb_page = alloc_page(GFP_KERNEL|__GFP_ZERO);
1034 		if (store->sb_page == NULL)
1035 			return -ENOMEM;
1036 	}
1037 
1038 	pnum = 0;
1039 	if (store->sb_page) {
1040 		store->filemap[0] = store->sb_page;
1041 		pnum = 1;
1042 		store->sb_index = offset;
1043 	}
1044 
1045 	for ( ; pnum < num_pages; pnum++) {
1046 		store->filemap[pnum] = alloc_page(GFP_KERNEL|__GFP_ZERO);
1047 		if (!store->filemap[pnum]) {
1048 			store->file_pages = pnum;
1049 			return -ENOMEM;
1050 		}
1051 	}
1052 	store->file_pages = pnum;
1053 
1054 	/* We need 4 bits per page, rounded up to a multiple
1055 	 * of sizeof(unsigned long) */
1056 	store->filemap_attr = kzalloc(
1057 		roundup(DIV_ROUND_UP(num_pages*4, 8), sizeof(unsigned long)),
1058 		GFP_KERNEL);
1059 	if (!store->filemap_attr)
1060 		return -ENOMEM;
1061 
1062 	store->bytes = bytes;
1063 
1064 	return 0;
1065 }
1066 
1067 static void md_bitmap_file_unmap(struct bitmap_storage *store)
1068 {
1069 	struct file *file = store->file;
1070 	struct page *sb_page = store->sb_page;
1071 	struct page **map = store->filemap;
1072 	int pages = store->file_pages;
1073 
1074 	while (pages--)
1075 		if (map[pages] != sb_page) /* 0 is sb_page, release it below */
1076 			free_buffers(map[pages]);
1077 	kfree(map);
1078 	kfree(store->filemap_attr);
1079 
1080 	if (sb_page)
1081 		free_buffers(sb_page);
1082 
1083 	if (file) {
1084 		struct inode *inode = file_inode(file);
1085 		invalidate_mapping_pages(inode->i_mapping, 0, -1);
1086 		fput(file);
1087 	}
1088 }
1089 
1090 /*
1091  * bitmap_file_kick - if an error occurs while manipulating the bitmap file
1092  * then it is no longer reliable, so we stop using it and we mark the file
1093  * as failed in the superblock
1094  */
1095 static void md_bitmap_file_kick(struct bitmap *bitmap)
1096 {
1097 	if (!test_and_set_bit(BITMAP_STALE, &bitmap->flags)) {
1098 		bitmap_update_sb(bitmap);
1099 
1100 		if (bitmap->storage.file) {
1101 			pr_warn("%s: kicking failed bitmap file %pD4 from array!\n",
1102 				bmname(bitmap), bitmap->storage.file);
1103 
1104 		} else
1105 			pr_warn("%s: disabling internal bitmap due to errors\n",
1106 				bmname(bitmap));
1107 	}
1108 }
1109 
1110 enum bitmap_page_attr {
1111 	BITMAP_PAGE_DIRTY = 0,     /* there are set bits that need to be synced */
1112 	BITMAP_PAGE_PENDING = 1,   /* there are bits that are being cleaned.
1113 				    * i.e. counter is 1 or 2. */
1114 	BITMAP_PAGE_NEEDWRITE = 2, /* there are cleared bits that need to be synced */
1115 };
1116 
1117 static inline void set_page_attr(struct bitmap *bitmap, int pnum,
1118 				 enum bitmap_page_attr attr)
1119 {
1120 	set_bit((pnum<<2) + attr, bitmap->storage.filemap_attr);
1121 }
1122 
1123 static inline void clear_page_attr(struct bitmap *bitmap, int pnum,
1124 				   enum bitmap_page_attr attr)
1125 {
1126 	clear_bit((pnum<<2) + attr, bitmap->storage.filemap_attr);
1127 }
1128 
1129 static inline int test_page_attr(struct bitmap *bitmap, int pnum,
1130 				 enum bitmap_page_attr attr)
1131 {
1132 	return test_bit((pnum<<2) + attr, bitmap->storage.filemap_attr);
1133 }
1134 
1135 static inline int test_and_clear_page_attr(struct bitmap *bitmap, int pnum,
1136 					   enum bitmap_page_attr attr)
1137 {
1138 	return test_and_clear_bit((pnum<<2) + attr,
1139 				  bitmap->storage.filemap_attr);
1140 }
1141 /*
1142  * bitmap_file_set_bit -- called before performing a write to the md device
1143  * to set (and eventually sync) a particular bit in the bitmap file
1144  *
1145  * we set the bit immediately, then we record the page number so that
1146  * when an unplug occurs, we can flush the dirty pages out to disk
1147  */
1148 static void md_bitmap_file_set_bit(struct bitmap *bitmap, sector_t block)
1149 {
1150 	unsigned long bit;
1151 	struct page *page;
1152 	void *kaddr;
1153 	unsigned long chunk = block >> bitmap->counts.chunkshift;
1154 	struct bitmap_storage *store = &bitmap->storage;
1155 	unsigned long index = file_page_index(store, chunk);
1156 	unsigned long node_offset = 0;
1157 
1158 	index += store->sb_index;
1159 	if (mddev_is_clustered(bitmap->mddev))
1160 		node_offset = bitmap->cluster_slot * store->file_pages;
1161 
1162 	page = filemap_get_page(&bitmap->storage, chunk);
1163 	if (!page)
1164 		return;
1165 	bit = file_page_offset(&bitmap->storage, chunk);
1166 
1167 	/* set the bit */
1168 	kaddr = kmap_local_page(page);
1169 	if (test_bit(BITMAP_HOSTENDIAN, &bitmap->flags))
1170 		set_bit(bit, kaddr);
1171 	else
1172 		set_bit_le(bit, kaddr);
1173 	kunmap_local(kaddr);
1174 	pr_debug("set file bit %lu page %lu\n", bit, index);
1175 	/* record page number so it gets flushed to disk when unplug occurs */
1176 	set_page_attr(bitmap, index - node_offset, BITMAP_PAGE_DIRTY);
1177 }
1178 
1179 static void md_bitmap_file_clear_bit(struct bitmap *bitmap, sector_t block)
1180 {
1181 	unsigned long bit;
1182 	struct page *page;
1183 	void *paddr;
1184 	unsigned long chunk = block >> bitmap->counts.chunkshift;
1185 	struct bitmap_storage *store = &bitmap->storage;
1186 	unsigned long index = file_page_index(store, chunk);
1187 	unsigned long node_offset = 0;
1188 
1189 	index += store->sb_index;
1190 	if (mddev_is_clustered(bitmap->mddev))
1191 		node_offset = bitmap->cluster_slot * store->file_pages;
1192 
1193 	page = filemap_get_page(&bitmap->storage, chunk);
1194 	if (!page)
1195 		return;
1196 	bit = file_page_offset(&bitmap->storage, chunk);
1197 	paddr = kmap_local_page(page);
1198 	if (test_bit(BITMAP_HOSTENDIAN, &bitmap->flags))
1199 		clear_bit(bit, paddr);
1200 	else
1201 		clear_bit_le(bit, paddr);
1202 	kunmap_local(paddr);
1203 	if (!test_page_attr(bitmap, index - node_offset, BITMAP_PAGE_NEEDWRITE)) {
1204 		set_page_attr(bitmap, index - node_offset, BITMAP_PAGE_PENDING);
1205 		bitmap->allclean = 0;
1206 	}
1207 }
1208 
1209 static int md_bitmap_file_test_bit(struct bitmap *bitmap, sector_t block)
1210 {
1211 	unsigned long bit;
1212 	struct page *page;
1213 	void *paddr;
1214 	unsigned long chunk = block >> bitmap->counts.chunkshift;
1215 	int set = 0;
1216 
1217 	page = filemap_get_page(&bitmap->storage, chunk);
1218 	if (!page)
1219 		return -EINVAL;
1220 	bit = file_page_offset(&bitmap->storage, chunk);
1221 	paddr = kmap_local_page(page);
1222 	if (test_bit(BITMAP_HOSTENDIAN, &bitmap->flags))
1223 		set = test_bit(bit, paddr);
1224 	else
1225 		set = test_bit_le(bit, paddr);
1226 	kunmap_local(paddr);
1227 	return set;
1228 }
1229 
1230 /* this gets called when the md device is ready to unplug its underlying
1231  * (slave) device queues -- before we let any writes go down, we need to
1232  * sync the dirty pages of the bitmap file to disk */
1233 static void __bitmap_unplug(struct bitmap *bitmap)
1234 {
1235 	unsigned long i;
1236 	int dirty, need_write;
1237 	int writing = 0;
1238 
1239 	if (!bitmap_enabled(bitmap, true))
1240 		return;
1241 
1242 	/* look at each page to see if there are any set bits that need to be
1243 	 * flushed out to disk */
1244 	for (i = 0; i < bitmap->storage.file_pages; i++) {
1245 		dirty = test_and_clear_page_attr(bitmap, i, BITMAP_PAGE_DIRTY);
1246 		need_write = test_and_clear_page_attr(bitmap, i,
1247 						      BITMAP_PAGE_NEEDWRITE);
1248 		if (dirty || need_write) {
1249 			if (!writing) {
1250 				md_bitmap_wait_writes(bitmap);
1251 				mddev_add_trace_msg(bitmap->mddev,
1252 					"md bitmap_unplug");
1253 			}
1254 			clear_page_attr(bitmap, i, BITMAP_PAGE_PENDING);
1255 			filemap_write_page(bitmap, i, false);
1256 			writing = 1;
1257 		}
1258 	}
1259 	if (writing)
1260 		md_bitmap_wait_writes(bitmap);
1261 
1262 	if (test_bit(BITMAP_WRITE_ERROR, &bitmap->flags))
1263 		md_bitmap_file_kick(bitmap);
1264 }
1265 
1266 struct bitmap_unplug_work {
1267 	struct work_struct work;
1268 	struct bitmap *bitmap;
1269 	struct completion *done;
1270 };
1271 
1272 static void md_bitmap_unplug_fn(struct work_struct *work)
1273 {
1274 	struct bitmap_unplug_work *unplug_work =
1275 		container_of(work, struct bitmap_unplug_work, work);
1276 
1277 	__bitmap_unplug(unplug_work->bitmap);
1278 	complete(unplug_work->done);
1279 }
1280 
1281 static void bitmap_unplug_async(struct bitmap *bitmap)
1282 {
1283 	DECLARE_COMPLETION_ONSTACK(done);
1284 	struct bitmap_unplug_work unplug_work;
1285 
1286 	INIT_WORK_ONSTACK(&unplug_work.work, md_bitmap_unplug_fn);
1287 	unplug_work.bitmap = bitmap;
1288 	unplug_work.done = &done;
1289 
1290 	queue_work(md_bitmap_wq, &unplug_work.work);
1291 	wait_for_completion(&done);
1292 	destroy_work_on_stack(&unplug_work.work);
1293 }
1294 
1295 static void bitmap_unplug(struct mddev *mddev, bool sync)
1296 {
1297 	struct bitmap *bitmap = mddev->bitmap;
1298 
1299 	if (!bitmap)
1300 		return;
1301 
1302 	if (sync)
1303 		__bitmap_unplug(bitmap);
1304 	else
1305 		bitmap_unplug_async(bitmap);
1306 }
1307 
1308 static void md_bitmap_set_memory_bits(struct bitmap *bitmap, sector_t offset, int needed);
1309 
1310 /*
1311  * Initialize the in-memory bitmap from the on-disk bitmap and set up the memory
1312  * mapping of the bitmap file.
1313  *
1314  * Special case: If there's no bitmap file, or if the bitmap file had been
1315  * previously kicked from the array, we mark all the bits as 1's in order to
1316  * cause a full resync.
1317  *
1318  * We ignore all bits for sectors that end earlier than 'start'.
1319  * This is used when reading an out-of-date bitmap.
1320  */
1321 static int md_bitmap_init_from_disk(struct bitmap *bitmap, sector_t start)
1322 {
1323 	bool outofdate = test_bit(BITMAP_STALE, &bitmap->flags);
1324 	struct mddev *mddev = bitmap->mddev;
1325 	unsigned long chunks = bitmap->counts.chunks;
1326 	struct bitmap_storage *store = &bitmap->storage;
1327 	struct file *file = store->file;
1328 	unsigned long node_offset = 0;
1329 	unsigned long bit_cnt = 0;
1330 	unsigned long i;
1331 	int ret;
1332 
1333 	if (!file && !mddev->bitmap_info.offset) {
1334 		/* No permanent bitmap - fill with '1s'. */
1335 		store->filemap = NULL;
1336 		store->file_pages = 0;
1337 		for (i = 0; i < chunks ; i++) {
1338 			/* if the disk bit is set, set the memory bit */
1339 			int needed = ((sector_t)(i+1) << (bitmap->counts.chunkshift)
1340 				      >= start);
1341 			md_bitmap_set_memory_bits(bitmap,
1342 						  (sector_t)i << bitmap->counts.chunkshift,
1343 						  needed);
1344 		}
1345 		return 0;
1346 	}
1347 
1348 	if (file && i_size_read(file->f_mapping->host) < store->bytes) {
1349 		pr_warn("%s: bitmap file too short %lu < %lu\n",
1350 			bmname(bitmap),
1351 			(unsigned long) i_size_read(file->f_mapping->host),
1352 			store->bytes);
1353 		ret = -ENOSPC;
1354 		goto err;
1355 	}
1356 
1357 	if (mddev_is_clustered(mddev))
1358 		node_offset = bitmap->cluster_slot * (DIV_ROUND_UP(store->bytes, PAGE_SIZE));
1359 
1360 	for (i = 0; i < store->file_pages; i++) {
1361 		struct page *page = store->filemap[i];
1362 		int count;
1363 
1364 		/* unmap the old page, we're done with it */
1365 		if (i == store->file_pages - 1)
1366 			count = store->bytes - i * PAGE_SIZE;
1367 		else
1368 			count = PAGE_SIZE;
1369 
1370 		if (file)
1371 			ret = read_file_page(file, i, bitmap, count, page);
1372 		else
1373 			ret = read_sb_page(mddev, 0, page, i + node_offset,
1374 					   count);
1375 		if (ret)
1376 			goto err;
1377 	}
1378 
1379 	if (outofdate) {
1380 		pr_warn("%s: bitmap file is out of date, doing full recovery\n",
1381 			bmname(bitmap));
1382 
1383 		for (i = 0; i < store->file_pages; i++) {
1384 			struct page *page = store->filemap[i];
1385 			unsigned long offset = 0;
1386 			void *paddr;
1387 
1388 			if (i == 0 && !mddev->bitmap_info.external)
1389 				offset = sizeof(bitmap_super_t);
1390 
1391 			/*
1392 			 * If the bitmap is out of date, dirty the whole page
1393 			 * and write it out
1394 			 */
1395 			paddr = kmap_local_page(page);
1396 			memset(paddr + offset, 0xff, PAGE_SIZE - offset);
1397 			kunmap_local(paddr);
1398 
1399 			filemap_write_page(bitmap, i, true);
1400 			if (test_bit(BITMAP_WRITE_ERROR, &bitmap->flags)) {
1401 				ret = -EIO;
1402 				goto err;
1403 			}
1404 		}
1405 	}
1406 
1407 	for (i = 0; i < chunks; i++) {
1408 		struct page *page = filemap_get_page(&bitmap->storage, i);
1409 		unsigned long bit = file_page_offset(&bitmap->storage, i);
1410 		void *paddr;
1411 		bool was_set;
1412 
1413 		paddr = kmap_local_page(page);
1414 		if (test_bit(BITMAP_HOSTENDIAN, &bitmap->flags))
1415 			was_set = test_bit(bit, paddr);
1416 		else
1417 			was_set = test_bit_le(bit, paddr);
1418 		kunmap_local(paddr);
1419 
1420 		if (was_set) {
1421 			/* if the disk bit is set, set the memory bit */
1422 			int needed = ((sector_t)(i+1) << bitmap->counts.chunkshift
1423 				      >= start);
1424 			md_bitmap_set_memory_bits(bitmap,
1425 						  (sector_t)i << bitmap->counts.chunkshift,
1426 						  needed);
1427 			bit_cnt++;
1428 		}
1429 	}
1430 
1431 	pr_debug("%s: bitmap initialized from disk: read %lu pages, set %lu of %lu bits\n",
1432 		 bmname(bitmap), store->file_pages,
1433 		 bit_cnt, chunks);
1434 
1435 	return 0;
1436 
1437  err:
1438 	pr_warn("%s: bitmap initialisation failed: %d\n",
1439 		bmname(bitmap), ret);
1440 	return ret;
1441 }
1442 
1443 /* just flag bitmap pages as needing to be written. */
1444 static void bitmap_write_all(struct mddev *mddev)
1445 {
1446 	int i;
1447 	struct bitmap *bitmap = mddev->bitmap;
1448 
1449 	if (!bitmap || !bitmap->storage.filemap)
1450 		return;
1451 
1452 	/* Only one copy, so nothing needed */
1453 	if (bitmap->storage.file)
1454 		return;
1455 
1456 	for (i = 0; i < bitmap->storage.file_pages; i++)
1457 		set_page_attr(bitmap, i, BITMAP_PAGE_NEEDWRITE);
1458 	bitmap->allclean = 0;
1459 }
1460 
1461 static void md_bitmap_count_page(struct bitmap_counts *bitmap,
1462 				 sector_t offset, int inc)
1463 {
1464 	sector_t chunk = offset >> bitmap->chunkshift;
1465 	unsigned long page = chunk >> PAGE_COUNTER_SHIFT;
1466 	bitmap->bp[page].count += inc;
1467 	md_bitmap_checkfree(bitmap, page);
1468 }
1469 
1470 static void md_bitmap_set_pending(struct bitmap_counts *bitmap, sector_t offset)
1471 {
1472 	sector_t chunk = offset >> bitmap->chunkshift;
1473 	unsigned long page = chunk >> PAGE_COUNTER_SHIFT;
1474 	struct bitmap_page *bp = &bitmap->bp[page];
1475 
1476 	if (!bp->pending)
1477 		bp->pending = 1;
1478 }
1479 
1480 static bitmap_counter_t *md_bitmap_get_counter(struct bitmap_counts *bitmap,
1481 					       sector_t offset, sector_t *blocks,
1482 					       int create);
1483 
1484 static void mddev_set_timeout(struct mddev *mddev, unsigned long timeout,
1485 			      bool force)
1486 {
1487 	struct md_thread *thread;
1488 
1489 	rcu_read_lock();
1490 	thread = rcu_dereference(mddev->thread);
1491 
1492 	if (!thread)
1493 		goto out;
1494 
1495 	if (force || thread->timeout < MAX_SCHEDULE_TIMEOUT)
1496 		thread->timeout = timeout;
1497 
1498 out:
1499 	rcu_read_unlock();
1500 }
1501 
1502 /*
1503  * bitmap daemon -- periodically wakes up to clean bits and flush pages
1504  *			out to disk
1505  */
1506 static void bitmap_daemon_work(struct mddev *mddev)
1507 {
1508 	struct bitmap *bitmap;
1509 	unsigned long j;
1510 	unsigned long nextpage;
1511 	sector_t blocks;
1512 	struct bitmap_counts *counts;
1513 
1514 	/* Use a mutex to guard daemon_work against
1515 	 * bitmap_destroy.
1516 	 */
1517 	mutex_lock(&mddev->bitmap_info.mutex);
1518 	bitmap = mddev->bitmap;
1519 	if (bitmap == NULL) {
1520 		mutex_unlock(&mddev->bitmap_info.mutex);
1521 		return;
1522 	}
1523 	if (time_before(jiffies, bitmap->daemon_lastrun
1524 			+ mddev->bitmap_info.daemon_sleep))
1525 		goto done;
1526 
1527 	bitmap->daemon_lastrun = jiffies;
1528 	if (bitmap->allclean) {
1529 		mddev_set_timeout(mddev, MAX_SCHEDULE_TIMEOUT, true);
1530 		goto done;
1531 	}
1532 	bitmap->allclean = 1;
1533 
1534 	mddev_add_trace_msg(bitmap->mddev, "md bitmap_daemon_work");
1535 
1536 	/* Any file-page which is PENDING now needs to be written.
1537 	 * So set NEEDWRITE now, then after we make any last-minute changes
1538 	 * we will write it.
1539 	 */
1540 	for (j = 0; j < bitmap->storage.file_pages; j++)
1541 		if (test_and_clear_page_attr(bitmap, j,
1542 					     BITMAP_PAGE_PENDING))
1543 			set_page_attr(bitmap, j,
1544 				      BITMAP_PAGE_NEEDWRITE);
1545 
1546 	if (bitmap->need_sync &&
1547 	    mddev->bitmap_info.external == 0) {
1548 		/* Arrange for superblock update as well as
1549 		 * other changes */
1550 		bitmap_super_t *sb;
1551 		bitmap->need_sync = 0;
1552 		if (bitmap->storage.filemap) {
1553 			sb = kmap_local_page(bitmap->storage.sb_page);
1554 			sb->events_cleared =
1555 				cpu_to_le64(bitmap->events_cleared);
1556 			kunmap_local(sb);
1557 			set_page_attr(bitmap, 0,
1558 				      BITMAP_PAGE_NEEDWRITE);
1559 		}
1560 	}
1561 	/* Now look at the bitmap counters and if any are '2' or '1',
1562 	 * decrement and handle accordingly.
1563 	 */
1564 	counts = &bitmap->counts;
1565 	spin_lock_irq(&counts->lock);
1566 	nextpage = 0;
1567 	for (j = 0; j < counts->chunks; j++) {
1568 		bitmap_counter_t *bmc;
1569 		sector_t  block = (sector_t)j << counts->chunkshift;
1570 
1571 		if (j == nextpage) {
1572 			nextpage += PAGE_COUNTER_RATIO;
1573 			if (!counts->bp[j >> PAGE_COUNTER_SHIFT].pending) {
1574 				j |= PAGE_COUNTER_MASK;
1575 				continue;
1576 			}
1577 			counts->bp[j >> PAGE_COUNTER_SHIFT].pending = 0;
1578 		}
1579 
1580 		bmc = md_bitmap_get_counter(counts, block, &blocks, 0);
1581 		if (!bmc) {
1582 			j |= PAGE_COUNTER_MASK;
1583 			continue;
1584 		}
1585 		if (*bmc == 1 && !bitmap->need_sync) {
1586 			/* We can clear the bit */
1587 			*bmc = 0;
1588 			md_bitmap_count_page(counts, block, -1);
1589 			md_bitmap_file_clear_bit(bitmap, block);
1590 		} else if (*bmc && *bmc <= 2) {
1591 			*bmc = 1;
1592 			md_bitmap_set_pending(counts, block);
1593 			bitmap->allclean = 0;
1594 		}
1595 	}
1596 	spin_unlock_irq(&counts->lock);
1597 
1598 	md_bitmap_wait_writes(bitmap);
1599 	/* Now start writeout on any page in NEEDWRITE that isn't DIRTY.
1600 	 * DIRTY pages need to be written by bitmap_unplug so it can wait
1601 	 * for them.
1602 	 * If we find any DIRTY page we stop there and let bitmap_unplug
1603 	 * handle all the rest.  This is important in the case where
1604 	 * the first blocking holds the superblock and it has been updated.
1605 	 * We mustn't write any other blocks before the superblock.
1606 	 */
1607 	for (j = 0;
1608 	     j < bitmap->storage.file_pages
1609 		     && !test_bit(BITMAP_STALE, &bitmap->flags);
1610 	     j++) {
1611 		if (test_page_attr(bitmap, j,
1612 				   BITMAP_PAGE_DIRTY))
1613 			/* bitmap_unplug will handle the rest */
1614 			break;
1615 		if (bitmap->storage.filemap &&
1616 		    test_and_clear_page_attr(bitmap, j,
1617 					     BITMAP_PAGE_NEEDWRITE))
1618 			filemap_write_page(bitmap, j, false);
1619 	}
1620 
1621  done:
1622 	if (bitmap->allclean == 0)
1623 		mddev_set_timeout(mddev, mddev->bitmap_info.daemon_sleep, true);
1624 	mutex_unlock(&mddev->bitmap_info.mutex);
1625 }
1626 
1627 static bitmap_counter_t *md_bitmap_get_counter(struct bitmap_counts *bitmap,
1628 					       sector_t offset, sector_t *blocks,
1629 					       int create)
1630 __releases(bitmap->lock)
1631 __acquires(bitmap->lock)
1632 {
1633 	/* If 'create', we might release the lock and reclaim it.
1634 	 * The lock must have been taken with interrupts enabled.
1635 	 * If !create, we don't release the lock.
1636 	 */
1637 	sector_t chunk = offset >> bitmap->chunkshift;
1638 	unsigned long page = chunk >> PAGE_COUNTER_SHIFT;
1639 	unsigned long pageoff = (chunk & PAGE_COUNTER_MASK) << COUNTER_BYTE_SHIFT;
1640 	sector_t csize = ((sector_t)1) << bitmap->chunkshift;
1641 	int err;
1642 
1643 	if (page >= bitmap->pages) {
1644 		/*
1645 		 * This can happen if bitmap_start_sync goes beyond
1646 		 * End-of-device while looking for a whole page or
1647 		 * user set a huge number to sysfs bitmap_set_bits.
1648 		 */
1649 		*blocks = csize - (offset & (csize - 1));
1650 		return NULL;
1651 	}
1652 	err = md_bitmap_checkpage(bitmap, page, create, 0);
1653 
1654 	if (bitmap->bp[page].hijacked ||
1655 	    bitmap->bp[page].map == NULL)
1656 		csize = ((sector_t)1) << (bitmap->chunkshift +
1657 					  PAGE_COUNTER_SHIFT);
1658 
1659 	*blocks = csize - (offset & (csize - 1));
1660 
1661 	if (err < 0)
1662 		return NULL;
1663 
1664 	/* now locked ... */
1665 
1666 	if (bitmap->bp[page].hijacked) { /* hijacked pointer */
1667 		/* should we use the first or second counter field
1668 		 * of the hijacked pointer? */
1669 		int hi = (pageoff > PAGE_COUNTER_MASK);
1670 		return  &((bitmap_counter_t *)
1671 			  &bitmap->bp[page].map)[hi];
1672 	} else /* page is allocated */
1673 		return (bitmap_counter_t *)
1674 			&(bitmap->bp[page].map[pageoff]);
1675 }
1676 
1677 static void bitmap_start_write(struct mddev *mddev, sector_t offset,
1678 			       unsigned long sectors)
1679 {
1680 	struct bitmap *bitmap = mddev->bitmap;
1681 
1682 	if (!bitmap)
1683 		return;
1684 
1685 	while (sectors) {
1686 		sector_t blocks;
1687 		bitmap_counter_t *bmc;
1688 
1689 		spin_lock_irq(&bitmap->counts.lock);
1690 		bmc = md_bitmap_get_counter(&bitmap->counts, offset, &blocks, 1);
1691 		if (!bmc) {
1692 			spin_unlock_irq(&bitmap->counts.lock);
1693 			return;
1694 		}
1695 
1696 		if (unlikely(COUNTER(*bmc) == COUNTER_MAX)) {
1697 			DEFINE_WAIT(__wait);
1698 			/* note that it is safe to do the prepare_to_wait
1699 			 * after the test as long as we do it before dropping
1700 			 * the spinlock.
1701 			 */
1702 			prepare_to_wait(&bitmap->overflow_wait, &__wait,
1703 					TASK_UNINTERRUPTIBLE);
1704 			spin_unlock_irq(&bitmap->counts.lock);
1705 			schedule();
1706 			finish_wait(&bitmap->overflow_wait, &__wait);
1707 			continue;
1708 		}
1709 
1710 		switch (*bmc) {
1711 		case 0:
1712 			md_bitmap_file_set_bit(bitmap, offset);
1713 			md_bitmap_count_page(&bitmap->counts, offset, 1);
1714 			fallthrough;
1715 		case 1:
1716 			*bmc = 2;
1717 		}
1718 
1719 		(*bmc)++;
1720 
1721 		spin_unlock_irq(&bitmap->counts.lock);
1722 
1723 		offset += blocks;
1724 		if (sectors > blocks)
1725 			sectors -= blocks;
1726 		else
1727 			sectors = 0;
1728 	}
1729 }
1730 
1731 static void bitmap_prepare_range(struct mddev *mddev, sector_t *offset,
1732 				 unsigned long *sectors, bool discard)
1733 {
1734 	if (mddev->pers->bitmap_sector)
1735 		mddev->pers->bitmap_sector(mddev, offset, sectors);
1736 }
1737 
1738 static void bitmap_end_write(struct mddev *mddev, sector_t offset,
1739 			     unsigned long sectors)
1740 {
1741 	struct bitmap *bitmap = mddev->bitmap;
1742 
1743 	if (!bitmap)
1744 		return;
1745 
1746 	while (sectors) {
1747 		sector_t blocks;
1748 		unsigned long flags;
1749 		bitmap_counter_t *bmc;
1750 
1751 		spin_lock_irqsave(&bitmap->counts.lock, flags);
1752 		bmc = md_bitmap_get_counter(&bitmap->counts, offset, &blocks, 0);
1753 		if (!bmc) {
1754 			spin_unlock_irqrestore(&bitmap->counts.lock, flags);
1755 			return;
1756 		}
1757 
1758 		if (!bitmap->mddev->degraded) {
1759 			if (bitmap->events_cleared < bitmap->mddev->events) {
1760 				bitmap->events_cleared = bitmap->mddev->events;
1761 				bitmap->need_sync = 1;
1762 				sysfs_notify_dirent_safe(
1763 						bitmap->sysfs_can_clear);
1764 			}
1765 		} else if (!NEEDED(*bmc)) {
1766 			*bmc |= NEEDED_MASK;
1767 		}
1768 
1769 		if (COUNTER(*bmc) == COUNTER_MAX)
1770 			wake_up(&bitmap->overflow_wait);
1771 
1772 		(*bmc)--;
1773 		if (*bmc <= 2) {
1774 			md_bitmap_set_pending(&bitmap->counts, offset);
1775 			bitmap->allclean = 0;
1776 		}
1777 		spin_unlock_irqrestore(&bitmap->counts.lock, flags);
1778 		offset += blocks;
1779 		if (sectors > blocks)
1780 			sectors -= blocks;
1781 		else
1782 			sectors = 0;
1783 	}
1784 }
1785 
1786 static bool __bitmap_start_sync(struct bitmap *bitmap, sector_t offset,
1787 				sector_t *blocks, bool degraded)
1788 {
1789 	bitmap_counter_t *bmc;
1790 	bool rv = false;
1791 
1792 	spin_lock_irq(&bitmap->counts.lock);
1793 	bmc = md_bitmap_get_counter(&bitmap->counts, offset, blocks, 0);
1794 	if (bmc) {
1795 		/* locked */
1796 		if (RESYNC(*bmc)) {
1797 			rv = true;
1798 		} else if (NEEDED(*bmc)) {
1799 			rv = true;
1800 			if (!degraded) { /* don't set/clear bits if degraded */
1801 				*bmc |= RESYNC_MASK;
1802 				*bmc &= ~NEEDED_MASK;
1803 			}
1804 		}
1805 	}
1806 	spin_unlock_irq(&bitmap->counts.lock);
1807 
1808 	return rv;
1809 }
1810 
1811 static bool bitmap_start_sync(struct mddev *mddev, sector_t offset,
1812 			      sector_t *blocks, bool degraded)
1813 {
1814 	/* bitmap_start_sync must always report on multiples of whole
1815 	 * pages, otherwise resync (which is very PAGE_SIZE based) will
1816 	 * get confused.
1817 	 * So call __bitmap_start_sync repeatedly (if needed) until
1818 	 * At least PAGE_SIZE>>9 blocks are covered.
1819 	 * Return the 'or' of the result.
1820 	 */
1821 	bool rv = false;
1822 	sector_t blocks1;
1823 
1824 	*blocks = 0;
1825 	while (*blocks < (PAGE_SIZE>>9)) {
1826 		rv |= __bitmap_start_sync(mddev->bitmap, offset,
1827 					  &blocks1, degraded);
1828 		offset += blocks1;
1829 		*blocks += blocks1;
1830 	}
1831 
1832 	return rv;
1833 }
1834 
1835 static void __bitmap_end_sync(struct bitmap *bitmap, sector_t offset,
1836 			      sector_t *blocks, bool aborted)
1837 {
1838 	bitmap_counter_t *bmc;
1839 	unsigned long flags;
1840 
1841 	spin_lock_irqsave(&bitmap->counts.lock, flags);
1842 	bmc = md_bitmap_get_counter(&bitmap->counts, offset, blocks, 0);
1843 	if (bmc == NULL)
1844 		goto unlock;
1845 	/* locked */
1846 	if (RESYNC(*bmc)) {
1847 		*bmc &= ~RESYNC_MASK;
1848 
1849 		if (!NEEDED(*bmc) && aborted)
1850 			*bmc |= NEEDED_MASK;
1851 		else {
1852 			if (*bmc <= 2) {
1853 				md_bitmap_set_pending(&bitmap->counts, offset);
1854 				bitmap->allclean = 0;
1855 			}
1856 		}
1857 	}
1858  unlock:
1859 	spin_unlock_irqrestore(&bitmap->counts.lock, flags);
1860 }
1861 
1862 static void bitmap_end_sync(struct mddev *mddev, sector_t offset,
1863 			    sector_t *blocks)
1864 {
1865 	__bitmap_end_sync(mddev->bitmap, offset, blocks, true);
1866 }
1867 
1868 static void bitmap_close_sync(struct mddev *mddev)
1869 {
1870 	/* Sync has finished, and any bitmap chunks that weren't synced
1871 	 * properly have been aborted.  It remains to us to clear the
1872 	 * RESYNC bit wherever it is still on
1873 	 */
1874 	sector_t sector = 0;
1875 	sector_t blocks;
1876 	struct bitmap *bitmap = mddev->bitmap;
1877 
1878 	if (!bitmap)
1879 		return;
1880 
1881 	while (sector < bitmap->mddev->resync_max_sectors) {
1882 		__bitmap_end_sync(bitmap, sector, &blocks, false);
1883 		sector += blocks;
1884 	}
1885 }
1886 
1887 static void bitmap_cond_end_sync(struct mddev *mddev, sector_t sector,
1888 				 bool force)
1889 {
1890 	sector_t s = 0;
1891 	sector_t blocks;
1892 	struct bitmap *bitmap = mddev->bitmap;
1893 
1894 	if (!bitmap)
1895 		return;
1896 	if (sector == 0) {
1897 		bitmap->last_end_sync = jiffies;
1898 		return;
1899 	}
1900 	if (!force && time_before(jiffies, (bitmap->last_end_sync
1901 				  + bitmap->mddev->bitmap_info.daemon_sleep)))
1902 		return;
1903 	wait_event(bitmap->mddev->recovery_wait,
1904 		   atomic_read(&bitmap->mddev->recovery_active) == 0);
1905 
1906 	bitmap->mddev->curr_resync_completed = sector;
1907 	set_bit(MD_SB_CHANGE_CLEAN, &bitmap->mddev->sb_flags);
1908 	sector &= ~((1ULL << bitmap->counts.chunkshift) - 1);
1909 	s = 0;
1910 	while (s < sector && s < bitmap->mddev->resync_max_sectors) {
1911 		__bitmap_end_sync(bitmap, s, &blocks, false);
1912 		s += blocks;
1913 	}
1914 	bitmap->last_end_sync = jiffies;
1915 	sysfs_notify_dirent_safe(bitmap->mddev->sysfs_completed);
1916 }
1917 
1918 static void bitmap_sync_with_cluster(struct mddev *mddev,
1919 				     sector_t old_lo, sector_t old_hi,
1920 				     sector_t new_lo, sector_t new_hi)
1921 {
1922 	struct bitmap *bitmap = mddev->bitmap;
1923 	sector_t sector, blocks = 0;
1924 
1925 	for (sector = old_lo; sector < new_lo; ) {
1926 		__bitmap_end_sync(bitmap, sector, &blocks, false);
1927 		sector += blocks;
1928 	}
1929 	WARN((blocks > new_lo) && old_lo, "alignment is not correct for lo\n");
1930 
1931 	for (sector = old_hi; sector < new_hi; ) {
1932 		bitmap_start_sync(mddev, sector, &blocks, false);
1933 		sector += blocks;
1934 	}
1935 	WARN((blocks > new_hi) && old_hi, "alignment is not correct for hi\n");
1936 }
1937 
1938 static void md_bitmap_set_memory_bits(struct bitmap *bitmap, sector_t offset, int needed)
1939 {
1940 	/* For each chunk covered by any of these sectors, set the
1941 	 * counter to 2 and possibly set resync_needed.  They should all
1942 	 * be 0 at this point
1943 	 */
1944 
1945 	sector_t secs;
1946 	bitmap_counter_t *bmc;
1947 	spin_lock_irq(&bitmap->counts.lock);
1948 	bmc = md_bitmap_get_counter(&bitmap->counts, offset, &secs, 1);
1949 	if (!bmc) {
1950 		spin_unlock_irq(&bitmap->counts.lock);
1951 		return;
1952 	}
1953 	if (!*bmc) {
1954 		*bmc = 2;
1955 		md_bitmap_count_page(&bitmap->counts, offset, 1);
1956 		md_bitmap_set_pending(&bitmap->counts, offset);
1957 		bitmap->allclean = 0;
1958 	}
1959 	if (needed)
1960 		*bmc |= NEEDED_MASK;
1961 	spin_unlock_irq(&bitmap->counts.lock);
1962 }
1963 
1964 /* dirty the memory and file bits for bitmap chunks "s" to "e" */
1965 static void bitmap_dirty_bits(struct mddev *mddev, unsigned long s,
1966 			      unsigned long e)
1967 {
1968 	unsigned long chunk;
1969 	struct bitmap *bitmap = mddev->bitmap;
1970 
1971 	if (!bitmap)
1972 		return;
1973 
1974 	for (chunk = s; chunk <= e; chunk++) {
1975 		sector_t sec = (sector_t)chunk << bitmap->counts.chunkshift;
1976 
1977 		md_bitmap_set_memory_bits(bitmap, sec, 1);
1978 		md_bitmap_file_set_bit(bitmap, sec);
1979 		if (sec < bitmap->mddev->resync_offset)
1980 			/* We are asserting that the array is dirty,
1981 			 * so move the resync_offset address back so
1982 			 * that it is obvious that it is dirty
1983 			 */
1984 			bitmap->mddev->resync_offset = sec;
1985 	}
1986 }
1987 
1988 static void bitmap_flush(struct mddev *mddev)
1989 {
1990 	struct bitmap *bitmap = mddev->bitmap;
1991 	long sleep;
1992 
1993 	if (!bitmap) /* there was no bitmap */
1994 		return;
1995 
1996 	/* run the daemon_work three time to ensure everything is flushed
1997 	 * that can be
1998 	 */
1999 	sleep = mddev->bitmap_info.daemon_sleep * 2;
2000 	bitmap->daemon_lastrun -= sleep;
2001 	bitmap_daemon_work(mddev);
2002 	bitmap->daemon_lastrun -= sleep;
2003 	bitmap_daemon_work(mddev);
2004 	bitmap->daemon_lastrun -= sleep;
2005 	bitmap_daemon_work(mddev);
2006 	if (mddev->bitmap_info.external)
2007 		md_super_wait(mddev);
2008 	bitmap_update_sb(bitmap);
2009 }
2010 
2011 static void md_bitmap_free(void *data)
2012 {
2013 	unsigned long k, pages;
2014 	struct bitmap_page *bp;
2015 	struct bitmap *bitmap = data;
2016 
2017 	if (!bitmap) /* there was no bitmap */
2018 		return;
2019 
2020 	if (bitmap->sysfs_can_clear)
2021 		sysfs_put(bitmap->sysfs_can_clear);
2022 
2023 	if (mddev_is_clustered(bitmap->mddev) && bitmap->mddev->cluster_info &&
2024 		bitmap->cluster_slot == bitmap->mddev->cluster_ops->slot_number(bitmap->mddev))
2025 		md_cluster_stop(bitmap->mddev);
2026 
2027 	/* Shouldn't be needed - but just in case.... */
2028 	wait_event(bitmap->write_wait,
2029 		   atomic_read(&bitmap->pending_writes) == 0);
2030 
2031 	/* release the bitmap file  */
2032 	md_bitmap_file_unmap(&bitmap->storage);
2033 
2034 	bp = bitmap->counts.bp;
2035 	pages = bitmap->counts.pages;
2036 
2037 	/* free all allocated memory */
2038 
2039 	if (bp) /* deallocate the page memory */
2040 		for (k = 0; k < pages; k++)
2041 			if (bp[k].map && !bp[k].hijacked)
2042 				kfree(bp[k].map);
2043 	kfree(bp);
2044 	kfree(bitmap);
2045 }
2046 
2047 static void bitmap_start_behind_write(struct mddev *mddev)
2048 {
2049 	struct bitmap *bitmap = mddev->bitmap;
2050 	int bw;
2051 
2052 	atomic_inc(&bitmap->behind_writes);
2053 	bw = atomic_read(&bitmap->behind_writes);
2054 	if (bw > bitmap->behind_writes_used)
2055 		bitmap->behind_writes_used = bw;
2056 
2057 	pr_debug("inc write-behind count %d/%lu\n",
2058 		 bw, bitmap->mddev->bitmap_info.max_write_behind);
2059 }
2060 
2061 static void bitmap_end_behind_write(struct mddev *mddev)
2062 {
2063 	struct bitmap *bitmap = mddev->bitmap;
2064 
2065 	if (atomic_dec_and_test(&bitmap->behind_writes))
2066 		wake_up(&bitmap->behind_wait);
2067 	pr_debug("dec write-behind count %d/%lu\n",
2068 		 atomic_read(&bitmap->behind_writes),
2069 		 bitmap->mddev->bitmap_info.max_write_behind);
2070 }
2071 
2072 static void bitmap_wait_behind_writes(struct mddev *mddev)
2073 {
2074 	struct bitmap *bitmap = mddev->bitmap;
2075 
2076 	/* wait for behind writes to complete */
2077 	if (bitmap && atomic_read(&bitmap->behind_writes) > 0) {
2078 		pr_debug("md:%s: behind writes in progress - waiting to stop.\n",
2079 			 mdname(mddev));
2080 		/* need to kick something here to make sure I/O goes? */
2081 		wait_event(bitmap->behind_wait,
2082 			   atomic_read(&bitmap->behind_writes) == 0);
2083 	}
2084 }
2085 
2086 static void bitmap_destroy(struct mddev *mddev)
2087 {
2088 	struct bitmap *bitmap = mddev->bitmap;
2089 
2090 	if (!bitmap) /* there was no bitmap */
2091 		return;
2092 
2093 	bitmap_wait_behind_writes(mddev);
2094 	if (!test_bit(MD_SERIALIZE_POLICY, &mddev->flags))
2095 		mddev_destroy_serial_pool(mddev, NULL);
2096 
2097 	mutex_lock(&mddev->bitmap_info.mutex);
2098 	spin_lock(&mddev->lock);
2099 	mddev->bitmap = NULL; /* disconnect from the md device */
2100 	spin_unlock(&mddev->lock);
2101 	mutex_unlock(&mddev->bitmap_info.mutex);
2102 	mddev_set_timeout(mddev, MAX_SCHEDULE_TIMEOUT, true);
2103 
2104 	md_bitmap_free(bitmap);
2105 }
2106 
2107 /*
2108  * initialize the bitmap structure
2109  * if this returns an error, bitmap_destroy must be called to do clean up
2110  * once mddev->bitmap is set
2111  */
2112 static struct bitmap *__bitmap_create(struct mddev *mddev, int slot)
2113 {
2114 	struct bitmap *bitmap;
2115 	sector_t blocks = mddev->resync_max_sectors;
2116 	struct file *file = mddev->bitmap_info.file;
2117 	int err;
2118 	struct kernfs_node *bm = NULL;
2119 
2120 	BUILD_BUG_ON(sizeof(bitmap_super_t) != 256);
2121 
2122 	BUG_ON(file && mddev->bitmap_info.offset);
2123 
2124 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
2125 		pr_notice("md/raid:%s: array with journal cannot have bitmap\n",
2126 			  mdname(mddev));
2127 		return ERR_PTR(-EBUSY);
2128 	}
2129 
2130 	bitmap = kzalloc_obj(*bitmap);
2131 	if (!bitmap)
2132 		return ERR_PTR(-ENOMEM);
2133 
2134 	spin_lock_init(&bitmap->counts.lock);
2135 	atomic_set(&bitmap->pending_writes, 0);
2136 	init_waitqueue_head(&bitmap->write_wait);
2137 	init_waitqueue_head(&bitmap->overflow_wait);
2138 	init_waitqueue_head(&bitmap->behind_wait);
2139 
2140 	bitmap->mddev = mddev;
2141 	bitmap->cluster_slot = slot;
2142 
2143 	if (mddev->kobj.sd)
2144 		bm = sysfs_get_dirent(mddev->kobj.sd, "bitmap");
2145 	if (bm) {
2146 		bitmap->sysfs_can_clear = sysfs_get_dirent(bm, "can_clear");
2147 		sysfs_put(bm);
2148 	} else
2149 		bitmap->sysfs_can_clear = NULL;
2150 
2151 	bitmap->storage.file = file;
2152 	if (file) {
2153 		get_file(file);
2154 		/* As future accesses to this file will use bmap,
2155 		 * and bypass the page cache, we must sync the file
2156 		 * first.
2157 		 */
2158 		vfs_fsync(file, 1);
2159 	}
2160 	/* read superblock from bitmap file (this sets mddev->bitmap_info.chunksize) */
2161 	if (!mddev->bitmap_info.external) {
2162 		/*
2163 		 * If 'MD_ARRAY_FIRST_USE' is set, then device-mapper is
2164 		 * instructing us to create a new on-disk bitmap instance.
2165 		 */
2166 		if (test_and_clear_bit(MD_ARRAY_FIRST_USE, &mddev->flags))
2167 			err = md_bitmap_new_disk_sb(bitmap);
2168 		else
2169 			err = md_bitmap_read_sb(bitmap);
2170 	} else {
2171 		err = 0;
2172 		if (mddev->bitmap_info.chunksize == 0 ||
2173 		    mddev->bitmap_info.daemon_sleep == 0)
2174 			/* chunksize and time_base need to be
2175 			 * set first. */
2176 			err = -EINVAL;
2177 	}
2178 	if (err)
2179 		goto error;
2180 
2181 	bitmap->daemon_lastrun = jiffies;
2182 	err = __bitmap_resize(bitmap, blocks, mddev->bitmap_info.chunksize,
2183 			      true);
2184 	if (err)
2185 		goto error;
2186 
2187 	pr_debug("created bitmap (%lu pages) for device %s\n",
2188 		 bitmap->counts.pages, bmname(bitmap));
2189 
2190 	err = test_bit(BITMAP_WRITE_ERROR, &bitmap->flags) ? -EIO : 0;
2191 	if (err)
2192 		goto error;
2193 
2194 	return bitmap;
2195  error:
2196 	md_bitmap_free(bitmap);
2197 	return ERR_PTR(err);
2198 }
2199 
2200 static int bitmap_create(struct mddev *mddev)
2201 {
2202 	struct bitmap *bitmap = __bitmap_create(mddev, -1);
2203 
2204 	if (IS_ERR(bitmap))
2205 		return PTR_ERR(bitmap);
2206 
2207 	mddev->bitmap = bitmap;
2208 	return 0;
2209 }
2210 
2211 static int bitmap_load(struct mddev *mddev)
2212 {
2213 	int err = 0;
2214 	sector_t start = 0;
2215 	sector_t sector = 0;
2216 	struct bitmap *bitmap = mddev->bitmap;
2217 	struct md_rdev *rdev;
2218 
2219 	if (!bitmap)
2220 		goto out;
2221 
2222 	rdev_for_each(rdev, mddev)
2223 		mddev_create_serial_pool(mddev, rdev);
2224 
2225 	if (mddev_is_clustered(mddev))
2226 		mddev->cluster_ops->load_bitmaps(mddev, mddev->bitmap_info.nodes);
2227 
2228 	/* Clear out old bitmap info first:  Either there is none, or we
2229 	 * are resuming after someone else has possibly changed things,
2230 	 * so we should forget old cached info.
2231 	 * All chunks should be clean, but some might need_sync.
2232 	 */
2233 	while (sector < mddev->resync_max_sectors) {
2234 		sector_t blocks;
2235 		bitmap_start_sync(mddev, sector, &blocks, false);
2236 		sector += blocks;
2237 	}
2238 	bitmap_close_sync(mddev);
2239 
2240 	if (mddev->degraded == 0
2241 	    || bitmap->events_cleared == mddev->events)
2242 		/* no need to keep dirty bits to optimise a
2243 		 * re-add of a missing device */
2244 		start = mddev->resync_offset;
2245 
2246 	mutex_lock(&mddev->bitmap_info.mutex);
2247 	err = md_bitmap_init_from_disk(bitmap, start);
2248 	mutex_unlock(&mddev->bitmap_info.mutex);
2249 
2250 	if (err)
2251 		goto out;
2252 	clear_bit(BITMAP_STALE, &bitmap->flags);
2253 
2254 	/* Kick recovery in case any bits were set */
2255 	set_bit(MD_RECOVERY_NEEDED, &bitmap->mddev->recovery);
2256 
2257 	mddev_set_timeout(mddev, mddev->bitmap_info.daemon_sleep, true);
2258 	md_wakeup_thread(mddev->thread);
2259 
2260 	bitmap_update_sb(bitmap);
2261 
2262 	if (test_bit(BITMAP_WRITE_ERROR, &bitmap->flags))
2263 		err = -EIO;
2264 out:
2265 	return err;
2266 }
2267 
2268 /* caller need to free returned bitmap with md_bitmap_free() */
2269 static void *bitmap_get_from_slot(struct mddev *mddev, int slot)
2270 {
2271 	int rv = 0;
2272 	struct bitmap *bitmap;
2273 
2274 	bitmap = __bitmap_create(mddev, slot);
2275 	if (IS_ERR(bitmap)) {
2276 		rv = PTR_ERR(bitmap);
2277 		return ERR_PTR(rv);
2278 	}
2279 
2280 	rv = md_bitmap_init_from_disk(bitmap, 0);
2281 	if (rv) {
2282 		md_bitmap_free(bitmap);
2283 		return ERR_PTR(rv);
2284 	}
2285 
2286 	return bitmap;
2287 }
2288 
2289 /* Loads the bitmap associated with slot and copies the resync information
2290  * to our bitmap
2291  */
2292 static int bitmap_copy_from_slot(struct mddev *mddev, int slot, sector_t *low,
2293 				 sector_t *high, bool clear_bits)
2294 {
2295 	int rv = 0, i, j;
2296 	sector_t block, lo = 0, hi = 0;
2297 	struct bitmap_counts *counts;
2298 	struct bitmap *bitmap;
2299 
2300 	bitmap = bitmap_get_from_slot(mddev, slot);
2301 	if (IS_ERR(bitmap)) {
2302 		pr_err("%s can't get bitmap from slot %d\n", __func__, slot);
2303 		return -1;
2304 	}
2305 
2306 	counts = &bitmap->counts;
2307 	for (j = 0; j < counts->chunks; j++) {
2308 		block = (sector_t)j << counts->chunkshift;
2309 		if (md_bitmap_file_test_bit(bitmap, block)) {
2310 			if (!lo)
2311 				lo = block;
2312 			hi = block;
2313 			md_bitmap_file_clear_bit(bitmap, block);
2314 			md_bitmap_set_memory_bits(mddev->bitmap, block, 1);
2315 			md_bitmap_file_set_bit(mddev->bitmap, block);
2316 		}
2317 	}
2318 
2319 	if (clear_bits) {
2320 		bitmap_update_sb(bitmap);
2321 		/* BITMAP_PAGE_PENDING is set, but bitmap_unplug needs
2322 		 * BITMAP_PAGE_DIRTY or _NEEDWRITE to write ... */
2323 		for (i = 0; i < bitmap->storage.file_pages; i++)
2324 			if (test_page_attr(bitmap, i, BITMAP_PAGE_PENDING))
2325 				set_page_attr(bitmap, i, BITMAP_PAGE_NEEDWRITE);
2326 		__bitmap_unplug(bitmap);
2327 	}
2328 	__bitmap_unplug(mddev->bitmap);
2329 	*low = lo;
2330 	*high = hi;
2331 	md_bitmap_free(bitmap);
2332 
2333 	return rv;
2334 }
2335 
2336 static void bitmap_set_pages(void *data, unsigned long pages)
2337 {
2338 	struct bitmap *bitmap = data;
2339 
2340 	bitmap->counts.pages = pages;
2341 }
2342 
2343 static int bitmap_get_stats(void *data, struct md_bitmap_stats *stats)
2344 {
2345 	struct bitmap_storage *storage;
2346 	struct bitmap_counts *counts;
2347 	struct bitmap *bitmap = data;
2348 	bitmap_super_t *sb;
2349 
2350 	if (!bitmap)
2351 		return -ENOENT;
2352 	if (!bitmap->storage.sb_page)
2353 		return -EINVAL;
2354 	sb = kmap_local_page(bitmap->storage.sb_page);
2355 	stats->sync_size = le64_to_cpu(sb->sync_size);
2356 	kunmap_local(sb);
2357 
2358 	counts = &bitmap->counts;
2359 	stats->missing_pages = counts->missing_pages;
2360 	stats->pages = counts->pages;
2361 
2362 	storage = &bitmap->storage;
2363 	stats->file_pages = storage->file_pages;
2364 	stats->file = storage->file;
2365 
2366 	stats->behind_writes = atomic_read(&bitmap->behind_writes);
2367 	stats->behind_wait = wq_has_sleeper(&bitmap->behind_wait);
2368 	stats->events_cleared = bitmap->events_cleared;
2369 	return 0;
2370 }
2371 
2372 static int __bitmap_resize(struct bitmap *bitmap, sector_t blocks,
2373 			   int chunksize, bool init)
2374 {
2375 	/* If chunk_size is 0, choose an appropriate chunk size.
2376 	 * Then possibly allocate new storage space.
2377 	 * Then quiesce, copy bits, replace bitmap, and re-start
2378 	 *
2379 	 * This function is called both to set up the initial bitmap
2380 	 * and to resize the bitmap while the array is active.
2381 	 * If this happens as a result of the array being resized,
2382 	 * chunksize will be zero, and we need to choose a suitable
2383 	 * chunksize, otherwise we use what we are given.
2384 	 */
2385 	struct bitmap_storage store;
2386 	struct bitmap_counts old_counts;
2387 	unsigned long chunks;
2388 	sector_t block;
2389 	sector_t old_blocks, new_blocks;
2390 	int chunkshift;
2391 	int ret = 0;
2392 	long pages;
2393 	struct bitmap_page *new_bp;
2394 
2395 	if (bitmap->storage.file && !init) {
2396 		pr_info("md: cannot resize file-based bitmap\n");
2397 		return -EINVAL;
2398 	}
2399 
2400 	if (chunksize == 0) {
2401 		/* If there is enough space, leave the chunk size unchanged,
2402 		 * else increase by factor of two until there is enough space.
2403 		 */
2404 		long bytes;
2405 		long space = bitmap->mddev->bitmap_info.space;
2406 
2407 		if (space == 0) {
2408 			/* We don't know how much space there is, so limit
2409 			 * to current size - in sectors.
2410 			 */
2411 			bytes = DIV_ROUND_UP(bitmap->counts.chunks, 8);
2412 			if (!bitmap->mddev->bitmap_info.external)
2413 				bytes += sizeof(bitmap_super_t);
2414 			space = DIV_ROUND_UP(bytes, 512);
2415 			bitmap->mddev->bitmap_info.space = space;
2416 		}
2417 		chunkshift = bitmap->counts.chunkshift;
2418 		chunkshift--;
2419 		do {
2420 			/* 'chunkshift' is shift from block size to chunk size */
2421 			chunkshift++;
2422 			chunks = DIV_ROUND_UP_SECTOR_T(blocks, 1 << chunkshift);
2423 			bytes = DIV_ROUND_UP(chunks, 8);
2424 			if (!bitmap->mddev->bitmap_info.external)
2425 				bytes += sizeof(bitmap_super_t);
2426 		} while (bytes > (space << 9) && (chunkshift + BITMAP_BLOCK_SHIFT) <
2427 			(BITS_PER_BYTE * sizeof(((bitmap_super_t *)0)->chunksize) - 1));
2428 	} else
2429 		chunkshift = ffz(~chunksize) - BITMAP_BLOCK_SHIFT;
2430 
2431 	chunks = DIV_ROUND_UP_SECTOR_T(blocks, 1 << chunkshift);
2432 	memset(&store, 0, sizeof(store));
2433 	if (bitmap->mddev->bitmap_info.offset || bitmap->mddev->bitmap_info.file)
2434 		ret = md_bitmap_storage_alloc(&store, chunks,
2435 					      !bitmap->mddev->bitmap_info.external,
2436 					      mddev_is_clustered(bitmap->mddev)
2437 					      ? bitmap->cluster_slot : 0);
2438 	if (ret) {
2439 		md_bitmap_file_unmap(&store);
2440 		goto err;
2441 	}
2442 
2443 	pages = DIV_ROUND_UP(chunks, PAGE_COUNTER_RATIO);
2444 
2445 	new_bp = kzalloc_objs(*new_bp, pages);
2446 	ret = -ENOMEM;
2447 	if (!new_bp) {
2448 		md_bitmap_file_unmap(&store);
2449 		goto err;
2450 	}
2451 
2452 	if (!init)
2453 		bitmap->mddev->pers->quiesce(bitmap->mddev, 1);
2454 
2455 	store.file = bitmap->storage.file;
2456 	bitmap->storage.file = NULL;
2457 
2458 	if (store.sb_page && bitmap->storage.sb_page)
2459 		memcpy(page_address(store.sb_page),
2460 		       page_address(bitmap->storage.sb_page),
2461 		       sizeof(bitmap_super_t));
2462 	mutex_lock(&bitmap->mddev->bitmap_info.mutex);
2463 	spin_lock_irq(&bitmap->counts.lock);
2464 	md_bitmap_file_unmap(&bitmap->storage);
2465 	bitmap->storage = store;
2466 
2467 	old_counts = bitmap->counts;
2468 	bitmap->counts.bp = new_bp;
2469 	bitmap->counts.pages = pages;
2470 	bitmap->counts.missing_pages = pages;
2471 	bitmap->counts.chunkshift = chunkshift;
2472 	bitmap->counts.chunks = chunks;
2473 	bitmap->mddev->bitmap_info.chunksize = 1UL << (chunkshift +
2474 						     BITMAP_BLOCK_SHIFT);
2475 
2476 	blocks = min(old_counts.chunks << old_counts.chunkshift,
2477 		     chunks << chunkshift);
2478 
2479 	/* For cluster raid, need to pre-allocate bitmap */
2480 	if (mddev_is_clustered(bitmap->mddev)) {
2481 		unsigned long page;
2482 		for (page = 0; page < pages; page++) {
2483 			ret = md_bitmap_checkpage(&bitmap->counts, page, 1, 1);
2484 			if (ret) {
2485 				unsigned long k;
2486 
2487 				/* deallocate the page memory */
2488 				for (k = 0; k < page; k++) {
2489 					kfree(new_bp[k].map);
2490 				}
2491 				kfree(new_bp);
2492 
2493 				/* restore some fields from old_counts */
2494 				bitmap->counts.bp = old_counts.bp;
2495 				bitmap->counts.pages = old_counts.pages;
2496 				bitmap->counts.missing_pages = old_counts.pages;
2497 				bitmap->counts.chunkshift = old_counts.chunkshift;
2498 				bitmap->counts.chunks = old_counts.chunks;
2499 				bitmap->mddev->bitmap_info.chunksize =
2500 					1UL << (old_counts.chunkshift + BITMAP_BLOCK_SHIFT);
2501 				blocks = old_counts.chunks << old_counts.chunkshift;
2502 				pr_warn("Could not pre-allocate in-memory bitmap for cluster raid\n");
2503 				break;
2504 			} else
2505 				bitmap->counts.bp[page].count += 1;
2506 		}
2507 	}
2508 
2509 	for (block = 0; block < blocks; ) {
2510 		bitmap_counter_t *bmc_old, *bmc_new;
2511 		int set;
2512 
2513 		bmc_old = md_bitmap_get_counter(&old_counts, block, &old_blocks, 0);
2514 		set = bmc_old && NEEDED(*bmc_old);
2515 
2516 		if (set) {
2517 			bmc_new = md_bitmap_get_counter(&bitmap->counts, block, &new_blocks, 1);
2518 			if (bmc_new) {
2519 				if (*bmc_new == 0) {
2520 					/* need to set on-disk bits too. */
2521 					sector_t end = block + new_blocks;
2522 					sector_t start = block >> chunkshift;
2523 
2524 					start <<= chunkshift;
2525 					while (start < end) {
2526 						md_bitmap_file_set_bit(bitmap, block);
2527 						start += 1 << chunkshift;
2528 					}
2529 					*bmc_new = 2;
2530 					md_bitmap_count_page(&bitmap->counts, block, 1);
2531 					md_bitmap_set_pending(&bitmap->counts, block);
2532 				}
2533 				*bmc_new |= NEEDED_MASK;
2534 			}
2535 			if (new_blocks < old_blocks)
2536 				old_blocks = new_blocks;
2537 		}
2538 		block += old_blocks;
2539 	}
2540 
2541 	if (bitmap->counts.bp != old_counts.bp) {
2542 		unsigned long k;
2543 		for (k = 0; k < old_counts.pages; k++)
2544 			if (!old_counts.bp[k].hijacked)
2545 				kfree(old_counts.bp[k].map);
2546 		kfree(old_counts.bp);
2547 	}
2548 
2549 	if (!init) {
2550 		int i;
2551 		while (block < (chunks << chunkshift)) {
2552 			bitmap_counter_t *bmc;
2553 			bmc = md_bitmap_get_counter(&bitmap->counts, block, &new_blocks, 1);
2554 			if (bmc) {
2555 				/* new space.  It needs to be resynced, so
2556 				 * we set NEEDED_MASK.
2557 				 */
2558 				if (*bmc == 0) {
2559 					*bmc = NEEDED_MASK | 2;
2560 					md_bitmap_count_page(&bitmap->counts, block, 1);
2561 					md_bitmap_set_pending(&bitmap->counts, block);
2562 				}
2563 			}
2564 			block += new_blocks;
2565 		}
2566 		for (i = 0; i < bitmap->storage.file_pages; i++)
2567 			set_page_attr(bitmap, i, BITMAP_PAGE_DIRTY);
2568 	}
2569 	spin_unlock_irq(&bitmap->counts.lock);
2570 	mutex_unlock(&bitmap->mddev->bitmap_info.mutex);
2571 	if (!init) {
2572 		__bitmap_unplug(bitmap);
2573 		bitmap->mddev->pers->quiesce(bitmap->mddev, 0);
2574 	}
2575 	ret = 0;
2576 err:
2577 	return ret;
2578 }
2579 
2580 static int bitmap_resize(struct mddev *mddev, sector_t blocks, int chunksize)
2581 {
2582 	struct bitmap *bitmap = mddev->bitmap;
2583 
2584 	if (!bitmap)
2585 		return 0;
2586 
2587 	return __bitmap_resize(bitmap, blocks, chunksize, false);
2588 }
2589 
2590 static bool bitmap_none_enabled(void *data, bool flush)
2591 {
2592 	return false;
2593 }
2594 
2595 static int bitmap_none_create(struct mddev *mddev)
2596 {
2597 	return 0;
2598 }
2599 
2600 static int bitmap_none_load(struct mddev *mddev)
2601 {
2602 	return 0;
2603 }
2604 
2605 static void bitmap_none_destroy(struct mddev *mddev)
2606 {
2607 }
2608 
2609 static int bitmap_none_get_stats(void *data, struct md_bitmap_stats *stats)
2610 {
2611 	return -ENOENT;
2612 }
2613 
2614 static ssize_t
2615 location_show(struct mddev *mddev, char *page)
2616 {
2617 	ssize_t len;
2618 	if (mddev->bitmap_info.file)
2619 		len = sprintf(page, "file");
2620 	else if (mddev->bitmap_info.offset)
2621 		len = sprintf(page, "%+lld", (long long)mddev->bitmap_info.offset);
2622 	else
2623 		len = sprintf(page, "none");
2624 	len += sprintf(page+len, "\n");
2625 	return len;
2626 }
2627 
2628 static ssize_t
2629 location_store(struct mddev *mddev, const char *buf, size_t len)
2630 {
2631 	int rv;
2632 	unsigned int noio_flags;
2633 
2634 	rv = mddev_suspend_and_lock(mddev);
2635 	if (rv)
2636 		return rv;
2637 	noio_flags = memalloc_noio_save();
2638 
2639 	if (mddev->pers) {
2640 		if (mddev->recovery || mddev->sync_thread) {
2641 			rv = -EBUSY;
2642 			goto out;
2643 		}
2644 	}
2645 
2646 	if (mddev->bitmap || mddev->bitmap_info.file ||
2647 	    mddev->bitmap_info.offset) {
2648 		/* bitmap already configured.  Only option is to clear it */
2649 		if (strncmp(buf, "none", 4) != 0) {
2650 			rv = -EBUSY;
2651 			goto out;
2652 		}
2653 
2654 		sysfs_unmerge_group(&mddev->kobj, &md_bitmap_internal_group);
2655 		md_bitmap_destroy_nosysfs(mddev);
2656 		mddev->bitmap_id = ID_BITMAP_NONE;
2657 		if (!mddev_set_bitmap_ops_nosysfs(mddev))
2658 			goto none_err;
2659 		mddev->bitmap_info.offset = 0;
2660 		if (mddev->bitmap_info.file) {
2661 			struct file *f = mddev->bitmap_info.file;
2662 			mddev->bitmap_info.file = NULL;
2663 			fput(f);
2664 		}
2665 	} else {
2666 		/* No bitmap, OK to set a location */
2667 		long long offset;
2668 
2669 		if (strncmp(buf, "none", 4) == 0)
2670 			/* nothing to be done */;
2671 		else if (strncmp(buf, "file:", 5) == 0) {
2672 			/* Not supported yet */
2673 			rv = -EINVAL;
2674 			goto out;
2675 		} else {
2676 			if (buf[0] == '+')
2677 				rv = kstrtoll(buf+1, 10, &offset);
2678 			else
2679 				rv = kstrtoll(buf, 10, &offset);
2680 			if (rv)
2681 				goto out;
2682 			if (offset == 0) {
2683 				rv = -EINVAL;
2684 				goto out;
2685 			}
2686 			if (mddev->bitmap_info.external == 0 &&
2687 			    mddev->major_version == 0 &&
2688 			    offset != mddev->bitmap_info.default_offset) {
2689 				rv = -EINVAL;
2690 				goto out;
2691 			}
2692 
2693 			mddev->bitmap_info.offset = offset;
2694 			md_bitmap_destroy_nosysfs(mddev);
2695 			mddev->bitmap_id = ID_BITMAP;
2696 			if (!mddev_set_bitmap_ops_nosysfs(mddev))
2697 				goto bitmap_err;
2698 
2699 			rv = md_bitmap_create_nosysfs(mddev);
2700 			if (rv)
2701 				goto create_err;
2702 
2703 			rv = mddev->bitmap_ops->load(mddev);
2704 			if (rv) {
2705 				mddev->bitmap_info.offset = 0;
2706 				goto load_err;
2707 			}
2708 
2709 			rv = sysfs_merge_group(&mddev->kobj,
2710 					       &md_bitmap_internal_group);
2711 			if (rv)
2712 				goto merge_err;
2713 		}
2714 	}
2715 	if (!mddev->external) {
2716 		/* Ensure new bitmap info is stored in
2717 		 * metadata promptly.
2718 		 */
2719 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2720 		md_wakeup_thread(mddev->thread);
2721 	}
2722 	rv = 0;
2723 out:
2724 	memalloc_noio_restore(noio_flags);
2725 	mddev_unlock_and_resume(mddev);
2726 	if (rv)
2727 		return rv;
2728 	return len;
2729 
2730 merge_err:
2731 	mddev->bitmap_info.offset = 0;
2732 load_err:
2733 	md_bitmap_destroy_nosysfs(mddev);
2734 create_err:
2735 	mddev->bitmap_info.offset = 0;
2736 	mddev->bitmap_id = ID_BITMAP_NONE;
2737 	if (!mddev_set_bitmap_ops_nosysfs(mddev))
2738 		rv = -ENOENT;
2739 	goto out;
2740 bitmap_err:
2741 	rv = -ENOENT;
2742 none_err:
2743 	mddev->bitmap_info.offset = 0;
2744 	goto out;
2745 }
2746 
2747 static struct md_sysfs_entry bitmap_location =
2748 __ATTR(location, S_IRUGO|S_IWUSR, location_show, location_store);
2749 
2750 /* 'bitmap/space' is the space available at 'location' for the
2751  * bitmap.  This allows the kernel to know when it is safe to
2752  * resize the bitmap to match a resized array.
2753  */
2754 static ssize_t
2755 space_show(struct mddev *mddev, char *page)
2756 {
2757 	return sprintf(page, "%lu\n", mddev->bitmap_info.space);
2758 }
2759 
2760 static ssize_t
2761 space_store(struct mddev *mddev, const char *buf, size_t len)
2762 {
2763 	struct bitmap *bitmap;
2764 	unsigned long sectors;
2765 	int rv;
2766 
2767 	rv = kstrtoul(buf, 10, &sectors);
2768 	if (rv)
2769 		return rv;
2770 
2771 	if (sectors == 0)
2772 		return -EINVAL;
2773 
2774 	bitmap = mddev->bitmap;
2775 	if (bitmap && sectors < (bitmap->storage.bytes + 511) >> 9)
2776 		return -EFBIG; /* Bitmap is too big for this small space */
2777 
2778 	/* could make sure it isn't too big, but that isn't really
2779 	 * needed - user-space should be careful.
2780 	 */
2781 	mddev->bitmap_info.space = sectors;
2782 	return len;
2783 }
2784 
2785 static struct md_sysfs_entry bitmap_space =
2786 __ATTR(space, S_IRUGO|S_IWUSR, space_show, space_store);
2787 
2788 static ssize_t
2789 timeout_show(struct mddev *mddev, char *page)
2790 {
2791 	ssize_t len;
2792 	unsigned long secs = mddev->bitmap_info.daemon_sleep / HZ;
2793 	unsigned long jifs = mddev->bitmap_info.daemon_sleep % HZ;
2794 
2795 	len = sprintf(page, "%lu", secs);
2796 	if (jifs)
2797 		len += sprintf(page+len, ".%03u", jiffies_to_msecs(jifs));
2798 	len += sprintf(page+len, "\n");
2799 	return len;
2800 }
2801 
2802 static ssize_t
2803 timeout_store(struct mddev *mddev, const char *buf, size_t len)
2804 {
2805 	/* timeout can be set at any time */
2806 	unsigned long timeout;
2807 	int rv = strict_strtoul_scaled(buf, &timeout, 4);
2808 	if (rv)
2809 		return rv;
2810 
2811 	/* just to make sure we don't overflow... */
2812 	if (timeout >= LONG_MAX / HZ)
2813 		return -EINVAL;
2814 
2815 	timeout = timeout * HZ / 10000;
2816 
2817 	if (timeout >= MAX_SCHEDULE_TIMEOUT)
2818 		timeout = MAX_SCHEDULE_TIMEOUT-1;
2819 	if (timeout < 1)
2820 		timeout = 1;
2821 
2822 	mddev->bitmap_info.daemon_sleep = timeout;
2823 	mddev_set_timeout(mddev, timeout, false);
2824 	md_wakeup_thread(mddev->thread);
2825 
2826 	return len;
2827 }
2828 
2829 static struct md_sysfs_entry bitmap_timeout =
2830 __ATTR(time_base, S_IRUGO|S_IWUSR, timeout_show, timeout_store);
2831 
2832 static ssize_t
2833 backlog_show(struct mddev *mddev, char *page)
2834 {
2835 	return sprintf(page, "%lu\n", mddev->bitmap_info.max_write_behind);
2836 }
2837 
2838 static ssize_t
2839 backlog_store(struct mddev *mddev, const char *buf, size_t len)
2840 {
2841 	unsigned long backlog;
2842 	unsigned long old_mwb = mddev->bitmap_info.max_write_behind;
2843 	struct md_rdev *rdev;
2844 	bool has_write_mostly = false;
2845 	int rv = kstrtoul(buf, 10, &backlog);
2846 	if (rv)
2847 		return rv;
2848 	if (backlog > COUNTER_MAX)
2849 		return -EINVAL;
2850 
2851 	rv = mddev_suspend_and_lock(mddev);
2852 	if (rv)
2853 		return rv;
2854 
2855 	/*
2856 	 * Without write mostly device, it doesn't make sense to set
2857 	 * backlog for max_write_behind.
2858 	 */
2859 	rdev_for_each(rdev, mddev) {
2860 		if (test_bit(WriteMostly, &rdev->flags)) {
2861 			has_write_mostly = true;
2862 			break;
2863 		}
2864 	}
2865 	if (!has_write_mostly) {
2866 		pr_warn_ratelimited("%s: can't set backlog, no write mostly device available\n",
2867 				    mdname(mddev));
2868 		mddev_unlock_and_resume(mddev);
2869 		return -EINVAL;
2870 	}
2871 
2872 	mddev->bitmap_info.max_write_behind = backlog;
2873 	if (!backlog && mddev->serial_info_pool) {
2874 		/* serial_info_pool is not needed if backlog is zero */
2875 		if (!test_bit(MD_SERIALIZE_POLICY, &mddev->flags))
2876 			mddev_destroy_serial_pool(mddev, NULL);
2877 	} else if (backlog && !mddev->serial_info_pool) {
2878 		/* serial_info_pool is needed since backlog is not zero */
2879 		rdev_for_each(rdev, mddev)
2880 			mddev_create_serial_pool(mddev, rdev);
2881 	}
2882 	if (old_mwb != backlog)
2883 		bitmap_update_sb(mddev->bitmap);
2884 
2885 	mddev_unlock_and_resume(mddev);
2886 	return len;
2887 }
2888 
2889 static struct md_sysfs_entry bitmap_backlog =
2890 __ATTR(backlog, S_IRUGO|S_IWUSR, backlog_show, backlog_store);
2891 
2892 static ssize_t
2893 chunksize_show(struct mddev *mddev, char *page)
2894 {
2895 	return sprintf(page, "%lu\n", mddev->bitmap_info.chunksize);
2896 }
2897 
2898 static ssize_t
2899 chunksize_store(struct mddev *mddev, const char *buf, size_t len)
2900 {
2901 	/* Can only be changed when no bitmap is active */
2902 	int rv;
2903 	unsigned long csize;
2904 	if (mddev->bitmap)
2905 		return -EBUSY;
2906 	rv = kstrtoul(buf, 10, &csize);
2907 	if (rv)
2908 		return rv;
2909 	if (csize < 512 ||
2910 	    !is_power_of_2(csize))
2911 		return -EINVAL;
2912 	if (BITS_PER_LONG > 32 && csize >= (1ULL << (BITS_PER_BYTE *
2913 		sizeof(((bitmap_super_t *)0)->chunksize))))
2914 		return -EOVERFLOW;
2915 	mddev->bitmap_info.chunksize = csize;
2916 	return len;
2917 }
2918 
2919 static struct md_sysfs_entry bitmap_chunksize =
2920 __ATTR(chunksize, S_IRUGO|S_IWUSR, chunksize_show, chunksize_store);
2921 
2922 static ssize_t metadata_show(struct mddev *mddev, char *page)
2923 {
2924 	if (mddev_is_clustered(mddev))
2925 		return sprintf(page, "clustered\n");
2926 	return sprintf(page, "%s\n", (mddev->bitmap_info.external
2927 				      ? "external" : "internal"));
2928 }
2929 
2930 static ssize_t metadata_store(struct mddev *mddev, const char *buf, size_t len)
2931 {
2932 	if (mddev->bitmap ||
2933 	    mddev->bitmap_info.file ||
2934 	    mddev->bitmap_info.offset)
2935 		return -EBUSY;
2936 	if (strncmp(buf, "external", 8) == 0)
2937 		mddev->bitmap_info.external = 1;
2938 	else if ((strncmp(buf, "internal", 8) == 0) ||
2939 			(strncmp(buf, "clustered", 9) == 0))
2940 		mddev->bitmap_info.external = 0;
2941 	else
2942 		return -EINVAL;
2943 	return len;
2944 }
2945 
2946 static struct md_sysfs_entry bitmap_metadata =
2947 __ATTR(metadata, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
2948 
2949 static ssize_t can_clear_show(struct mddev *mddev, char *page)
2950 {
2951 	int len;
2952 	struct bitmap *bitmap;
2953 
2954 	spin_lock(&mddev->lock);
2955 	bitmap = mddev->bitmap;
2956 	if (bitmap)
2957 		len = sprintf(page, "%s\n", (bitmap->need_sync ? "false" :
2958 								 "true"));
2959 	else
2960 		len = sprintf(page, "\n");
2961 	spin_unlock(&mddev->lock);
2962 	return len;
2963 }
2964 
2965 static ssize_t can_clear_store(struct mddev *mddev, const char *buf, size_t len)
2966 {
2967 	struct bitmap *bitmap = mddev->bitmap;
2968 
2969 	if (!bitmap)
2970 		return -ENOENT;
2971 
2972 	if (strncmp(buf, "false", 5) == 0) {
2973 		bitmap->need_sync = 1;
2974 		return len;
2975 	}
2976 
2977 	if (strncmp(buf, "true", 4) == 0) {
2978 		if (mddev->degraded)
2979 			return -EBUSY;
2980 		bitmap->need_sync = 0;
2981 		return len;
2982 	}
2983 
2984 	return -EINVAL;
2985 }
2986 
2987 static struct md_sysfs_entry bitmap_can_clear =
2988 __ATTR(can_clear, S_IRUGO|S_IWUSR, can_clear_show, can_clear_store);
2989 
2990 static ssize_t
2991 behind_writes_used_show(struct mddev *mddev, char *page)
2992 {
2993 	ssize_t ret;
2994 	struct bitmap *bitmap;
2995 
2996 	spin_lock(&mddev->lock);
2997 	bitmap = mddev->bitmap;
2998 	if (!bitmap)
2999 		ret = sprintf(page, "0\n");
3000 	else
3001 		ret = sprintf(page, "%lu\n", bitmap->behind_writes_used);
3002 	spin_unlock(&mddev->lock);
3003 
3004 	return ret;
3005 }
3006 
3007 static ssize_t
3008 behind_writes_used_reset(struct mddev *mddev, const char *buf, size_t len)
3009 {
3010 	struct bitmap *bitmap = mddev->bitmap;
3011 
3012 	if (bitmap)
3013 		bitmap->behind_writes_used = 0;
3014 	return len;
3015 }
3016 
3017 static struct md_sysfs_entry max_backlog_used =
3018 __ATTR(max_backlog_used, S_IRUGO | S_IWUSR,
3019        behind_writes_used_show, behind_writes_used_reset);
3020 
3021 static struct attribute *md_bitmap_common_attrs[] = {
3022 	&bitmap_location.attr,
3023 	NULL
3024 };
3025 
3026 static struct attribute *md_bitmap_internal_attrs[] = {
3027 	&bitmap_space.attr,
3028 	&bitmap_timeout.attr,
3029 	&bitmap_backlog.attr,
3030 	&bitmap_chunksize.attr,
3031 	&bitmap_metadata.attr,
3032 	&bitmap_can_clear.attr,
3033 	&max_backlog_used.attr,
3034 	NULL
3035 };
3036 
3037 static struct attribute_group md_bitmap_common_group = {
3038 	.name = "bitmap",
3039 	.attrs = md_bitmap_common_attrs,
3040 };
3041 
3042 static struct attribute_group md_bitmap_internal_group = {
3043 	.name = "bitmap",
3044 	.attrs = md_bitmap_internal_attrs,
3045 };
3046 
3047 static const struct attribute_group *bitmap_groups[] = {
3048 	&md_bitmap_common_group,
3049 	&md_bitmap_internal_group,
3050 	NULL,
3051 };
3052 
3053 static const struct attribute_group *bitmap_none_groups[] = {
3054 	&md_bitmap_common_group,
3055 	NULL,
3056 };
3057 
3058 static struct bitmap_operations bitmap_none_ops = {
3059 	.head = {
3060 		.type	= MD_BITMAP,
3061 		.id	= ID_BITMAP_NONE,
3062 		.name	= "none",
3063 	},
3064 
3065 	.enabled		= bitmap_none_enabled,
3066 	.create			= bitmap_none_create,
3067 	.load			= bitmap_none_load,
3068 	.destroy		= bitmap_none_destroy,
3069 	.get_stats		= bitmap_none_get_stats,
3070 
3071 	.groups			= bitmap_none_groups,
3072 };
3073 
3074 static struct bitmap_operations bitmap_ops = {
3075 	.head = {
3076 		.type	= MD_BITMAP,
3077 		.id	= ID_BITMAP,
3078 		.name	= "bitmap",
3079 	},
3080 
3081 	.enabled		= bitmap_enabled,
3082 	.create			= bitmap_create,
3083 	.resize			= bitmap_resize,
3084 	.load			= bitmap_load,
3085 	.destroy		= bitmap_destroy,
3086 	.flush			= bitmap_flush,
3087 	.write_all		= bitmap_write_all,
3088 	.dirty_bits		= bitmap_dirty_bits,
3089 	.prepare_range		= bitmap_prepare_range,
3090 	.unplug			= bitmap_unplug,
3091 	.daemon_work		= bitmap_daemon_work,
3092 
3093 	.start_behind_write	= bitmap_start_behind_write,
3094 	.end_behind_write	= bitmap_end_behind_write,
3095 	.wait_behind_writes	= bitmap_wait_behind_writes,
3096 
3097 	.start_write		= bitmap_start_write,
3098 	.end_write		= bitmap_end_write,
3099 	.start_discard		= bitmap_start_write,
3100 	.end_discard		= bitmap_end_write,
3101 
3102 	.start_sync		= bitmap_start_sync,
3103 	.end_sync		= bitmap_end_sync,
3104 	.cond_end_sync		= bitmap_cond_end_sync,
3105 	.close_sync		= bitmap_close_sync,
3106 
3107 	.update_sb		= bitmap_update_sb,
3108 	.get_stats		= bitmap_get_stats,
3109 
3110 	.sync_with_cluster	= bitmap_sync_with_cluster,
3111 	.get_from_slot		= bitmap_get_from_slot,
3112 	.copy_from_slot		= bitmap_copy_from_slot,
3113 	.set_pages		= bitmap_set_pages,
3114 	.free			= md_bitmap_free,
3115 
3116 	.groups			= bitmap_groups,
3117 };
3118 
3119 int md_bitmap_init(void)
3120 {
3121 	int err;
3122 
3123 	md_bitmap_wq = alloc_workqueue("md_bitmap", WQ_MEM_RECLAIM | WQ_UNBOUND,
3124 				       0);
3125 	if (!md_bitmap_wq)
3126 		return -ENOMEM;
3127 
3128 	err = register_md_submodule(&bitmap_none_ops.head);
3129 	if (err)
3130 		goto err_wq;
3131 
3132 	err = register_md_submodule(&bitmap_ops.head);
3133 	if (err)
3134 		goto err_none;
3135 
3136 	return 0;
3137 
3138 err_none:
3139 	unregister_md_submodule(&bitmap_none_ops.head);
3140 err_wq:
3141 	destroy_workqueue(md_bitmap_wq);
3142 	return err;
3143 }
3144 
3145 void md_bitmap_exit(void)
3146 {
3147 	unregister_md_submodule(&bitmap_ops.head);
3148 	unregister_md_submodule(&bitmap_none_ops.head);
3149 	destroy_workqueue(md_bitmap_wq);
3150 }
3151