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