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