md/bitmap: remove some pointless locking.
[pandora-kernel.git] / drivers / 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 "md.h"
31 #include "bitmap.h"
32
33 static inline char *bmname(struct bitmap *bitmap)
34 {
35         return bitmap->mddev ? mdname(bitmap->mddev) : "mdX";
36 }
37
38 /*
39  * just a placeholder - calls kmalloc for bitmap pages
40  */
41 static unsigned char *bitmap_alloc_page(struct bitmap *bitmap)
42 {
43         unsigned char *page;
44
45         page = kzalloc(PAGE_SIZE, GFP_NOIO);
46         if (!page)
47                 printk("%s: bitmap_alloc_page FAILED\n", bmname(bitmap));
48         else
49                 pr_debug("%s: bitmap_alloc_page: allocated page at %p\n",
50                          bmname(bitmap), page);
51         return page;
52 }
53
54 /*
55  * for now just a placeholder -- just calls kfree for bitmap pages
56  */
57 static void bitmap_free_page(struct bitmap *bitmap, unsigned char *page)
58 {
59         pr_debug("%s: bitmap_free_page: free page %p\n", bmname(bitmap), page);
60         kfree(page);
61 }
62
63 /*
64  * check a page and, if necessary, allocate it (or hijack it if the alloc fails)
65  *
66  * 1) check to see if this page is allocated, if it's not then try to alloc
67  * 2) if the alloc fails, set the page's hijacked flag so we'll use the
68  *    page pointer directly as a counter
69  *
70  * if we find our page, we increment the page's refcount so that it stays
71  * allocated while we're using it
72  */
73 static int bitmap_checkpage(struct bitmap *bitmap,
74                             unsigned long page, int create)
75 __releases(bitmap->lock)
76 __acquires(bitmap->lock)
77 {
78         unsigned char *mappage;
79
80         if (page >= bitmap->pages) {
81                 /* This can happen if bitmap_start_sync goes beyond
82                  * End-of-device while looking for a whole page.
83                  * It is harmless.
84                  */
85                 return -EINVAL;
86         }
87
88         if (bitmap->bp[page].hijacked) /* it's hijacked, don't try to alloc */
89                 return 0;
90
91         if (bitmap->bp[page].map) /* page is already allocated, just return */
92                 return 0;
93
94         if (!create)
95                 return -ENOENT;
96
97         /* this page has not been allocated yet */
98
99         spin_unlock_irq(&bitmap->lock);
100         mappage = bitmap_alloc_page(bitmap);
101         spin_lock_irq(&bitmap->lock);
102
103         if (mappage == NULL) {
104                 pr_debug("%s: bitmap map page allocation failed, hijacking\n",
105                          bmname(bitmap));
106                 /* failed - set the hijacked flag so that we can use the
107                  * pointer as a counter */
108                 if (!bitmap->bp[page].map)
109                         bitmap->bp[page].hijacked = 1;
110         } else if (bitmap->bp[page].map ||
111                    bitmap->bp[page].hijacked) {
112                 /* somebody beat us to getting the page */
113                 bitmap_free_page(bitmap, mappage);
114                 return 0;
115         } else {
116
117                 /* no page was in place and we have one, so install it */
118
119                 bitmap->bp[page].map = mappage;
120                 bitmap->missing_pages--;
121         }
122         return 0;
123 }
124
125 /* if page is completely empty, put it back on the free list, or dealloc it */
126 /* if page was hijacked, unmark the flag so it might get alloced next time */
127 /* Note: lock should be held when calling this */
128 static void bitmap_checkfree(struct bitmap *bitmap, unsigned long page)
129 {
130         char *ptr;
131
132         if (bitmap->bp[page].count) /* page is still busy */
133                 return;
134
135         /* page is no longer in use, it can be released */
136
137         if (bitmap->bp[page].hijacked) { /* page was hijacked, undo this now */
138                 bitmap->bp[page].hijacked = 0;
139                 bitmap->bp[page].map = NULL;
140         } else {
141                 /* normal case, free the page */
142                 ptr = bitmap->bp[page].map;
143                 bitmap->bp[page].map = NULL;
144                 bitmap->missing_pages++;
145                 bitmap_free_page(bitmap, ptr);
146         }
147 }
148
149 /*
150  * bitmap file handling - read and write the bitmap file and its superblock
151  */
152
153 /*
154  * basic page I/O operations
155  */
156
157 /* IO operations when bitmap is stored near all superblocks */
158 static struct page *read_sb_page(struct mddev *mddev, loff_t offset,
159                                  struct page *page,
160                                  unsigned long index, int size)
161 {
162         /* choose a good rdev and read the page from there */
163
164         struct md_rdev *rdev;
165         sector_t target;
166         int did_alloc = 0;
167
168         if (!page) {
169                 page = alloc_page(GFP_KERNEL);
170                 if (!page)
171                         return ERR_PTR(-ENOMEM);
172                 did_alloc = 1;
173         }
174
175         rdev_for_each(rdev, mddev) {
176                 if (! test_bit(In_sync, &rdev->flags)
177                     || test_bit(Faulty, &rdev->flags))
178                         continue;
179
180                 target = offset + index * (PAGE_SIZE/512);
181
182                 if (sync_page_io(rdev, target,
183                                  roundup(size, bdev_logical_block_size(rdev->bdev)),
184                                  page, READ, true)) {
185                         page->index = index;
186                         attach_page_buffers(page, NULL); /* so that free_buffer will
187                                                           * quietly no-op */
188                         return page;
189                 }
190         }
191         if (did_alloc)
192                 put_page(page);
193         return ERR_PTR(-EIO);
194
195 }
196
197 static struct md_rdev *next_active_rdev(struct md_rdev *rdev, struct mddev *mddev)
198 {
199         /* Iterate the disks of an mddev, using rcu to protect access to the
200          * linked list, and raising the refcount of devices we return to ensure
201          * they don't disappear while in use.
202          * As devices are only added or removed when raid_disk is < 0 and
203          * nr_pending is 0 and In_sync is clear, the entries we return will
204          * still be in the same position on the list when we re-enter
205          * list_for_each_continue_rcu.
206          */
207         struct list_head *pos;
208         rcu_read_lock();
209         if (rdev == NULL)
210                 /* start at the beginning */
211                 pos = &mddev->disks;
212         else {
213                 /* release the previous rdev and start from there. */
214                 rdev_dec_pending(rdev, mddev);
215                 pos = &rdev->same_set;
216         }
217         list_for_each_continue_rcu(pos, &mddev->disks) {
218                 rdev = list_entry(pos, struct md_rdev, same_set);
219                 if (rdev->raid_disk >= 0 &&
220                     !test_bit(Faulty, &rdev->flags)) {
221                         /* this is a usable devices */
222                         atomic_inc(&rdev->nr_pending);
223                         rcu_read_unlock();
224                         return rdev;
225                 }
226         }
227         rcu_read_unlock();
228         return NULL;
229 }
230
231 static int write_sb_page(struct bitmap *bitmap, struct page *page, int wait)
232 {
233         struct md_rdev *rdev = NULL;
234         struct block_device *bdev;
235         struct mddev *mddev = bitmap->mddev;
236
237         while ((rdev = next_active_rdev(rdev, mddev)) != NULL) {
238                 int size = PAGE_SIZE;
239                 loff_t offset = mddev->bitmap_info.offset;
240
241                 bdev = (rdev->meta_bdev) ? rdev->meta_bdev : rdev->bdev;
242
243                 if (page->index == bitmap->file_pages-1)
244                         size = roundup(bitmap->last_page_size,
245                                        bdev_logical_block_size(bdev));
246                 /* Just make sure we aren't corrupting data or
247                  * metadata
248                  */
249                 if (mddev->external) {
250                         /* Bitmap could be anywhere. */
251                         if (rdev->sb_start + offset + (page->index
252                                                        * (PAGE_SIZE/512))
253                             > rdev->data_offset
254                             &&
255                             rdev->sb_start + offset
256                             < (rdev->data_offset + mddev->dev_sectors
257                              + (PAGE_SIZE/512)))
258                                 goto bad_alignment;
259                 } else if (offset < 0) {
260                         /* DATA  BITMAP METADATA  */
261                         if (offset
262                             + (long)(page->index * (PAGE_SIZE/512))
263                             + size/512 > 0)
264                                 /* bitmap runs in to metadata */
265                                 goto bad_alignment;
266                         if (rdev->data_offset + mddev->dev_sectors
267                             > rdev->sb_start + offset)
268                                 /* data runs in to bitmap */
269                                 goto bad_alignment;
270                 } else if (rdev->sb_start < rdev->data_offset) {
271                         /* METADATA BITMAP DATA */
272                         if (rdev->sb_start
273                             + offset
274                             + page->index*(PAGE_SIZE/512) + size/512
275                             > rdev->data_offset)
276                                 /* bitmap runs in to data */
277                                 goto bad_alignment;
278                 } else {
279                         /* DATA METADATA BITMAP - no problems */
280                 }
281                 md_super_write(mddev, rdev,
282                                rdev->sb_start + offset
283                                + page->index * (PAGE_SIZE/512),
284                                size,
285                                page);
286         }
287
288         if (wait)
289                 md_super_wait(mddev);
290         return 0;
291
292  bad_alignment:
293         return -EINVAL;
294 }
295
296 static void bitmap_file_kick(struct bitmap *bitmap);
297 /*
298  * write out a page to a file
299  */
300 static void write_page(struct bitmap *bitmap, struct page *page, int wait)
301 {
302         struct buffer_head *bh;
303
304         if (bitmap->file == NULL) {
305                 switch (write_sb_page(bitmap, page, wait)) {
306                 case -EINVAL:
307                         bitmap->flags |= BITMAP_WRITE_ERROR;
308                 }
309         } else {
310
311                 bh = page_buffers(page);
312
313                 while (bh && bh->b_blocknr) {
314                         atomic_inc(&bitmap->pending_writes);
315                         set_buffer_locked(bh);
316                         set_buffer_mapped(bh);
317                         submit_bh(WRITE | REQ_SYNC, bh);
318                         bh = bh->b_this_page;
319                 }
320
321                 if (wait)
322                         wait_event(bitmap->write_wait,
323                                    atomic_read(&bitmap->pending_writes)==0);
324         }
325         if (bitmap->flags & BITMAP_WRITE_ERROR)
326                 bitmap_file_kick(bitmap);
327 }
328
329 static void end_bitmap_write(struct buffer_head *bh, int uptodate)
330 {
331         struct bitmap *bitmap = bh->b_private;
332         unsigned long flags;
333
334         if (!uptodate) {
335                 spin_lock_irqsave(&bitmap->lock, flags);
336                 bitmap->flags |= BITMAP_WRITE_ERROR;
337                 spin_unlock_irqrestore(&bitmap->lock, flags);
338         }
339         if (atomic_dec_and_test(&bitmap->pending_writes))
340                 wake_up(&bitmap->write_wait);
341 }
342
343 /* copied from buffer.c */
344 static void
345 __clear_page_buffers(struct page *page)
346 {
347         ClearPagePrivate(page);
348         set_page_private(page, 0);
349         page_cache_release(page);
350 }
351 static void free_buffers(struct page *page)
352 {
353         struct buffer_head *bh = page_buffers(page);
354
355         while (bh) {
356                 struct buffer_head *next = bh->b_this_page;
357                 free_buffer_head(bh);
358                 bh = next;
359         }
360         __clear_page_buffers(page);
361         put_page(page);
362 }
363
364 /* read a page from a file.
365  * We both read the page, and attach buffers to the page to record the
366  * address of each block (using bmap).  These addresses will be used
367  * to write the block later, completely bypassing the filesystem.
368  * This usage is similar to how swap files are handled, and allows us
369  * to write to a file with no concerns of memory allocation failing.
370  */
371 static struct page *read_page(struct file *file, unsigned long index,
372                               struct bitmap *bitmap,
373                               unsigned long count)
374 {
375         struct page *page = NULL;
376         struct inode *inode = file->f_path.dentry->d_inode;
377         struct buffer_head *bh;
378         sector_t block;
379
380         pr_debug("read bitmap file (%dB @ %llu)\n", (int)PAGE_SIZE,
381                  (unsigned long long)index << PAGE_SHIFT);
382
383         page = alloc_page(GFP_KERNEL);
384         if (!page)
385                 page = ERR_PTR(-ENOMEM);
386         if (IS_ERR(page))
387                 goto out;
388
389         bh = alloc_page_buffers(page, 1<<inode->i_blkbits, 0);
390         if (!bh) {
391                 put_page(page);
392                 page = ERR_PTR(-ENOMEM);
393                 goto out;
394         }
395         attach_page_buffers(page, bh);
396         block = index << (PAGE_SHIFT - inode->i_blkbits);
397         while (bh) {
398                 if (count == 0)
399                         bh->b_blocknr = 0;
400                 else {
401                         bh->b_blocknr = bmap(inode, block);
402                         if (bh->b_blocknr == 0) {
403                                 /* Cannot use this file! */
404                                 free_buffers(page);
405                                 page = ERR_PTR(-EINVAL);
406                                 goto out;
407                         }
408                         bh->b_bdev = inode->i_sb->s_bdev;
409                         if (count < (1<<inode->i_blkbits))
410                                 count = 0;
411                         else
412                                 count -= (1<<inode->i_blkbits);
413
414                         bh->b_end_io = end_bitmap_write;
415                         bh->b_private = bitmap;
416                         atomic_inc(&bitmap->pending_writes);
417                         set_buffer_locked(bh);
418                         set_buffer_mapped(bh);
419                         submit_bh(READ, bh);
420                 }
421                 block++;
422                 bh = bh->b_this_page;
423         }
424         page->index = index;
425
426         wait_event(bitmap->write_wait,
427                    atomic_read(&bitmap->pending_writes)==0);
428         if (bitmap->flags & BITMAP_WRITE_ERROR) {
429                 free_buffers(page);
430                 page = ERR_PTR(-EIO);
431         }
432 out:
433         if (IS_ERR(page))
434                 printk(KERN_ALERT "md: bitmap read error: (%dB @ %llu): %ld\n",
435                         (int)PAGE_SIZE,
436                         (unsigned long long)index << PAGE_SHIFT,
437                         PTR_ERR(page));
438         return page;
439 }
440
441 /*
442  * bitmap file superblock operations
443  */
444
445 /* update the event counter and sync the superblock to disk */
446 void bitmap_update_sb(struct bitmap *bitmap)
447 {
448         bitmap_super_t *sb;
449
450         if (!bitmap || !bitmap->mddev) /* no bitmap for this array */
451                 return;
452         if (bitmap->mddev->bitmap_info.external)
453                 return;
454         if (!bitmap->sb_page) /* no superblock */
455                 return;
456         sb = kmap_atomic(bitmap->sb_page, KM_USER0);
457         sb->events = cpu_to_le64(bitmap->mddev->events);
458         if (bitmap->mddev->events < bitmap->events_cleared)
459                 /* rocking back to read-only */
460                 bitmap->events_cleared = bitmap->mddev->events;
461         sb->events_cleared = cpu_to_le64(bitmap->events_cleared);
462         sb->state = cpu_to_le32(bitmap->flags);
463         /* Just in case these have been changed via sysfs: */
464         sb->daemon_sleep = cpu_to_le32(bitmap->mddev->bitmap_info.daemon_sleep/HZ);
465         sb->write_behind = cpu_to_le32(bitmap->mddev->bitmap_info.max_write_behind);
466         kunmap_atomic(sb, KM_USER0);
467         write_page(bitmap, bitmap->sb_page, 1);
468 }
469
470 /* print out the bitmap file superblock */
471 void bitmap_print_sb(struct bitmap *bitmap)
472 {
473         bitmap_super_t *sb;
474
475         if (!bitmap || !bitmap->sb_page)
476                 return;
477         sb = kmap_atomic(bitmap->sb_page, KM_USER0);
478         printk(KERN_DEBUG "%s: bitmap file superblock:\n", bmname(bitmap));
479         printk(KERN_DEBUG "         magic: %08x\n", le32_to_cpu(sb->magic));
480         printk(KERN_DEBUG "       version: %d\n", le32_to_cpu(sb->version));
481         printk(KERN_DEBUG "          uuid: %08x.%08x.%08x.%08x\n",
482                                         *(__u32 *)(sb->uuid+0),
483                                         *(__u32 *)(sb->uuid+4),
484                                         *(__u32 *)(sb->uuid+8),
485                                         *(__u32 *)(sb->uuid+12));
486         printk(KERN_DEBUG "        events: %llu\n",
487                         (unsigned long long) le64_to_cpu(sb->events));
488         printk(KERN_DEBUG "events cleared: %llu\n",
489                         (unsigned long long) le64_to_cpu(sb->events_cleared));
490         printk(KERN_DEBUG "         state: %08x\n", le32_to_cpu(sb->state));
491         printk(KERN_DEBUG "     chunksize: %d B\n", le32_to_cpu(sb->chunksize));
492         printk(KERN_DEBUG "  daemon sleep: %ds\n", le32_to_cpu(sb->daemon_sleep));
493         printk(KERN_DEBUG "     sync size: %llu KB\n",
494                         (unsigned long long)le64_to_cpu(sb->sync_size)/2);
495         printk(KERN_DEBUG "max write behind: %d\n", le32_to_cpu(sb->write_behind));
496         kunmap_atomic(sb, KM_USER0);
497 }
498
499 /*
500  * bitmap_new_disk_sb
501  * @bitmap
502  *
503  * This function is somewhat the reverse of bitmap_read_sb.  bitmap_read_sb
504  * reads and verifies the on-disk bitmap superblock and populates bitmap_info.
505  * This function verifies 'bitmap_info' and populates the on-disk bitmap
506  * structure, which is to be written to disk.
507  *
508  * Returns: 0 on success, -Exxx on error
509  */
510 static int bitmap_new_disk_sb(struct bitmap *bitmap)
511 {
512         bitmap_super_t *sb;
513         unsigned long chunksize, daemon_sleep, write_behind;
514         int err = -EINVAL;
515
516         bitmap->sb_page = alloc_page(GFP_KERNEL);
517         if (IS_ERR(bitmap->sb_page)) {
518                 err = PTR_ERR(bitmap->sb_page);
519                 bitmap->sb_page = NULL;
520                 return err;
521         }
522         bitmap->sb_page->index = 0;
523
524         sb = kmap_atomic(bitmap->sb_page, KM_USER0);
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, KM_USER0);
533                 printk(KERN_ERR "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 ||
540             (daemon_sleep < 1) || (daemon_sleep > MAX_SCHEDULE_TIMEOUT)) {
541                 printk(KERN_INFO "Choosing daemon_sleep default (5 sec)\n");
542                 daemon_sleep = 5 * HZ;
543         }
544         sb->daemon_sleep = cpu_to_le32(daemon_sleep);
545         bitmap->mddev->bitmap_info.daemon_sleep = daemon_sleep;
546
547         /*
548          * FIXME: write_behind for RAID1.  If not specified, what
549          * is a good choice?  We choose COUNTER_MAX / 2 arbitrarily.
550          */
551         write_behind = bitmap->mddev->bitmap_info.max_write_behind;
552         if (write_behind > COUNTER_MAX)
553                 write_behind = COUNTER_MAX / 2;
554         sb->write_behind = cpu_to_le32(write_behind);
555         bitmap->mddev->bitmap_info.max_write_behind = write_behind;
556
557         /* keep the array size field of the bitmap superblock up to date */
558         sb->sync_size = cpu_to_le64(bitmap->mddev->resync_max_sectors);
559
560         memcpy(sb->uuid, bitmap->mddev->uuid, 16);
561
562         bitmap->flags |= BITMAP_STALE;
563         sb->state |= cpu_to_le32(BITMAP_STALE);
564         bitmap->events_cleared = bitmap->mddev->events;
565         sb->events_cleared = cpu_to_le64(bitmap->mddev->events);
566
567         bitmap->flags |= BITMAP_HOSTENDIAN;
568         sb->version = cpu_to_le32(BITMAP_MAJOR_HOSTENDIAN);
569
570         kunmap_atomic(sb, KM_USER0);
571
572         return 0;
573 }
574
575 /* read the superblock from the bitmap file and initialize some bitmap fields */
576 static int bitmap_read_sb(struct bitmap *bitmap)
577 {
578         char *reason = NULL;
579         bitmap_super_t *sb;
580         unsigned long chunksize, daemon_sleep, write_behind;
581         unsigned long long events;
582         int err = -EINVAL;
583
584         /* page 0 is the superblock, read it... */
585         if (bitmap->file) {
586                 loff_t isize = i_size_read(bitmap->file->f_mapping->host);
587                 int bytes = isize > PAGE_SIZE ? PAGE_SIZE : isize;
588
589                 bitmap->sb_page = read_page(bitmap->file, 0, bitmap, bytes);
590         } else {
591                 bitmap->sb_page = read_sb_page(bitmap->mddev,
592                                                bitmap->mddev->bitmap_info.offset,
593                                                NULL,
594                                                0, sizeof(bitmap_super_t));
595         }
596         if (IS_ERR(bitmap->sb_page)) {
597                 err = PTR_ERR(bitmap->sb_page);
598                 bitmap->sb_page = NULL;
599                 return err;
600         }
601
602         sb = kmap_atomic(bitmap->sb_page, KM_USER0);
603
604         chunksize = le32_to_cpu(sb->chunksize);
605         daemon_sleep = le32_to_cpu(sb->daemon_sleep) * HZ;
606         write_behind = le32_to_cpu(sb->write_behind);
607
608         /* verify that the bitmap-specific fields are valid */
609         if (sb->magic != cpu_to_le32(BITMAP_MAGIC))
610                 reason = "bad magic";
611         else if (le32_to_cpu(sb->version) < BITMAP_MAJOR_LO ||
612                  le32_to_cpu(sb->version) > BITMAP_MAJOR_HI)
613                 reason = "unrecognized superblock version";
614         else if (chunksize < 512)
615                 reason = "bitmap chunksize too small";
616         else if (!is_power_of_2(chunksize))
617                 reason = "bitmap chunksize not a power of 2";
618         else if (daemon_sleep < 1 || daemon_sleep > MAX_SCHEDULE_TIMEOUT)
619                 reason = "daemon sleep period out of range";
620         else if (write_behind > COUNTER_MAX)
621                 reason = "write-behind limit out of range (0 - 16383)";
622         if (reason) {
623                 printk(KERN_INFO "%s: invalid bitmap file superblock: %s\n",
624                         bmname(bitmap), reason);
625                 goto out;
626         }
627
628         /* keep the array size field of the bitmap superblock up to date */
629         sb->sync_size = cpu_to_le64(bitmap->mddev->resync_max_sectors);
630
631         if (bitmap->mddev->persistent) {
632                 /*
633                  * We have a persistent array superblock, so compare the
634                  * bitmap's UUID and event counter to the mddev's
635                  */
636                 if (memcmp(sb->uuid, bitmap->mddev->uuid, 16)) {
637                         printk(KERN_INFO
638                                "%s: bitmap superblock UUID mismatch\n",
639                                bmname(bitmap));
640                         goto out;
641                 }
642                 events = le64_to_cpu(sb->events);
643                 if (events < bitmap->mddev->events) {
644                         printk(KERN_INFO
645                                "%s: bitmap file is out of date (%llu < %llu) "
646                                "-- forcing full recovery\n",
647                                bmname(bitmap), events,
648                                (unsigned long long) bitmap->mddev->events);
649                         sb->state |= cpu_to_le32(BITMAP_STALE);
650                 }
651         }
652
653         /* assign fields using values from superblock */
654         bitmap->mddev->bitmap_info.chunksize = chunksize;
655         bitmap->mddev->bitmap_info.daemon_sleep = daemon_sleep;
656         bitmap->mddev->bitmap_info.max_write_behind = write_behind;
657         bitmap->flags |= le32_to_cpu(sb->state);
658         if (le32_to_cpu(sb->version) == BITMAP_MAJOR_HOSTENDIAN)
659                 bitmap->flags |= BITMAP_HOSTENDIAN;
660         bitmap->events_cleared = le64_to_cpu(sb->events_cleared);
661         if (bitmap->flags & BITMAP_STALE)
662                 bitmap->events_cleared = bitmap->mddev->events;
663         err = 0;
664 out:
665         kunmap_atomic(sb, KM_USER0);
666         if (err)
667                 bitmap_print_sb(bitmap);
668         return err;
669 }
670
671 enum bitmap_mask_op {
672         MASK_SET,
673         MASK_UNSET
674 };
675
676 /* record the state of the bitmap in the superblock.  Return the old value */
677 static int bitmap_mask_state(struct bitmap *bitmap, enum bitmap_state bits,
678                              enum bitmap_mask_op op)
679 {
680         bitmap_super_t *sb;
681         int old;
682
683         if (!bitmap->sb_page) /* can't set the state */
684                 return 0;
685         sb = kmap_atomic(bitmap->sb_page, KM_USER0);
686         old = le32_to_cpu(sb->state) & bits;
687         switch (op) {
688         case MASK_SET:
689                 sb->state |= cpu_to_le32(bits);
690                 bitmap->flags |= bits;
691                 break;
692         case MASK_UNSET:
693                 sb->state &= cpu_to_le32(~bits);
694                 bitmap->flags &= ~bits;
695                 break;
696         default:
697                 BUG();
698         }
699         kunmap_atomic(sb, KM_USER0);
700         return old;
701 }
702
703 /*
704  * general bitmap file operations
705  */
706
707 /*
708  * on-disk bitmap:
709  *
710  * Use one bit per "chunk" (block set). We do the disk I/O on the bitmap
711  * file a page at a time. There's a superblock at the start of the file.
712  */
713 /* calculate the index of the page that contains this bit */
714 static inline unsigned long file_page_index(struct bitmap *bitmap, unsigned long chunk)
715 {
716         if (!bitmap->mddev->bitmap_info.external)
717                 chunk += sizeof(bitmap_super_t) << 3;
718         return chunk >> PAGE_BIT_SHIFT;
719 }
720
721 /* calculate the (bit) offset of this bit within a page */
722 static inline unsigned long file_page_offset(struct bitmap *bitmap, unsigned long chunk)
723 {
724         if (!bitmap->mddev->bitmap_info.external)
725                 chunk += sizeof(bitmap_super_t) << 3;
726         return chunk & (PAGE_BITS - 1);
727 }
728
729 /*
730  * return a pointer to the page in the filemap that contains the given bit
731  *
732  * this lookup is complicated by the fact that the bitmap sb might be exactly
733  * 1 page (e.g., x86) or less than 1 page -- so the bitmap might start on page
734  * 0 or page 1
735  */
736 static inline struct page *filemap_get_page(struct bitmap *bitmap,
737                                             unsigned long chunk)
738 {
739         if (file_page_index(bitmap, chunk) >= bitmap->file_pages)
740                 return NULL;
741         return bitmap->filemap[file_page_index(bitmap, chunk)
742                                - file_page_index(bitmap, 0)];
743 }
744
745 static void bitmap_file_unmap(struct bitmap *bitmap)
746 {
747         struct page **map, *sb_page;
748         unsigned long *attr;
749         int pages;
750         unsigned long flags;
751
752         spin_lock_irqsave(&bitmap->lock, flags);
753         map = bitmap->filemap;
754         bitmap->filemap = NULL;
755         attr = bitmap->filemap_attr;
756         bitmap->filemap_attr = NULL;
757         pages = bitmap->file_pages;
758         bitmap->file_pages = 0;
759         sb_page = bitmap->sb_page;
760         bitmap->sb_page = NULL;
761         spin_unlock_irqrestore(&bitmap->lock, flags);
762
763         while (pages--)
764                 if (map[pages] != sb_page) /* 0 is sb_page, release it below */
765                         free_buffers(map[pages]);
766         kfree(map);
767         kfree(attr);
768
769         if (sb_page)
770                 free_buffers(sb_page);
771 }
772
773 static void bitmap_file_put(struct bitmap *bitmap)
774 {
775         struct file *file;
776         unsigned long flags;
777
778         spin_lock_irqsave(&bitmap->lock, flags);
779         file = bitmap->file;
780         bitmap->file = NULL;
781         spin_unlock_irqrestore(&bitmap->lock, flags);
782
783         if (file)
784                 wait_event(bitmap->write_wait,
785                            atomic_read(&bitmap->pending_writes)==0);
786         bitmap_file_unmap(bitmap);
787
788         if (file) {
789                 struct inode *inode = file->f_path.dentry->d_inode;
790                 invalidate_mapping_pages(inode->i_mapping, 0, -1);
791                 fput(file);
792         }
793 }
794
795 /*
796  * bitmap_file_kick - if an error occurs while manipulating the bitmap file
797  * then it is no longer reliable, so we stop using it and we mark the file
798  * as failed in the superblock
799  */
800 static void bitmap_file_kick(struct bitmap *bitmap)
801 {
802         char *path, *ptr = NULL;
803
804         if (bitmap_mask_state(bitmap, BITMAP_STALE, MASK_SET) == 0) {
805                 bitmap_update_sb(bitmap);
806
807                 if (bitmap->file) {
808                         path = kmalloc(PAGE_SIZE, GFP_KERNEL);
809                         if (path)
810                                 ptr = d_path(&bitmap->file->f_path, path,
811                                              PAGE_SIZE);
812
813                         printk(KERN_ALERT
814                               "%s: kicking failed bitmap file %s from array!\n",
815                               bmname(bitmap), IS_ERR(ptr) ? "" : ptr);
816
817                         kfree(path);
818                 } else
819                         printk(KERN_ALERT
820                                "%s: disabling internal bitmap due to errors\n",
821                                bmname(bitmap));
822         }
823
824         bitmap_file_put(bitmap);
825
826         return;
827 }
828
829 enum bitmap_page_attr {
830         BITMAP_PAGE_DIRTY = 0,     /* there are set bits that need to be synced */
831         BITMAP_PAGE_PENDING = 1,   /* there are bits that are being cleaned.
832                                     * i.e. counter is 1 or 2. */
833         BITMAP_PAGE_NEEDWRITE = 2, /* there are cleared bits that need to be synced */
834 };
835
836 static inline void set_page_attr(struct bitmap *bitmap, struct page *page,
837                                 enum bitmap_page_attr attr)
838 {
839         __set_bit((page->index<<2) + attr, bitmap->filemap_attr);
840 }
841
842 static inline void clear_page_attr(struct bitmap *bitmap, struct page *page,
843                                 enum bitmap_page_attr attr)
844 {
845         __clear_bit((page->index<<2) + attr, bitmap->filemap_attr);
846 }
847
848 static inline unsigned long test_page_attr(struct bitmap *bitmap, struct page *page,
849                                            enum bitmap_page_attr attr)
850 {
851         return test_bit((page->index<<2) + attr, bitmap->filemap_attr);
852 }
853
854 /*
855  * bitmap_file_set_bit -- called before performing a write to the md device
856  * to set (and eventually sync) a particular bit in the bitmap file
857  *
858  * we set the bit immediately, then we record the page number so that
859  * when an unplug occurs, we can flush the dirty pages out to disk
860  */
861 static void bitmap_file_set_bit(struct bitmap *bitmap, sector_t block)
862 {
863         unsigned long bit;
864         struct page *page;
865         void *kaddr;
866         unsigned long chunk = block >> CHUNK_BLOCK_SHIFT(bitmap);
867
868         if (!bitmap->filemap)
869                 return;
870
871         page = filemap_get_page(bitmap, chunk);
872         if (!page)
873                 return;
874         bit = file_page_offset(bitmap, chunk);
875
876         /* set the bit */
877         kaddr = kmap_atomic(page, KM_USER0);
878         if (bitmap->flags & BITMAP_HOSTENDIAN)
879                 set_bit(bit, kaddr);
880         else
881                 __set_bit_le(bit, kaddr);
882         kunmap_atomic(kaddr, KM_USER0);
883         pr_debug("set file bit %lu page %lu\n", bit, page->index);
884         /* record page number so it gets flushed to disk when unplug occurs */
885         set_page_attr(bitmap, page, BITMAP_PAGE_DIRTY);
886 }
887
888 /* this gets called when the md device is ready to unplug its underlying
889  * (slave) device queues -- before we let any writes go down, we need to
890  * sync the dirty pages of the bitmap file to disk */
891 void bitmap_unplug(struct bitmap *bitmap)
892 {
893         unsigned long i, flags;
894         int dirty, need_write;
895         struct page *page;
896         int wait = 0;
897
898         if (!bitmap)
899                 return;
900
901         /* look at each page to see if there are any set bits that need to be
902          * flushed out to disk */
903         for (i = 0; i < bitmap->file_pages; i++) {
904                 spin_lock_irqsave(&bitmap->lock, flags);
905                 if (!bitmap->filemap) {
906                         spin_unlock_irqrestore(&bitmap->lock, flags);
907                         return;
908                 }
909                 page = bitmap->filemap[i];
910                 dirty = test_page_attr(bitmap, page, BITMAP_PAGE_DIRTY);
911                 need_write = test_page_attr(bitmap, page, BITMAP_PAGE_NEEDWRITE);
912                 clear_page_attr(bitmap, page, BITMAP_PAGE_DIRTY);
913                 clear_page_attr(bitmap, page, BITMAP_PAGE_NEEDWRITE);
914                 if (dirty)
915                         wait = 1;
916                 spin_unlock_irqrestore(&bitmap->lock, flags);
917
918                 if (dirty || need_write)
919                         write_page(bitmap, page, 0);
920         }
921         if (wait) { /* if any writes were performed, we need to wait on them */
922                 if (bitmap->file)
923                         wait_event(bitmap->write_wait,
924                                    atomic_read(&bitmap->pending_writes)==0);
925                 else
926                         md_super_wait(bitmap->mddev);
927         }
928         if (bitmap->flags & BITMAP_WRITE_ERROR)
929                 bitmap_file_kick(bitmap);
930 }
931 EXPORT_SYMBOL(bitmap_unplug);
932
933 static void bitmap_set_memory_bits(struct bitmap *bitmap, sector_t offset, int needed);
934 /* * bitmap_init_from_disk -- called at bitmap_create time to initialize
935  * the in-memory bitmap from the on-disk bitmap -- also, sets up the
936  * memory mapping of the bitmap file
937  * Special cases:
938  *   if there's no bitmap file, or if the bitmap file had been
939  *   previously kicked from the array, we mark all the bits as
940  *   1's in order to cause a full resync.
941  *
942  * We ignore all bits for sectors that end earlier than 'start'.
943  * This is used when reading an out-of-date bitmap...
944  */
945 static int bitmap_init_from_disk(struct bitmap *bitmap, sector_t start)
946 {
947         unsigned long i, chunks, index, oldindex, bit;
948         struct page *page = NULL, *oldpage = NULL;
949         unsigned long num_pages, bit_cnt = 0;
950         struct file *file;
951         unsigned long bytes, offset;
952         int outofdate;
953         int ret = -ENOSPC;
954         void *paddr;
955
956         chunks = bitmap->chunks;
957         file = bitmap->file;
958
959         BUG_ON(!file && !bitmap->mddev->bitmap_info.offset);
960
961         outofdate = bitmap->flags & BITMAP_STALE;
962         if (outofdate)
963                 printk(KERN_INFO "%s: bitmap file is out of date, doing full "
964                         "recovery\n", bmname(bitmap));
965
966         bytes = DIV_ROUND_UP(bitmap->chunks, 8);
967         if (!bitmap->mddev->bitmap_info.external)
968                 bytes += sizeof(bitmap_super_t);
969
970         num_pages = DIV_ROUND_UP(bytes, PAGE_SIZE);
971
972         if (file && i_size_read(file->f_mapping->host) < bytes) {
973                 printk(KERN_INFO "%s: bitmap file too short %lu < %lu\n",
974                         bmname(bitmap),
975                         (unsigned long) i_size_read(file->f_mapping->host),
976                         bytes);
977                 goto err;
978         }
979
980         ret = -ENOMEM;
981
982         bitmap->filemap = kmalloc(sizeof(struct page *) * num_pages, GFP_KERNEL);
983         if (!bitmap->filemap)
984                 goto err;
985
986         /* We need 4 bits per page, rounded up to a multiple of sizeof(unsigned long) */
987         bitmap->filemap_attr = kzalloc(
988                 roundup(DIV_ROUND_UP(num_pages*4, 8), sizeof(unsigned long)),
989                 GFP_KERNEL);
990         if (!bitmap->filemap_attr)
991                 goto err;
992
993         oldindex = ~0L;
994
995         for (i = 0; i < chunks; i++) {
996                 int b;
997                 index = file_page_index(bitmap, i);
998                 bit = file_page_offset(bitmap, i);
999                 if (index != oldindex) { /* this is a new page, read it in */
1000                         int count;
1001                         /* unmap the old page, we're done with it */
1002                         if (index == num_pages-1)
1003                                 count = bytes - index * PAGE_SIZE;
1004                         else
1005                                 count = PAGE_SIZE;
1006                         if (index == 0 && bitmap->sb_page) {
1007                                 /*
1008                                  * if we're here then the superblock page
1009                                  * contains some bits (PAGE_SIZE != sizeof sb)
1010                                  * we've already read it in, so just use it
1011                                  */
1012                                 page = bitmap->sb_page;
1013                                 offset = sizeof(bitmap_super_t);
1014                                 if (!file)
1015                                         page = read_sb_page(
1016                                                 bitmap->mddev,
1017                                                 bitmap->mddev->bitmap_info.offset,
1018                                                 page,
1019                                                 index, count);
1020                         } else if (file) {
1021                                 page = read_page(file, index, bitmap, count);
1022                                 offset = 0;
1023                         } else {
1024                                 page = read_sb_page(bitmap->mddev,
1025                                                     bitmap->mddev->bitmap_info.offset,
1026                                                     NULL,
1027                                                     index, count);
1028                                 offset = 0;
1029                         }
1030                         if (IS_ERR(page)) { /* read error */
1031                                 ret = PTR_ERR(page);
1032                                 goto err;
1033                         }
1034
1035                         oldindex = index;
1036                         oldpage = page;
1037
1038                         bitmap->filemap[bitmap->file_pages++] = page;
1039                         bitmap->last_page_size = count;
1040
1041                         if (outofdate) {
1042                                 /*
1043                                  * if bitmap is out of date, dirty the
1044                                  * whole page and write it out
1045                                  */
1046                                 paddr = kmap_atomic(page, KM_USER0);
1047                                 memset(paddr + offset, 0xff,
1048                                        PAGE_SIZE - offset);
1049                                 kunmap_atomic(paddr, KM_USER0);
1050                                 write_page(bitmap, page, 1);
1051
1052                                 ret = -EIO;
1053                                 if (bitmap->flags & BITMAP_WRITE_ERROR)
1054                                         goto err;
1055                         }
1056                 }
1057                 paddr = kmap_atomic(page, KM_USER0);
1058                 if (bitmap->flags & BITMAP_HOSTENDIAN)
1059                         b = test_bit(bit, paddr);
1060                 else
1061                         b = test_bit_le(bit, paddr);
1062                 kunmap_atomic(paddr, KM_USER0);
1063                 if (b) {
1064                         /* if the disk bit is set, set the memory bit */
1065                         int needed = ((sector_t)(i+1) << (CHUNK_BLOCK_SHIFT(bitmap))
1066                                       >= start);
1067                         bitmap_set_memory_bits(bitmap,
1068                                                (sector_t)i << CHUNK_BLOCK_SHIFT(bitmap),
1069                                                needed);
1070                         bit_cnt++;
1071                 }
1072         }
1073
1074         /* everything went OK */
1075         ret = 0;
1076         bitmap_mask_state(bitmap, BITMAP_STALE, MASK_UNSET);
1077
1078         if (bit_cnt) { /* Kick recovery if any bits were set */
1079                 set_bit(MD_RECOVERY_NEEDED, &bitmap->mddev->recovery);
1080                 md_wakeup_thread(bitmap->mddev->thread);
1081         }
1082
1083         printk(KERN_INFO "%s: bitmap initialized from disk: "
1084                "read %lu/%lu pages, set %lu of %lu bits\n",
1085                bmname(bitmap), bitmap->file_pages, num_pages, bit_cnt, chunks);
1086
1087         return 0;
1088
1089  err:
1090         printk(KERN_INFO "%s: bitmap initialisation failed: %d\n",
1091                bmname(bitmap), ret);
1092         return ret;
1093 }
1094
1095 void bitmap_write_all(struct bitmap *bitmap)
1096 {
1097         /* We don't actually write all bitmap blocks here,
1098          * just flag them as needing to be written
1099          */
1100         int i;
1101
1102         spin_lock_irq(&bitmap->lock);
1103         for (i = 0; i < bitmap->file_pages; i++)
1104                 set_page_attr(bitmap, bitmap->filemap[i],
1105                               BITMAP_PAGE_NEEDWRITE);
1106         bitmap->allclean = 0;
1107         spin_unlock_irq(&bitmap->lock);
1108 }
1109
1110 static void bitmap_count_page(struct bitmap *bitmap, sector_t offset, int inc)
1111 {
1112         sector_t chunk = offset >> CHUNK_BLOCK_SHIFT(bitmap);
1113         unsigned long page = chunk >> PAGE_COUNTER_SHIFT;
1114         bitmap->bp[page].count += inc;
1115         bitmap_checkfree(bitmap, page);
1116 }
1117 static bitmap_counter_t *bitmap_get_counter(struct bitmap *bitmap,
1118                                             sector_t offset, sector_t *blocks,
1119                                             int create);
1120
1121 /*
1122  * bitmap daemon -- periodically wakes up to clean bits and flush pages
1123  *                      out to disk
1124  */
1125
1126 void bitmap_daemon_work(struct mddev *mddev)
1127 {
1128         struct bitmap *bitmap;
1129         unsigned long j;
1130         unsigned long flags;
1131         struct page *page = NULL, *lastpage = NULL;
1132         sector_t blocks;
1133         void *paddr;
1134
1135         /* Use a mutex to guard daemon_work against
1136          * bitmap_destroy.
1137          */
1138         mutex_lock(&mddev->bitmap_info.mutex);
1139         bitmap = mddev->bitmap;
1140         if (bitmap == NULL) {
1141                 mutex_unlock(&mddev->bitmap_info.mutex);
1142                 return;
1143         }
1144         if (time_before(jiffies, bitmap->daemon_lastrun
1145                         + mddev->bitmap_info.daemon_sleep))
1146                 goto done;
1147
1148         bitmap->daemon_lastrun = jiffies;
1149         if (bitmap->allclean) {
1150                 mddev->thread->timeout = MAX_SCHEDULE_TIMEOUT;
1151                 goto done;
1152         }
1153         bitmap->allclean = 1;
1154
1155         spin_lock_irqsave(&bitmap->lock, flags);
1156         for (j = 0; j < bitmap->chunks; j++) {
1157                 bitmap_counter_t *bmc;
1158                 if (!bitmap->filemap)
1159                         /* error or shutdown */
1160                         break;
1161
1162                 page = filemap_get_page(bitmap, j);
1163
1164                 if (page != lastpage) {
1165                         /* skip this page unless it's marked as needing cleaning */
1166                         if (!test_page_attr(bitmap, page, BITMAP_PAGE_PENDING)) {
1167                                 int need_write = test_page_attr(bitmap, page,
1168                                                                 BITMAP_PAGE_NEEDWRITE);
1169                                 if (need_write)
1170                                         clear_page_attr(bitmap, page, BITMAP_PAGE_NEEDWRITE);
1171
1172                                 spin_unlock_irqrestore(&bitmap->lock, flags);
1173                                 if (need_write)
1174                                         write_page(bitmap, page, 0);
1175                                 spin_lock_irqsave(&bitmap->lock, flags);
1176                                 j |= (PAGE_BITS - 1);
1177                                 continue;
1178                         }
1179
1180                         /* grab the new page, sync and release the old */
1181                         if (lastpage != NULL) {
1182                                 if (test_page_attr(bitmap, lastpage,
1183                                                    BITMAP_PAGE_NEEDWRITE)) {
1184                                         clear_page_attr(bitmap, lastpage,
1185                                                         BITMAP_PAGE_NEEDWRITE);
1186                                         spin_unlock_irqrestore(&bitmap->lock, flags);
1187                                         write_page(bitmap, lastpage, 0);
1188                                 } else {
1189                                         set_page_attr(bitmap, lastpage,
1190                                                       BITMAP_PAGE_NEEDWRITE);
1191                                         bitmap->allclean = 0;
1192                                         spin_unlock_irqrestore(&bitmap->lock, flags);
1193                                 }
1194                         } else
1195                                 spin_unlock_irqrestore(&bitmap->lock, flags);
1196                         lastpage = page;
1197
1198                         /* We are possibly going to clear some bits, so make
1199                          * sure that events_cleared is up-to-date.
1200                          */
1201                         if (bitmap->need_sync &&
1202                             mddev->bitmap_info.external == 0) {
1203                                 bitmap_super_t *sb;
1204                                 bitmap->need_sync = 0;
1205                                 sb = kmap_atomic(bitmap->sb_page, KM_USER0);
1206                                 sb->events_cleared =
1207                                         cpu_to_le64(bitmap->events_cleared);
1208                                 kunmap_atomic(sb, KM_USER0);
1209                                 write_page(bitmap, bitmap->sb_page, 1);
1210                         }
1211                         spin_lock_irqsave(&bitmap->lock, flags);
1212                         if (!bitmap->need_sync)
1213                                 clear_page_attr(bitmap, page, BITMAP_PAGE_PENDING);
1214                         else
1215                                 bitmap->allclean = 0;
1216                 }
1217                 bmc = bitmap_get_counter(bitmap,
1218                                          (sector_t)j << CHUNK_BLOCK_SHIFT(bitmap),
1219                                          &blocks, 0);
1220                 if (!bmc)
1221                         j |= PAGE_COUNTER_MASK;
1222                 else if (*bmc) {
1223                         if (*bmc == 1 && !bitmap->need_sync) {
1224                                 /* we can clear the bit */
1225                                 *bmc = 0;
1226                                 bitmap_count_page(bitmap,
1227                                                   (sector_t)j << CHUNK_BLOCK_SHIFT(bitmap),
1228                                                   -1);
1229
1230                                 /* clear the bit */
1231                                 paddr = kmap_atomic(page, KM_USER0);
1232                                 if (bitmap->flags & BITMAP_HOSTENDIAN)
1233                                         clear_bit(file_page_offset(bitmap, j),
1234                                                   paddr);
1235                                 else
1236                                         __clear_bit_le(
1237                                                 file_page_offset(bitmap,
1238                                                                  j),
1239                                                 paddr);
1240                                 kunmap_atomic(paddr, KM_USER0);
1241                         } else if (*bmc <= 2) {
1242                                 *bmc = 1; /* maybe clear the bit next time */
1243                                 set_page_attr(bitmap, page, BITMAP_PAGE_PENDING);
1244                                 bitmap->allclean = 0;
1245                         }
1246                 }
1247         }
1248         spin_unlock_irqrestore(&bitmap->lock, flags);
1249
1250         /* now sync the final page */
1251         if (lastpage != NULL) {
1252                 spin_lock_irqsave(&bitmap->lock, flags);
1253                 if (test_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE)) {
1254                         clear_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE);
1255                         spin_unlock_irqrestore(&bitmap->lock, flags);
1256                         write_page(bitmap, lastpage, 0);
1257                 } else {
1258                         set_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE);
1259                         bitmap->allclean = 0;
1260                         spin_unlock_irqrestore(&bitmap->lock, flags);
1261                 }
1262         }
1263
1264  done:
1265         if (bitmap->allclean == 0)
1266                 mddev->thread->timeout =
1267                         mddev->bitmap_info.daemon_sleep;
1268         mutex_unlock(&mddev->bitmap_info.mutex);
1269 }
1270
1271 static bitmap_counter_t *bitmap_get_counter(struct bitmap *bitmap,
1272                                             sector_t offset, sector_t *blocks,
1273                                             int create)
1274 __releases(bitmap->lock)
1275 __acquires(bitmap->lock)
1276 {
1277         /* If 'create', we might release the lock and reclaim it.
1278          * The lock must have been taken with interrupts enabled.
1279          * If !create, we don't release the lock.
1280          */
1281         sector_t chunk = offset >> CHUNK_BLOCK_SHIFT(bitmap);
1282         unsigned long page = chunk >> PAGE_COUNTER_SHIFT;
1283         unsigned long pageoff = (chunk & PAGE_COUNTER_MASK) << COUNTER_BYTE_SHIFT;
1284         sector_t csize;
1285         int err;
1286
1287         err = bitmap_checkpage(bitmap, page, create);
1288
1289         if (bitmap->bp[page].hijacked ||
1290             bitmap->bp[page].map == NULL)
1291                 csize = ((sector_t)1) << (CHUNK_BLOCK_SHIFT(bitmap) +
1292                                           PAGE_COUNTER_SHIFT - 1);
1293         else
1294                 csize = ((sector_t)1) << (CHUNK_BLOCK_SHIFT(bitmap));
1295         *blocks = csize - (offset & (csize - 1));
1296
1297         if (err < 0)
1298                 return NULL;
1299
1300         /* now locked ... */
1301
1302         if (bitmap->bp[page].hijacked) { /* hijacked pointer */
1303                 /* should we use the first or second counter field
1304                  * of the hijacked pointer? */
1305                 int hi = (pageoff > PAGE_COUNTER_MASK);
1306                 return  &((bitmap_counter_t *)
1307                           &bitmap->bp[page].map)[hi];
1308         } else /* page is allocated */
1309                 return (bitmap_counter_t *)
1310                         &(bitmap->bp[page].map[pageoff]);
1311 }
1312
1313 int bitmap_startwrite(struct bitmap *bitmap, sector_t offset, unsigned long sectors, int behind)
1314 {
1315         if (!bitmap)
1316                 return 0;
1317
1318         if (behind) {
1319                 int bw;
1320                 atomic_inc(&bitmap->behind_writes);
1321                 bw = atomic_read(&bitmap->behind_writes);
1322                 if (bw > bitmap->behind_writes_used)
1323                         bitmap->behind_writes_used = bw;
1324
1325                 pr_debug("inc write-behind count %d/%lu\n",
1326                          bw, bitmap->mddev->bitmap_info.max_write_behind);
1327         }
1328
1329         while (sectors) {
1330                 sector_t blocks;
1331                 bitmap_counter_t *bmc;
1332
1333                 spin_lock_irq(&bitmap->lock);
1334                 bmc = bitmap_get_counter(bitmap, offset, &blocks, 1);
1335                 if (!bmc) {
1336                         spin_unlock_irq(&bitmap->lock);
1337                         return 0;
1338                 }
1339
1340                 if (unlikely(COUNTER(*bmc) == COUNTER_MAX)) {
1341                         DEFINE_WAIT(__wait);
1342                         /* note that it is safe to do the prepare_to_wait
1343                          * after the test as long as we do it before dropping
1344                          * the spinlock.
1345                          */
1346                         prepare_to_wait(&bitmap->overflow_wait, &__wait,
1347                                         TASK_UNINTERRUPTIBLE);
1348                         spin_unlock_irq(&bitmap->lock);
1349                         io_schedule();
1350                         finish_wait(&bitmap->overflow_wait, &__wait);
1351                         continue;
1352                 }
1353
1354                 switch (*bmc) {
1355                 case 0:
1356                         bitmap_file_set_bit(bitmap, offset);
1357                         bitmap_count_page(bitmap, offset, 1);
1358                         /* fall through */
1359                 case 1:
1360                         *bmc = 2;
1361                 }
1362
1363                 (*bmc)++;
1364
1365                 spin_unlock_irq(&bitmap->lock);
1366
1367                 offset += blocks;
1368                 if (sectors > blocks)
1369                         sectors -= blocks;
1370                 else
1371                         sectors = 0;
1372         }
1373         return 0;
1374 }
1375 EXPORT_SYMBOL(bitmap_startwrite);
1376
1377 void bitmap_endwrite(struct bitmap *bitmap, sector_t offset, unsigned long sectors,
1378                      int success, int behind)
1379 {
1380         if (!bitmap)
1381                 return;
1382         if (behind) {
1383                 if (atomic_dec_and_test(&bitmap->behind_writes))
1384                         wake_up(&bitmap->behind_wait);
1385                 pr_debug("dec write-behind count %d/%lu\n",
1386                          atomic_read(&bitmap->behind_writes),
1387                          bitmap->mddev->bitmap_info.max_write_behind);
1388         }
1389
1390         while (sectors) {
1391                 sector_t blocks;
1392                 unsigned long flags;
1393                 bitmap_counter_t *bmc;
1394
1395                 spin_lock_irqsave(&bitmap->lock, flags);
1396                 bmc = bitmap_get_counter(bitmap, offset, &blocks, 0);
1397                 if (!bmc) {
1398                         spin_unlock_irqrestore(&bitmap->lock, flags);
1399                         return;
1400                 }
1401
1402                 if (success && !bitmap->mddev->degraded &&
1403                     bitmap->events_cleared < bitmap->mddev->events) {
1404                         bitmap->events_cleared = bitmap->mddev->events;
1405                         bitmap->need_sync = 1;
1406                         sysfs_notify_dirent_safe(bitmap->sysfs_can_clear);
1407                 }
1408
1409                 if (!success && !NEEDED(*bmc))
1410                         *bmc |= NEEDED_MASK;
1411
1412                 if (COUNTER(*bmc) == COUNTER_MAX)
1413                         wake_up(&bitmap->overflow_wait);
1414
1415                 (*bmc)--;
1416                 if (*bmc <= 2) {
1417                         set_page_attr(bitmap,
1418                                       filemap_get_page(
1419                                               bitmap,
1420                                               offset >> CHUNK_BLOCK_SHIFT(bitmap)),
1421                                       BITMAP_PAGE_PENDING);
1422                         bitmap->allclean = 0;
1423                 }
1424                 spin_unlock_irqrestore(&bitmap->lock, flags);
1425                 offset += blocks;
1426                 if (sectors > blocks)
1427                         sectors -= blocks;
1428                 else
1429                         sectors = 0;
1430         }
1431 }
1432 EXPORT_SYMBOL(bitmap_endwrite);
1433
1434 static int __bitmap_start_sync(struct bitmap *bitmap, sector_t offset, sector_t *blocks,
1435                                int degraded)
1436 {
1437         bitmap_counter_t *bmc;
1438         int rv;
1439         if (bitmap == NULL) {/* FIXME or bitmap set as 'failed' */
1440                 *blocks = 1024;
1441                 return 1; /* always resync if no bitmap */
1442         }
1443         spin_lock_irq(&bitmap->lock);
1444         bmc = bitmap_get_counter(bitmap, offset, blocks, 0);
1445         rv = 0;
1446         if (bmc) {
1447                 /* locked */
1448                 if (RESYNC(*bmc))
1449                         rv = 1;
1450                 else if (NEEDED(*bmc)) {
1451                         rv = 1;
1452                         if (!degraded) { /* don't set/clear bits if degraded */
1453                                 *bmc |= RESYNC_MASK;
1454                                 *bmc &= ~NEEDED_MASK;
1455                         }
1456                 }
1457         }
1458         spin_unlock_irq(&bitmap->lock);
1459         return rv;
1460 }
1461
1462 int bitmap_start_sync(struct bitmap *bitmap, sector_t offset, sector_t *blocks,
1463                       int degraded)
1464 {
1465         /* bitmap_start_sync must always report on multiples of whole
1466          * pages, otherwise resync (which is very PAGE_SIZE based) will
1467          * get confused.
1468          * So call __bitmap_start_sync repeatedly (if needed) until
1469          * At least PAGE_SIZE>>9 blocks are covered.
1470          * Return the 'or' of the result.
1471          */
1472         int rv = 0;
1473         sector_t blocks1;
1474
1475         *blocks = 0;
1476         while (*blocks < (PAGE_SIZE>>9)) {
1477                 rv |= __bitmap_start_sync(bitmap, offset,
1478                                           &blocks1, degraded);
1479                 offset += blocks1;
1480                 *blocks += blocks1;
1481         }
1482         return rv;
1483 }
1484 EXPORT_SYMBOL(bitmap_start_sync);
1485
1486 void bitmap_end_sync(struct bitmap *bitmap, sector_t offset, sector_t *blocks, int aborted)
1487 {
1488         bitmap_counter_t *bmc;
1489         unsigned long flags;
1490
1491         if (bitmap == NULL) {
1492                 *blocks = 1024;
1493                 return;
1494         }
1495         spin_lock_irqsave(&bitmap->lock, flags);
1496         bmc = bitmap_get_counter(bitmap, offset, blocks, 0);
1497         if (bmc == NULL)
1498                 goto unlock;
1499         /* locked */
1500         if (RESYNC(*bmc)) {
1501                 *bmc &= ~RESYNC_MASK;
1502
1503                 if (!NEEDED(*bmc) && aborted)
1504                         *bmc |= NEEDED_MASK;
1505                 else {
1506                         if (*bmc <= 2) {
1507                                 set_page_attr(bitmap,
1508                                               filemap_get_page(bitmap, offset >> CHUNK_BLOCK_SHIFT(bitmap)),
1509                                               BITMAP_PAGE_PENDING);
1510                                 bitmap->allclean = 0;
1511                         }
1512                 }
1513         }
1514  unlock:
1515         spin_unlock_irqrestore(&bitmap->lock, flags);
1516 }
1517 EXPORT_SYMBOL(bitmap_end_sync);
1518
1519 void bitmap_close_sync(struct bitmap *bitmap)
1520 {
1521         /* Sync has finished, and any bitmap chunks that weren't synced
1522          * properly have been aborted.  It remains to us to clear the
1523          * RESYNC bit wherever it is still on
1524          */
1525         sector_t sector = 0;
1526         sector_t blocks;
1527         if (!bitmap)
1528                 return;
1529         while (sector < bitmap->mddev->resync_max_sectors) {
1530                 bitmap_end_sync(bitmap, sector, &blocks, 0);
1531                 sector += blocks;
1532         }
1533 }
1534 EXPORT_SYMBOL(bitmap_close_sync);
1535
1536 void bitmap_cond_end_sync(struct bitmap *bitmap, sector_t sector)
1537 {
1538         sector_t s = 0;
1539         sector_t blocks;
1540
1541         if (!bitmap)
1542                 return;
1543         if (sector == 0) {
1544                 bitmap->last_end_sync = jiffies;
1545                 return;
1546         }
1547         if (time_before(jiffies, (bitmap->last_end_sync
1548                                   + bitmap->mddev->bitmap_info.daemon_sleep)))
1549                 return;
1550         wait_event(bitmap->mddev->recovery_wait,
1551                    atomic_read(&bitmap->mddev->recovery_active) == 0);
1552
1553         bitmap->mddev->curr_resync_completed = sector;
1554         set_bit(MD_CHANGE_CLEAN, &bitmap->mddev->flags);
1555         sector &= ~((1ULL << CHUNK_BLOCK_SHIFT(bitmap)) - 1);
1556         s = 0;
1557         while (s < sector && s < bitmap->mddev->resync_max_sectors) {
1558                 bitmap_end_sync(bitmap, s, &blocks, 0);
1559                 s += blocks;
1560         }
1561         bitmap->last_end_sync = jiffies;
1562         sysfs_notify(&bitmap->mddev->kobj, NULL, "sync_completed");
1563 }
1564 EXPORT_SYMBOL(bitmap_cond_end_sync);
1565
1566 static void bitmap_set_memory_bits(struct bitmap *bitmap, sector_t offset, int needed)
1567 {
1568         /* For each chunk covered by any of these sectors, set the
1569          * counter to 1 and set resync_needed.  They should all
1570          * be 0 at this point
1571          */
1572
1573         sector_t secs;
1574         bitmap_counter_t *bmc;
1575         spin_lock_irq(&bitmap->lock);
1576         bmc = bitmap_get_counter(bitmap, offset, &secs, 1);
1577         if (!bmc) {
1578                 spin_unlock_irq(&bitmap->lock);
1579                 return;
1580         }
1581         if (!*bmc) {
1582                 struct page *page;
1583                 *bmc = 2 | (needed ? NEEDED_MASK : 0);
1584                 bitmap_count_page(bitmap, offset, 1);
1585                 page = filemap_get_page(bitmap, offset >> CHUNK_BLOCK_SHIFT(bitmap));
1586                 set_page_attr(bitmap, page, BITMAP_PAGE_PENDING);
1587                 bitmap->allclean = 0;
1588         }
1589         spin_unlock_irq(&bitmap->lock);
1590 }
1591
1592 /* dirty the memory and file bits for bitmap chunks "s" to "e" */
1593 void bitmap_dirty_bits(struct bitmap *bitmap, unsigned long s, unsigned long e)
1594 {
1595         unsigned long chunk;
1596
1597         for (chunk = s; chunk <= e; chunk++) {
1598                 sector_t sec = (sector_t)chunk << CHUNK_BLOCK_SHIFT(bitmap);
1599                 bitmap_set_memory_bits(bitmap, sec, 1);
1600                 spin_lock_irq(&bitmap->lock);
1601                 bitmap_file_set_bit(bitmap, sec);
1602                 spin_unlock_irq(&bitmap->lock);
1603                 if (sec < bitmap->mddev->recovery_cp)
1604                         /* We are asserting that the array is dirty,
1605                          * so move the recovery_cp address back so
1606                          * that it is obvious that it is dirty
1607                          */
1608                         bitmap->mddev->recovery_cp = sec;
1609         }
1610 }
1611
1612 /*
1613  * flush out any pending updates
1614  */
1615 void bitmap_flush(struct mddev *mddev)
1616 {
1617         struct bitmap *bitmap = mddev->bitmap;
1618         long sleep;
1619
1620         if (!bitmap) /* there was no bitmap */
1621                 return;
1622
1623         /* run the daemon_work three time to ensure everything is flushed
1624          * that can be
1625          */
1626         sleep = mddev->bitmap_info.daemon_sleep * 2;
1627         bitmap->daemon_lastrun -= sleep;
1628         bitmap_daemon_work(mddev);
1629         bitmap->daemon_lastrun -= sleep;
1630         bitmap_daemon_work(mddev);
1631         bitmap->daemon_lastrun -= sleep;
1632         bitmap_daemon_work(mddev);
1633         bitmap_update_sb(bitmap);
1634 }
1635
1636 /*
1637  * free memory that was allocated
1638  */
1639 static void bitmap_free(struct bitmap *bitmap)
1640 {
1641         unsigned long k, pages;
1642         struct bitmap_page *bp;
1643
1644         if (!bitmap) /* there was no bitmap */
1645                 return;
1646
1647         /* release the bitmap file and kill the daemon */
1648         bitmap_file_put(bitmap);
1649
1650         bp = bitmap->bp;
1651         pages = bitmap->pages;
1652
1653         /* free all allocated memory */
1654
1655         if (bp) /* deallocate the page memory */
1656                 for (k = 0; k < pages; k++)
1657                         if (bp[k].map && !bp[k].hijacked)
1658                                 kfree(bp[k].map);
1659         kfree(bp);
1660         kfree(bitmap);
1661 }
1662
1663 void bitmap_destroy(struct mddev *mddev)
1664 {
1665         struct bitmap *bitmap = mddev->bitmap;
1666
1667         if (!bitmap) /* there was no bitmap */
1668                 return;
1669
1670         mutex_lock(&mddev->bitmap_info.mutex);
1671         mddev->bitmap = NULL; /* disconnect from the md device */
1672         mutex_unlock(&mddev->bitmap_info.mutex);
1673         if (mddev->thread)
1674                 mddev->thread->timeout = MAX_SCHEDULE_TIMEOUT;
1675
1676         if (bitmap->sysfs_can_clear)
1677                 sysfs_put(bitmap->sysfs_can_clear);
1678
1679         bitmap_free(bitmap);
1680 }
1681
1682 /*
1683  * initialize the bitmap structure
1684  * if this returns an error, bitmap_destroy must be called to do clean up
1685  */
1686 int bitmap_create(struct mddev *mddev)
1687 {
1688         struct bitmap *bitmap;
1689         sector_t blocks = mddev->resync_max_sectors;
1690         unsigned long chunks;
1691         unsigned long pages;
1692         struct file *file = mddev->bitmap_info.file;
1693         int err;
1694         struct sysfs_dirent *bm = NULL;
1695
1696         BUILD_BUG_ON(sizeof(bitmap_super_t) != 256);
1697
1698         if (!file
1699             && !mddev->bitmap_info.offset) /* bitmap disabled, nothing to do */
1700                 return 0;
1701
1702         BUG_ON(file && mddev->bitmap_info.offset);
1703
1704         bitmap = kzalloc(sizeof(*bitmap), GFP_KERNEL);
1705         if (!bitmap)
1706                 return -ENOMEM;
1707
1708         spin_lock_init(&bitmap->lock);
1709         atomic_set(&bitmap->pending_writes, 0);
1710         init_waitqueue_head(&bitmap->write_wait);
1711         init_waitqueue_head(&bitmap->overflow_wait);
1712         init_waitqueue_head(&bitmap->behind_wait);
1713
1714         bitmap->mddev = mddev;
1715
1716         if (mddev->kobj.sd)
1717                 bm = sysfs_get_dirent(mddev->kobj.sd, NULL, "bitmap");
1718         if (bm) {
1719                 bitmap->sysfs_can_clear = sysfs_get_dirent(bm, NULL, "can_clear");
1720                 sysfs_put(bm);
1721         } else
1722                 bitmap->sysfs_can_clear = NULL;
1723
1724         bitmap->file = file;
1725         if (file) {
1726                 get_file(file);
1727                 /* As future accesses to this file will use bmap,
1728                  * and bypass the page cache, we must sync the file
1729                  * first.
1730                  */
1731                 vfs_fsync(file, 1);
1732         }
1733         /* read superblock from bitmap file (this sets mddev->bitmap_info.chunksize) */
1734         if (!mddev->bitmap_info.external) {
1735                 /*
1736                  * If 'MD_ARRAY_FIRST_USE' is set, then device-mapper is
1737                  * instructing us to create a new on-disk bitmap instance.
1738                  */
1739                 if (test_and_clear_bit(MD_ARRAY_FIRST_USE, &mddev->flags))
1740                         err = bitmap_new_disk_sb(bitmap);
1741                 else
1742                         err = bitmap_read_sb(bitmap);
1743         } else {
1744                 err = 0;
1745                 if (mddev->bitmap_info.chunksize == 0 ||
1746                     mddev->bitmap_info.daemon_sleep == 0)
1747                         /* chunksize and time_base need to be
1748                          * set first. */
1749                         err = -EINVAL;
1750         }
1751         if (err)
1752                 goto error;
1753
1754         bitmap->daemon_lastrun = jiffies;
1755         bitmap->chunkshift = ffz(~mddev->bitmap_info.chunksize);
1756
1757         /* now that chunksize and chunkshift are set, we can use these macros */
1758         chunks = (blocks + CHUNK_BLOCK_RATIO(bitmap) - 1) >>
1759                         CHUNK_BLOCK_SHIFT(bitmap);
1760         pages = (chunks + PAGE_COUNTER_RATIO - 1) / PAGE_COUNTER_RATIO;
1761
1762         BUG_ON(!pages);
1763
1764         bitmap->chunks = chunks;
1765         bitmap->pages = pages;
1766         bitmap->missing_pages = pages;
1767
1768         bitmap->bp = kzalloc(pages * sizeof(*bitmap->bp), GFP_KERNEL);
1769
1770         err = -ENOMEM;
1771         if (!bitmap->bp)
1772                 goto error;
1773
1774         printk(KERN_INFO "created bitmap (%lu pages) for device %s\n",
1775                 pages, bmname(bitmap));
1776
1777         mddev->bitmap = bitmap;
1778
1779
1780         return (bitmap->flags & BITMAP_WRITE_ERROR) ? -EIO : 0;
1781
1782  error:
1783         bitmap_free(bitmap);
1784         return err;
1785 }
1786
1787 int bitmap_load(struct mddev *mddev)
1788 {
1789         int err = 0;
1790         sector_t start = 0;
1791         sector_t sector = 0;
1792         struct bitmap *bitmap = mddev->bitmap;
1793
1794         if (!bitmap)
1795                 goto out;
1796
1797         /* Clear out old bitmap info first:  Either there is none, or we
1798          * are resuming after someone else has possibly changed things,
1799          * so we should forget old cached info.
1800          * All chunks should be clean, but some might need_sync.
1801          */
1802         while (sector < mddev->resync_max_sectors) {
1803                 sector_t blocks;
1804                 bitmap_start_sync(bitmap, sector, &blocks, 0);
1805                 sector += blocks;
1806         }
1807         bitmap_close_sync(bitmap);
1808
1809         if (mddev->degraded == 0
1810             || bitmap->events_cleared == mddev->events)
1811                 /* no need to keep dirty bits to optimise a
1812                  * re-add of a missing device */
1813                 start = mddev->recovery_cp;
1814
1815         err = bitmap_init_from_disk(bitmap, start);
1816
1817         if (err)
1818                 goto out;
1819
1820         mddev->thread->timeout = mddev->bitmap_info.daemon_sleep;
1821         md_wakeup_thread(mddev->thread);
1822
1823         bitmap_update_sb(bitmap);
1824
1825         if (bitmap->flags & BITMAP_WRITE_ERROR)
1826                 err = -EIO;
1827 out:
1828         return err;
1829 }
1830 EXPORT_SYMBOL_GPL(bitmap_load);
1831
1832 void bitmap_status(struct seq_file *seq, struct bitmap *bitmap)
1833 {
1834         unsigned long chunk_kb;
1835         unsigned long flags;
1836
1837         if (!bitmap)
1838                 return;
1839
1840         spin_lock_irqsave(&bitmap->lock, flags);
1841         chunk_kb = bitmap->mddev->bitmap_info.chunksize >> 10;
1842         seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
1843                    "%lu%s chunk",
1844                    bitmap->pages - bitmap->missing_pages,
1845                    bitmap->pages,
1846                    (bitmap->pages - bitmap->missing_pages)
1847                    << (PAGE_SHIFT - 10),
1848                    chunk_kb ? chunk_kb : bitmap->mddev->bitmap_info.chunksize,
1849                    chunk_kb ? "KB" : "B");
1850         if (bitmap->file) {
1851                 seq_printf(seq, ", file: ");
1852                 seq_path(seq, &bitmap->file->f_path, " \t\n");
1853         }
1854
1855         seq_printf(seq, "\n");
1856         spin_unlock_irqrestore(&bitmap->lock, flags);
1857 }
1858
1859 static ssize_t
1860 location_show(struct mddev *mddev, char *page)
1861 {
1862         ssize_t len;
1863         if (mddev->bitmap_info.file)
1864                 len = sprintf(page, "file");
1865         else if (mddev->bitmap_info.offset)
1866                 len = sprintf(page, "%+lld", (long long)mddev->bitmap_info.offset);
1867         else
1868                 len = sprintf(page, "none");
1869         len += sprintf(page+len, "\n");
1870         return len;
1871 }
1872
1873 static ssize_t
1874 location_store(struct mddev *mddev, const char *buf, size_t len)
1875 {
1876
1877         if (mddev->pers) {
1878                 if (!mddev->pers->quiesce)
1879                         return -EBUSY;
1880                 if (mddev->recovery || mddev->sync_thread)
1881                         return -EBUSY;
1882         }
1883
1884         if (mddev->bitmap || mddev->bitmap_info.file ||
1885             mddev->bitmap_info.offset) {
1886                 /* bitmap already configured.  Only option is to clear it */
1887                 if (strncmp(buf, "none", 4) != 0)
1888                         return -EBUSY;
1889                 if (mddev->pers) {
1890                         mddev->pers->quiesce(mddev, 1);
1891                         bitmap_destroy(mddev);
1892                         mddev->pers->quiesce(mddev, 0);
1893                 }
1894                 mddev->bitmap_info.offset = 0;
1895                 if (mddev->bitmap_info.file) {
1896                         struct file *f = mddev->bitmap_info.file;
1897                         mddev->bitmap_info.file = NULL;
1898                         restore_bitmap_write_access(f);
1899                         fput(f);
1900                 }
1901         } else {
1902                 /* No bitmap, OK to set a location */
1903                 long long offset;
1904                 if (strncmp(buf, "none", 4) == 0)
1905                         /* nothing to be done */;
1906                 else if (strncmp(buf, "file:", 5) == 0) {
1907                         /* Not supported yet */
1908                         return -EINVAL;
1909                 } else {
1910                         int rv;
1911                         if (buf[0] == '+')
1912                                 rv = strict_strtoll(buf+1, 10, &offset);
1913                         else
1914                                 rv = strict_strtoll(buf, 10, &offset);
1915                         if (rv)
1916                                 return rv;
1917                         if (offset == 0)
1918                                 return -EINVAL;
1919                         if (mddev->bitmap_info.external == 0 &&
1920                             mddev->major_version == 0 &&
1921                             offset != mddev->bitmap_info.default_offset)
1922                                 return -EINVAL;
1923                         mddev->bitmap_info.offset = offset;
1924                         if (mddev->pers) {
1925                                 mddev->pers->quiesce(mddev, 1);
1926                                 rv = bitmap_create(mddev);
1927                                 if (!rv)
1928                                         rv = bitmap_load(mddev);
1929                                 if (rv) {
1930                                         bitmap_destroy(mddev);
1931                                         mddev->bitmap_info.offset = 0;
1932                                 }
1933                                 mddev->pers->quiesce(mddev, 0);
1934                                 if (rv)
1935                                         return rv;
1936                         }
1937                 }
1938         }
1939         if (!mddev->external) {
1940                 /* Ensure new bitmap info is stored in
1941                  * metadata promptly.
1942                  */
1943                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
1944                 md_wakeup_thread(mddev->thread);
1945         }
1946         return len;
1947 }
1948
1949 static struct md_sysfs_entry bitmap_location =
1950 __ATTR(location, S_IRUGO|S_IWUSR, location_show, location_store);
1951
1952 static ssize_t
1953 timeout_show(struct mddev *mddev, char *page)
1954 {
1955         ssize_t len;
1956         unsigned long secs = mddev->bitmap_info.daemon_sleep / HZ;
1957         unsigned long jifs = mddev->bitmap_info.daemon_sleep % HZ;
1958
1959         len = sprintf(page, "%lu", secs);
1960         if (jifs)
1961                 len += sprintf(page+len, ".%03u", jiffies_to_msecs(jifs));
1962         len += sprintf(page+len, "\n");
1963         return len;
1964 }
1965
1966 static ssize_t
1967 timeout_store(struct mddev *mddev, const char *buf, size_t len)
1968 {
1969         /* timeout can be set at any time */
1970         unsigned long timeout;
1971         int rv = strict_strtoul_scaled(buf, &timeout, 4);
1972         if (rv)
1973                 return rv;
1974
1975         /* just to make sure we don't overflow... */
1976         if (timeout >= LONG_MAX / HZ)
1977                 return -EINVAL;
1978
1979         timeout = timeout * HZ / 10000;
1980
1981         if (timeout >= MAX_SCHEDULE_TIMEOUT)
1982                 timeout = MAX_SCHEDULE_TIMEOUT-1;
1983         if (timeout < 1)
1984                 timeout = 1;
1985         mddev->bitmap_info.daemon_sleep = timeout;
1986         if (mddev->thread) {
1987                 /* if thread->timeout is MAX_SCHEDULE_TIMEOUT, then
1988                  * the bitmap is all clean and we don't need to
1989                  * adjust the timeout right now
1990                  */
1991                 if (mddev->thread->timeout < MAX_SCHEDULE_TIMEOUT) {
1992                         mddev->thread->timeout = timeout;
1993                         md_wakeup_thread(mddev->thread);
1994                 }
1995         }
1996         return len;
1997 }
1998
1999 static struct md_sysfs_entry bitmap_timeout =
2000 __ATTR(time_base, S_IRUGO|S_IWUSR, timeout_show, timeout_store);
2001
2002 static ssize_t
2003 backlog_show(struct mddev *mddev, char *page)
2004 {
2005         return sprintf(page, "%lu\n", mddev->bitmap_info.max_write_behind);
2006 }
2007
2008 static ssize_t
2009 backlog_store(struct mddev *mddev, const char *buf, size_t len)
2010 {
2011         unsigned long backlog;
2012         int rv = strict_strtoul(buf, 10, &backlog);
2013         if (rv)
2014                 return rv;
2015         if (backlog > COUNTER_MAX)
2016                 return -EINVAL;
2017         mddev->bitmap_info.max_write_behind = backlog;
2018         return len;
2019 }
2020
2021 static struct md_sysfs_entry bitmap_backlog =
2022 __ATTR(backlog, S_IRUGO|S_IWUSR, backlog_show, backlog_store);
2023
2024 static ssize_t
2025 chunksize_show(struct mddev *mddev, char *page)
2026 {
2027         return sprintf(page, "%lu\n", mddev->bitmap_info.chunksize);
2028 }
2029
2030 static ssize_t
2031 chunksize_store(struct mddev *mddev, const char *buf, size_t len)
2032 {
2033         /* Can only be changed when no bitmap is active */
2034         int rv;
2035         unsigned long csize;
2036         if (mddev->bitmap)
2037                 return -EBUSY;
2038         rv = strict_strtoul(buf, 10, &csize);
2039         if (rv)
2040                 return rv;
2041         if (csize < 512 ||
2042             !is_power_of_2(csize))
2043                 return -EINVAL;
2044         mddev->bitmap_info.chunksize = csize;
2045         return len;
2046 }
2047
2048 static struct md_sysfs_entry bitmap_chunksize =
2049 __ATTR(chunksize, S_IRUGO|S_IWUSR, chunksize_show, chunksize_store);
2050
2051 static ssize_t metadata_show(struct mddev *mddev, char *page)
2052 {
2053         return sprintf(page, "%s\n", (mddev->bitmap_info.external
2054                                       ? "external" : "internal"));
2055 }
2056
2057 static ssize_t metadata_store(struct mddev *mddev, const char *buf, size_t len)
2058 {
2059         if (mddev->bitmap ||
2060             mddev->bitmap_info.file ||
2061             mddev->bitmap_info.offset)
2062                 return -EBUSY;
2063         if (strncmp(buf, "external", 8) == 0)
2064                 mddev->bitmap_info.external = 1;
2065         else if (strncmp(buf, "internal", 8) == 0)
2066                 mddev->bitmap_info.external = 0;
2067         else
2068                 return -EINVAL;
2069         return len;
2070 }
2071
2072 static struct md_sysfs_entry bitmap_metadata =
2073 __ATTR(metadata, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
2074
2075 static ssize_t can_clear_show(struct mddev *mddev, char *page)
2076 {
2077         int len;
2078         if (mddev->bitmap)
2079                 len = sprintf(page, "%s\n", (mddev->bitmap->need_sync ?
2080                                              "false" : "true"));
2081         else
2082                 len = sprintf(page, "\n");
2083         return len;
2084 }
2085
2086 static ssize_t can_clear_store(struct mddev *mddev, const char *buf, size_t len)
2087 {
2088         if (mddev->bitmap == NULL)
2089                 return -ENOENT;
2090         if (strncmp(buf, "false", 5) == 0)
2091                 mddev->bitmap->need_sync = 1;
2092         else if (strncmp(buf, "true", 4) == 0) {
2093                 if (mddev->degraded)
2094                         return -EBUSY;
2095                 mddev->bitmap->need_sync = 0;
2096         } else
2097                 return -EINVAL;
2098         return len;
2099 }
2100
2101 static struct md_sysfs_entry bitmap_can_clear =
2102 __ATTR(can_clear, S_IRUGO|S_IWUSR, can_clear_show, can_clear_store);
2103
2104 static ssize_t
2105 behind_writes_used_show(struct mddev *mddev, char *page)
2106 {
2107         if (mddev->bitmap == NULL)
2108                 return sprintf(page, "0\n");
2109         return sprintf(page, "%lu\n",
2110                        mddev->bitmap->behind_writes_used);
2111 }
2112
2113 static ssize_t
2114 behind_writes_used_reset(struct mddev *mddev, const char *buf, size_t len)
2115 {
2116         if (mddev->bitmap)
2117                 mddev->bitmap->behind_writes_used = 0;
2118         return len;
2119 }
2120
2121 static struct md_sysfs_entry max_backlog_used =
2122 __ATTR(max_backlog_used, S_IRUGO | S_IWUSR,
2123        behind_writes_used_show, behind_writes_used_reset);
2124
2125 static struct attribute *md_bitmap_attrs[] = {
2126         &bitmap_location.attr,
2127         &bitmap_timeout.attr,
2128         &bitmap_backlog.attr,
2129         &bitmap_chunksize.attr,
2130         &bitmap_metadata.attr,
2131         &bitmap_can_clear.attr,
2132         &max_backlog_used.attr,
2133         NULL
2134 };
2135 struct attribute_group md_bitmap_group = {
2136         .name = "bitmap",
2137         .attrs = md_bitmap_attrs,
2138 };
2139