md: remove needless setting of thread->timeout in raid10_quiesce
[safe/jmp/linux-2.6] / 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  * wait if count gets too high, wake when it drops to half.
17  */
18
19 #include <linux/blkdev.h>
20 #include <linux/module.h>
21 #include <linux/errno.h>
22 #include <linux/slab.h>
23 #include <linux/init.h>
24 #include <linux/timer.h>
25 #include <linux/sched.h>
26 #include <linux/list.h>
27 #include <linux/file.h>
28 #include <linux/mount.h>
29 #include <linux/buffer_head.h>
30 #include "md.h"
31 #include "bitmap.h"
32
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 //#define DPRINTK PRINTK /* set this NULL to avoid verbose debug output */
55 #define DPRINTK(x...) do { } while(0)
56
57 #ifndef PRINTK
58 #  if DEBUG > 0
59 #    define PRINTK(x...) printk(KERN_DEBUG x)
60 #  else
61 #    define PRINTK(x...)
62 #  endif
63 #endif
64
65 static inline char * bmname(struct bitmap *bitmap)
66 {
67         return bitmap->mddev ? mdname(bitmap->mddev) : "mdX";
68 }
69
70
71 /*
72  * just a placeholder - calls kmalloc for bitmap pages
73  */
74 static unsigned char *bitmap_alloc_page(struct bitmap *bitmap)
75 {
76         unsigned char *page;
77
78 #ifdef INJECT_FAULTS_1
79         page = NULL;
80 #else
81         page = kmalloc(PAGE_SIZE, GFP_NOIO);
82 #endif
83         if (!page)
84                 printk("%s: bitmap_alloc_page FAILED\n", bmname(bitmap));
85         else
86                 PRINTK("%s: bitmap_alloc_page: allocated page at %p\n",
87                         bmname(bitmap), page);
88         return page;
89 }
90
91 /*
92  * for now just a placeholder -- just calls kfree for bitmap pages
93  */
94 static void bitmap_free_page(struct bitmap *bitmap, unsigned char *page)
95 {
96         PRINTK("%s: bitmap_free_page: free page %p\n", bmname(bitmap), page);
97         kfree(page);
98 }
99
100 /*
101  * check a page and, if necessary, allocate it (or hijack it if the alloc fails)
102  *
103  * 1) check to see if this page is allocated, if it's not then try to alloc
104  * 2) if the alloc fails, set the page's hijacked flag so we'll use the
105  *    page pointer directly as a counter
106  *
107  * if we find our page, we increment the page's refcount so that it stays
108  * allocated while we're using it
109  */
110 static int bitmap_checkpage(struct bitmap *bitmap, unsigned long page, int create)
111 __releases(bitmap->lock)
112 __acquires(bitmap->lock)
113 {
114         unsigned char *mappage;
115
116         if (page >= bitmap->pages) {
117                 /* This can happen if bitmap_start_sync goes beyond
118                  * End-of-device while looking for a whole page.
119                  * It is harmless.
120                  */
121                 return -EINVAL;
122         }
123
124
125         if (bitmap->bp[page].hijacked) /* it's hijacked, don't try to alloc */
126                 return 0;
127
128         if (bitmap->bp[page].map) /* page is already allocated, just return */
129                 return 0;
130
131         if (!create)
132                 return -ENOENT;
133
134         spin_unlock_irq(&bitmap->lock);
135
136         /* this page has not been allocated yet */
137
138         if ((mappage = bitmap_alloc_page(bitmap)) == NULL) {
139                 PRINTK("%s: bitmap map page allocation failed, hijacking\n",
140                         bmname(bitmap));
141                 /* failed - set the hijacked flag so that we can use the
142                  * pointer as a counter */
143                 spin_lock_irq(&bitmap->lock);
144                 if (!bitmap->bp[page].map)
145                         bitmap->bp[page].hijacked = 1;
146                 goto out;
147         }
148
149         /* got a page */
150
151         spin_lock_irq(&bitmap->lock);
152
153         /* recheck the page */
154
155         if (bitmap->bp[page].map || bitmap->bp[page].hijacked) {
156                 /* somebody beat us to getting the page */
157                 bitmap_free_page(bitmap, mappage);
158                 return 0;
159         }
160
161         /* no page was in place and we have one, so install it */
162
163         memset(mappage, 0, PAGE_SIZE);
164         bitmap->bp[page].map = mappage;
165         bitmap->missing_pages--;
166 out:
167         return 0;
168 }
169
170
171 /* if page is completely empty, put it back on the free list, or dealloc it */
172 /* if page was hijacked, unmark the flag so it might get alloced next time */
173 /* Note: lock should be held when calling this */
174 static void bitmap_checkfree(struct bitmap *bitmap, unsigned long page)
175 {
176         char *ptr;
177
178         if (bitmap->bp[page].count) /* page is still busy */
179                 return;
180
181         /* page is no longer in use, it can be released */
182
183         if (bitmap->bp[page].hijacked) { /* page was hijacked, undo this now */
184                 bitmap->bp[page].hijacked = 0;
185                 bitmap->bp[page].map = NULL;
186                 return;
187         }
188
189         /* normal case, free the page */
190
191 #if 0
192 /* actually ... let's not.  We will probably need the page again exactly when
193  * memory is tight and we are flusing to disk
194  */
195         return;
196 #else
197         ptr = bitmap->bp[page].map;
198         bitmap->bp[page].map = NULL;
199         bitmap->missing_pages++;
200         bitmap_free_page(bitmap, ptr);
201         return;
202 #endif
203 }
204
205
206 /*
207  * bitmap file handling - read and write the bitmap file and its superblock
208  */
209
210 /*
211  * basic page I/O operations
212  */
213
214 /* IO operations when bitmap is stored near all superblocks */
215 static struct page *read_sb_page(mddev_t *mddev, long offset,
216                                  struct page *page,
217                                  unsigned long index, int size)
218 {
219         /* choose a good rdev and read the page from there */
220
221         mdk_rdev_t *rdev;
222         sector_t target;
223
224         if (!page)
225                 page = alloc_page(GFP_KERNEL);
226         if (!page)
227                 return ERR_PTR(-ENOMEM);
228
229         list_for_each_entry(rdev, &mddev->disks, same_set) {
230                 if (! test_bit(In_sync, &rdev->flags)
231                     || test_bit(Faulty, &rdev->flags))
232                         continue;
233
234                 target = rdev->sb_start + offset + index * (PAGE_SIZE/512);
235
236                 if (sync_page_io(rdev->bdev, target,
237                                  roundup(size, bdev_logical_block_size(rdev->bdev)),
238                                  page, READ)) {
239                         page->index = index;
240                         attach_page_buffers(page, NULL); /* so that free_buffer will
241                                                           * quietly no-op */
242                         return page;
243                 }
244         }
245         return ERR_PTR(-EIO);
246
247 }
248
249 static mdk_rdev_t *next_active_rdev(mdk_rdev_t *rdev, mddev_t *mddev)
250 {
251         /* Iterate the disks of an mddev, using rcu to protect access to the
252          * linked list, and raising the refcount of devices we return to ensure
253          * they don't disappear while in use.
254          * As devices are only added or removed when raid_disk is < 0 and
255          * nr_pending is 0 and In_sync is clear, the entries we return will
256          * still be in the same position on the list when we re-enter
257          * list_for_each_continue_rcu.
258          */
259         struct list_head *pos;
260         rcu_read_lock();
261         if (rdev == NULL)
262                 /* start at the beginning */
263                 pos = &mddev->disks;
264         else {
265                 /* release the previous rdev and start from there. */
266                 rdev_dec_pending(rdev, mddev);
267                 pos = &rdev->same_set;
268         }
269         list_for_each_continue_rcu(pos, &mddev->disks) {
270                 rdev = list_entry(pos, mdk_rdev_t, same_set);
271                 if (rdev->raid_disk >= 0 &&
272                     !test_bit(Faulty, &rdev->flags)) {
273                         /* this is a usable devices */
274                         atomic_inc(&rdev->nr_pending);
275                         rcu_read_unlock();
276                         return rdev;
277                 }
278         }
279         rcu_read_unlock();
280         return NULL;
281 }
282
283 static int write_sb_page(struct bitmap *bitmap, struct page *page, int wait)
284 {
285         mdk_rdev_t *rdev = NULL;
286         mddev_t *mddev = bitmap->mddev;
287
288         while ((rdev = next_active_rdev(rdev, mddev)) != NULL) {
289                         int size = PAGE_SIZE;
290                         long offset = mddev->bitmap_info.offset;
291                         if (page->index == bitmap->file_pages-1)
292                                 size = roundup(bitmap->last_page_size,
293                                                bdev_logical_block_size(rdev->bdev));
294                         /* Just make sure we aren't corrupting data or
295                          * metadata
296                          */
297                         if (offset < 0) {
298                                 /* DATA  BITMAP METADATA  */
299                                 if (offset
300                                     + (long)(page->index * (PAGE_SIZE/512))
301                                     + size/512 > 0)
302                                         /* bitmap runs in to metadata */
303                                         goto bad_alignment;
304                                 if (rdev->data_offset + mddev->dev_sectors
305                                     > rdev->sb_start + offset)
306                                         /* data runs in to bitmap */
307                                         goto bad_alignment;
308                         } else if (rdev->sb_start < rdev->data_offset) {
309                                 /* METADATA BITMAP DATA */
310                                 if (rdev->sb_start
311                                     + offset
312                                     + page->index*(PAGE_SIZE/512) + size/512
313                                     > rdev->data_offset)
314                                         /* bitmap runs in to data */
315                                         goto bad_alignment;
316                         } else {
317                                 /* DATA METADATA BITMAP - no problems */
318                         }
319                         md_super_write(mddev, rdev,
320                                        rdev->sb_start + offset
321                                        + page->index * (PAGE_SIZE/512),
322                                        size,
323                                        page);
324         }
325
326         if (wait)
327                 md_super_wait(mddev);
328         return 0;
329
330  bad_alignment:
331         return -EINVAL;
332 }
333
334 static void bitmap_file_kick(struct bitmap *bitmap);
335 /*
336  * write out a page to a file
337  */
338 static void write_page(struct bitmap *bitmap, struct page *page, int wait)
339 {
340         struct buffer_head *bh;
341
342         if (bitmap->file == NULL) {
343                 switch (write_sb_page(bitmap, page, wait)) {
344                 case -EINVAL:
345                         bitmap->flags |= BITMAP_WRITE_ERROR;
346                 }
347         } else {
348
349                 bh = page_buffers(page);
350
351                 while (bh && bh->b_blocknr) {
352                         atomic_inc(&bitmap->pending_writes);
353                         set_buffer_locked(bh);
354                         set_buffer_mapped(bh);
355                         submit_bh(WRITE, bh);
356                         bh = bh->b_this_page;
357                 }
358
359                 if (wait) {
360                         wait_event(bitmap->write_wait,
361                                    atomic_read(&bitmap->pending_writes)==0);
362                 }
363         }
364         if (bitmap->flags & BITMAP_WRITE_ERROR)
365                 bitmap_file_kick(bitmap);
366 }
367
368 static void end_bitmap_write(struct buffer_head *bh, int uptodate)
369 {
370         struct bitmap *bitmap = bh->b_private;
371         unsigned long flags;
372
373         if (!uptodate) {
374                 spin_lock_irqsave(&bitmap->lock, flags);
375                 bitmap->flags |= BITMAP_WRITE_ERROR;
376                 spin_unlock_irqrestore(&bitmap->lock, flags);
377         }
378         if (atomic_dec_and_test(&bitmap->pending_writes))
379                 wake_up(&bitmap->write_wait);
380 }
381
382 /* copied from buffer.c */
383 static void
384 __clear_page_buffers(struct page *page)
385 {
386         ClearPagePrivate(page);
387         set_page_private(page, 0);
388         page_cache_release(page);
389 }
390 static void free_buffers(struct page *page)
391 {
392         struct buffer_head *bh = page_buffers(page);
393
394         while (bh) {
395                 struct buffer_head *next = bh->b_this_page;
396                 free_buffer_head(bh);
397                 bh = next;
398         }
399         __clear_page_buffers(page);
400         put_page(page);
401 }
402
403 /* read a page from a file.
404  * We both read the page, and attach buffers to the page to record the
405  * address of each block (using bmap).  These addresses will be used
406  * to write the block later, completely bypassing the filesystem.
407  * This usage is similar to how swap files are handled, and allows us
408  * to write to a file with no concerns of memory allocation failing.
409  */
410 static struct page *read_page(struct file *file, unsigned long index,
411                               struct bitmap *bitmap,
412                               unsigned long count)
413 {
414         struct page *page = NULL;
415         struct inode *inode = file->f_path.dentry->d_inode;
416         struct buffer_head *bh;
417         sector_t block;
418
419         PRINTK("read bitmap file (%dB @ %Lu)\n", (int)PAGE_SIZE,
420                         (unsigned long long)index << PAGE_SHIFT);
421
422         page = alloc_page(GFP_KERNEL);
423         if (!page)
424                 page = ERR_PTR(-ENOMEM);
425         if (IS_ERR(page))
426                 goto out;
427
428         bh = alloc_page_buffers(page, 1<<inode->i_blkbits, 0);
429         if (!bh) {
430                 put_page(page);
431                 page = ERR_PTR(-ENOMEM);
432                 goto out;
433         }
434         attach_page_buffers(page, bh);
435         block = index << (PAGE_SHIFT - inode->i_blkbits);
436         while (bh) {
437                 if (count == 0)
438                         bh->b_blocknr = 0;
439                 else {
440                         bh->b_blocknr = bmap(inode, block);
441                         if (bh->b_blocknr == 0) {
442                                 /* Cannot use this file! */
443                                 free_buffers(page);
444                                 page = ERR_PTR(-EINVAL);
445                                 goto out;
446                         }
447                         bh->b_bdev = inode->i_sb->s_bdev;
448                         if (count < (1<<inode->i_blkbits))
449                                 count = 0;
450                         else
451                                 count -= (1<<inode->i_blkbits);
452
453                         bh->b_end_io = end_bitmap_write;
454                         bh->b_private = bitmap;
455                         atomic_inc(&bitmap->pending_writes);
456                         set_buffer_locked(bh);
457                         set_buffer_mapped(bh);
458                         submit_bh(READ, bh);
459                 }
460                 block++;
461                 bh = bh->b_this_page;
462         }
463         page->index = index;
464
465         wait_event(bitmap->write_wait,
466                    atomic_read(&bitmap->pending_writes)==0);
467         if (bitmap->flags & BITMAP_WRITE_ERROR) {
468                 free_buffers(page);
469                 page = ERR_PTR(-EIO);
470         }
471 out:
472         if (IS_ERR(page))
473                 printk(KERN_ALERT "md: bitmap read error: (%dB @ %Lu): %ld\n",
474                         (int)PAGE_SIZE,
475                         (unsigned long long)index << PAGE_SHIFT,
476                         PTR_ERR(page));
477         return page;
478 }
479
480 /*
481  * bitmap file superblock operations
482  */
483
484 /* update the event counter and sync the superblock to disk */
485 void bitmap_update_sb(struct bitmap *bitmap)
486 {
487         bitmap_super_t *sb;
488         unsigned long flags;
489
490         if (!bitmap || !bitmap->mddev) /* no bitmap for this array */
491                 return;
492         spin_lock_irqsave(&bitmap->lock, flags);
493         if (!bitmap->sb_page) { /* no superblock */
494                 spin_unlock_irqrestore(&bitmap->lock, flags);
495                 return;
496         }
497         spin_unlock_irqrestore(&bitmap->lock, flags);
498         sb = (bitmap_super_t *)kmap_atomic(bitmap->sb_page, KM_USER0);
499         sb->events = cpu_to_le64(bitmap->mddev->events);
500         if (bitmap->mddev->events < bitmap->events_cleared) {
501                 /* rocking back to read-only */
502                 bitmap->events_cleared = bitmap->mddev->events;
503                 sb->events_cleared = cpu_to_le64(bitmap->events_cleared);
504         }
505         kunmap_atomic(sb, KM_USER0);
506         write_page(bitmap, bitmap->sb_page, 1);
507 }
508
509 /* print out the bitmap file superblock */
510 void bitmap_print_sb(struct bitmap *bitmap)
511 {
512         bitmap_super_t *sb;
513
514         if (!bitmap || !bitmap->sb_page)
515                 return;
516         sb = (bitmap_super_t *)kmap_atomic(bitmap->sb_page, KM_USER0);
517         printk(KERN_DEBUG "%s: bitmap file superblock:\n", bmname(bitmap));
518         printk(KERN_DEBUG "         magic: %08x\n", le32_to_cpu(sb->magic));
519         printk(KERN_DEBUG "       version: %d\n", le32_to_cpu(sb->version));
520         printk(KERN_DEBUG "          uuid: %08x.%08x.%08x.%08x\n",
521                                         *(__u32 *)(sb->uuid+0),
522                                         *(__u32 *)(sb->uuid+4),
523                                         *(__u32 *)(sb->uuid+8),
524                                         *(__u32 *)(sb->uuid+12));
525         printk(KERN_DEBUG "        events: %llu\n",
526                         (unsigned long long) le64_to_cpu(sb->events));
527         printk(KERN_DEBUG "events cleared: %llu\n",
528                         (unsigned long long) le64_to_cpu(sb->events_cleared));
529         printk(KERN_DEBUG "         state: %08x\n", le32_to_cpu(sb->state));
530         printk(KERN_DEBUG "     chunksize: %d B\n", le32_to_cpu(sb->chunksize));
531         printk(KERN_DEBUG "  daemon sleep: %ds\n", le32_to_cpu(sb->daemon_sleep));
532         printk(KERN_DEBUG "     sync size: %llu KB\n",
533                         (unsigned long long)le64_to_cpu(sb->sync_size)/2);
534         printk(KERN_DEBUG "max write behind: %d\n", le32_to_cpu(sb->write_behind));
535         kunmap_atomic(sb, KM_USER0);
536 }
537
538 /* read the superblock from the bitmap file and initialize some bitmap fields */
539 static int bitmap_read_sb(struct bitmap *bitmap)
540 {
541         char *reason = NULL;
542         bitmap_super_t *sb;
543         unsigned long chunksize, daemon_sleep, write_behind;
544         unsigned long long events;
545         int err = -EINVAL;
546
547         /* page 0 is the superblock, read it... */
548         if (bitmap->file) {
549                 loff_t isize = i_size_read(bitmap->file->f_mapping->host);
550                 int bytes = isize > PAGE_SIZE ? PAGE_SIZE : isize;
551
552                 bitmap->sb_page = read_page(bitmap->file, 0, bitmap, bytes);
553         } else {
554                 bitmap->sb_page = read_sb_page(bitmap->mddev,
555                                                bitmap->mddev->bitmap_info.offset,
556                                                NULL,
557                                                0, sizeof(bitmap_super_t));
558         }
559         if (IS_ERR(bitmap->sb_page)) {
560                 err = PTR_ERR(bitmap->sb_page);
561                 bitmap->sb_page = NULL;
562                 return err;
563         }
564
565         sb = (bitmap_super_t *)kmap_atomic(bitmap->sb_page, KM_USER0);
566
567         chunksize = le32_to_cpu(sb->chunksize);
568         daemon_sleep = le32_to_cpu(sb->daemon_sleep) * HZ;
569         write_behind = le32_to_cpu(sb->write_behind);
570
571         /* verify that the bitmap-specific fields are valid */
572         if (sb->magic != cpu_to_le32(BITMAP_MAGIC))
573                 reason = "bad magic";
574         else if (le32_to_cpu(sb->version) < BITMAP_MAJOR_LO ||
575                  le32_to_cpu(sb->version) > BITMAP_MAJOR_HI)
576                 reason = "unrecognized superblock version";
577         else if (chunksize < 512)
578                 reason = "bitmap chunksize too small";
579         else if ((1 << ffz(~chunksize)) != chunksize)
580                 reason = "bitmap chunksize not a power of 2";
581         else if (daemon_sleep < 1 || daemon_sleep > MAX_SCHEDULE_TIMEOUT)
582                 reason = "daemon sleep period out of range";
583         else if (write_behind > COUNTER_MAX)
584                 reason = "write-behind limit out of range (0 - 16383)";
585         if (reason) {
586                 printk(KERN_INFO "%s: invalid bitmap file superblock: %s\n",
587                         bmname(bitmap), reason);
588                 goto out;
589         }
590
591         /* keep the array size field of the bitmap superblock up to date */
592         sb->sync_size = cpu_to_le64(bitmap->mddev->resync_max_sectors);
593
594         if (!bitmap->mddev->persistent)
595                 goto success;
596
597         /*
598          * if we have a persistent array superblock, compare the
599          * bitmap's UUID and event counter to the mddev's
600          */
601         if (memcmp(sb->uuid, bitmap->mddev->uuid, 16)) {
602                 printk(KERN_INFO "%s: bitmap superblock UUID mismatch\n",
603                         bmname(bitmap));
604                 goto out;
605         }
606         events = le64_to_cpu(sb->events);
607         if (events < bitmap->mddev->events) {
608                 printk(KERN_INFO "%s: bitmap file is out of date (%llu < %llu) "
609                         "-- forcing full recovery\n", bmname(bitmap), events,
610                         (unsigned long long) bitmap->mddev->events);
611                 sb->state |= cpu_to_le32(BITMAP_STALE);
612         }
613 success:
614         /* assign fields using values from superblock */
615         bitmap->mddev->bitmap_info.chunksize = chunksize;
616         bitmap->mddev->bitmap_info.daemon_sleep = daemon_sleep;
617         bitmap->daemon_lastrun = jiffies;
618         bitmap->mddev->bitmap_info.max_write_behind = write_behind;
619         bitmap->flags |= le32_to_cpu(sb->state);
620         if (le32_to_cpu(sb->version) == BITMAP_MAJOR_HOSTENDIAN)
621                 bitmap->flags |= BITMAP_HOSTENDIAN;
622         bitmap->events_cleared = le64_to_cpu(sb->events_cleared);
623         if (sb->state & cpu_to_le32(BITMAP_STALE))
624                 bitmap->events_cleared = bitmap->mddev->events;
625         err = 0;
626 out:
627         kunmap_atomic(sb, KM_USER0);
628         if (err)
629                 bitmap_print_sb(bitmap);
630         return err;
631 }
632
633 enum bitmap_mask_op {
634         MASK_SET,
635         MASK_UNSET
636 };
637
638 /* record the state of the bitmap in the superblock.  Return the old value */
639 static int bitmap_mask_state(struct bitmap *bitmap, enum bitmap_state bits,
640                              enum bitmap_mask_op op)
641 {
642         bitmap_super_t *sb;
643         unsigned long flags;
644         int old;
645
646         spin_lock_irqsave(&bitmap->lock, flags);
647         if (!bitmap->sb_page) { /* can't set the state */
648                 spin_unlock_irqrestore(&bitmap->lock, flags);
649                 return 0;
650         }
651         spin_unlock_irqrestore(&bitmap->lock, flags);
652         sb = (bitmap_super_t *)kmap_atomic(bitmap->sb_page, KM_USER0);
653         old = le32_to_cpu(sb->state) & bits;
654         switch (op) {
655                 case MASK_SET: sb->state |= cpu_to_le32(bits);
656                                 break;
657                 case MASK_UNSET: sb->state &= cpu_to_le32(~bits);
658                                 break;
659                 default: BUG();
660         }
661         kunmap_atomic(sb, KM_USER0);
662         return old;
663 }
664
665 /*
666  * general bitmap file operations
667  */
668
669 /* calculate the index of the page that contains this bit */
670 static inline unsigned long file_page_index(unsigned long chunk)
671 {
672         return CHUNK_BIT_OFFSET(chunk) >> PAGE_BIT_SHIFT;
673 }
674
675 /* calculate the (bit) offset of this bit within a page */
676 static inline unsigned long file_page_offset(unsigned long chunk)
677 {
678         return CHUNK_BIT_OFFSET(chunk) & (PAGE_BITS - 1);
679 }
680
681 /*
682  * return a pointer to the page in the filemap that contains the given bit
683  *
684  * this lookup is complicated by the fact that the bitmap sb might be exactly
685  * 1 page (e.g., x86) or less than 1 page -- so the bitmap might start on page
686  * 0 or page 1
687  */
688 static inline struct page *filemap_get_page(struct bitmap *bitmap,
689                                         unsigned long chunk)
690 {
691         if (file_page_index(chunk) >= bitmap->file_pages) return NULL;
692         return bitmap->filemap[file_page_index(chunk) - file_page_index(0)];
693 }
694
695
696 static void bitmap_file_unmap(struct bitmap *bitmap)
697 {
698         struct page **map, *sb_page;
699         unsigned long *attr;
700         int pages;
701         unsigned long flags;
702
703         spin_lock_irqsave(&bitmap->lock, flags);
704         map = bitmap->filemap;
705         bitmap->filemap = NULL;
706         attr = bitmap->filemap_attr;
707         bitmap->filemap_attr = NULL;
708         pages = bitmap->file_pages;
709         bitmap->file_pages = 0;
710         sb_page = bitmap->sb_page;
711         bitmap->sb_page = NULL;
712         spin_unlock_irqrestore(&bitmap->lock, flags);
713
714         while (pages--)
715                 if (map[pages]->index != 0) /* 0 is sb_page, release it below */
716                         free_buffers(map[pages]);
717         kfree(map);
718         kfree(attr);
719
720         if (sb_page)
721                 free_buffers(sb_page);
722 }
723
724 static void bitmap_file_put(struct bitmap *bitmap)
725 {
726         struct file *file;
727         unsigned long flags;
728
729         spin_lock_irqsave(&bitmap->lock, flags);
730         file = bitmap->file;
731         bitmap->file = NULL;
732         spin_unlock_irqrestore(&bitmap->lock, flags);
733
734         if (file)
735                 wait_event(bitmap->write_wait,
736                            atomic_read(&bitmap->pending_writes)==0);
737         bitmap_file_unmap(bitmap);
738
739         if (file) {
740                 struct inode *inode = file->f_path.dentry->d_inode;
741                 invalidate_mapping_pages(inode->i_mapping, 0, -1);
742                 fput(file);
743         }
744 }
745
746
747 /*
748  * bitmap_file_kick - if an error occurs while manipulating the bitmap file
749  * then it is no longer reliable, so we stop using it and we mark the file
750  * as failed in the superblock
751  */
752 static void bitmap_file_kick(struct bitmap *bitmap)
753 {
754         char *path, *ptr = NULL;
755
756         if (bitmap_mask_state(bitmap, BITMAP_STALE, MASK_SET) == 0) {
757                 bitmap_update_sb(bitmap);
758
759                 if (bitmap->file) {
760                         path = kmalloc(PAGE_SIZE, GFP_KERNEL);
761                         if (path)
762                                 ptr = d_path(&bitmap->file->f_path, path,
763                                              PAGE_SIZE);
764
765
766                         printk(KERN_ALERT
767                               "%s: kicking failed bitmap file %s from array!\n",
768                               bmname(bitmap), IS_ERR(ptr) ? "" : ptr);
769
770                         kfree(path);
771                 } else
772                         printk(KERN_ALERT
773                                "%s: disabling internal bitmap due to errors\n",
774                                bmname(bitmap));
775         }
776
777         bitmap_file_put(bitmap);
778
779         return;
780 }
781
782 enum bitmap_page_attr {
783         BITMAP_PAGE_DIRTY = 0, // there are set bits that need to be synced
784         BITMAP_PAGE_CLEAN = 1, // there are bits that might need to be cleared
785         BITMAP_PAGE_NEEDWRITE=2, // there are cleared bits that need to be synced
786 };
787
788 static inline void set_page_attr(struct bitmap *bitmap, struct page *page,
789                                 enum bitmap_page_attr attr)
790 {
791         __set_bit((page->index<<2) + attr, bitmap->filemap_attr);
792 }
793
794 static inline void clear_page_attr(struct bitmap *bitmap, struct page *page,
795                                 enum bitmap_page_attr attr)
796 {
797         __clear_bit((page->index<<2) + attr, bitmap->filemap_attr);
798 }
799
800 static inline unsigned long test_page_attr(struct bitmap *bitmap, struct page *page,
801                                            enum bitmap_page_attr attr)
802 {
803         return test_bit((page->index<<2) + attr, bitmap->filemap_attr);
804 }
805
806 /*
807  * bitmap_file_set_bit -- called before performing a write to the md device
808  * to set (and eventually sync) a particular bit in the bitmap file
809  *
810  * we set the bit immediately, then we record the page number so that
811  * when an unplug occurs, we can flush the dirty pages out to disk
812  */
813 static void bitmap_file_set_bit(struct bitmap *bitmap, sector_t block)
814 {
815         unsigned long bit;
816         struct page *page;
817         void *kaddr;
818         unsigned long chunk = block >> CHUNK_BLOCK_SHIFT(bitmap);
819
820         if (!bitmap->filemap) {
821                 return;
822         }
823
824         page = filemap_get_page(bitmap, chunk);
825         if (!page) return;
826         bit = file_page_offset(chunk);
827
828         /* set the bit */
829         kaddr = kmap_atomic(page, KM_USER0);
830         if (bitmap->flags & BITMAP_HOSTENDIAN)
831                 set_bit(bit, kaddr);
832         else
833                 ext2_set_bit(bit, kaddr);
834         kunmap_atomic(kaddr, KM_USER0);
835         PRINTK("set file bit %lu page %lu\n", bit, page->index);
836
837         /* record page number so it gets flushed to disk when unplug occurs */
838         set_page_attr(bitmap, page, BITMAP_PAGE_DIRTY);
839
840 }
841
842 /* this gets called when the md device is ready to unplug its underlying
843  * (slave) device queues -- before we let any writes go down, we need to
844  * sync the dirty pages of the bitmap file to disk */
845 void bitmap_unplug(struct bitmap *bitmap)
846 {
847         unsigned long i, flags;
848         int dirty, need_write;
849         struct page *page;
850         int wait = 0;
851
852         if (!bitmap)
853                 return;
854
855         /* look at each page to see if there are any set bits that need to be
856          * flushed out to disk */
857         for (i = 0; i < bitmap->file_pages; i++) {
858                 spin_lock_irqsave(&bitmap->lock, flags);
859                 if (!bitmap->filemap) {
860                         spin_unlock_irqrestore(&bitmap->lock, flags);
861                         return;
862                 }
863                 page = bitmap->filemap[i];
864                 dirty = test_page_attr(bitmap, page, BITMAP_PAGE_DIRTY);
865                 need_write = test_page_attr(bitmap, page, BITMAP_PAGE_NEEDWRITE);
866                 clear_page_attr(bitmap, page, BITMAP_PAGE_DIRTY);
867                 clear_page_attr(bitmap, page, BITMAP_PAGE_NEEDWRITE);
868                 if (dirty)
869                         wait = 1;
870                 spin_unlock_irqrestore(&bitmap->lock, flags);
871
872                 if (dirty | need_write)
873                         write_page(bitmap, page, 0);
874         }
875         if (wait) { /* if any writes were performed, we need to wait on them */
876                 if (bitmap->file)
877                         wait_event(bitmap->write_wait,
878                                    atomic_read(&bitmap->pending_writes)==0);
879                 else
880                         md_super_wait(bitmap->mddev);
881         }
882         if (bitmap->flags & BITMAP_WRITE_ERROR)
883                 bitmap_file_kick(bitmap);
884 }
885
886 static void bitmap_set_memory_bits(struct bitmap *bitmap, sector_t offset, int needed);
887 /* * bitmap_init_from_disk -- called at bitmap_create time to initialize
888  * the in-memory bitmap from the on-disk bitmap -- also, sets up the
889  * memory mapping of the bitmap file
890  * Special cases:
891  *   if there's no bitmap file, or if the bitmap file had been
892  *   previously kicked from the array, we mark all the bits as
893  *   1's in order to cause a full resync.
894  *
895  * We ignore all bits for sectors that end earlier than 'start'.
896  * This is used when reading an out-of-date bitmap...
897  */
898 static int bitmap_init_from_disk(struct bitmap *bitmap, sector_t start)
899 {
900         unsigned long i, chunks, index, oldindex, bit;
901         struct page *page = NULL, *oldpage = NULL;
902         unsigned long num_pages, bit_cnt = 0;
903         struct file *file;
904         unsigned long bytes, offset;
905         int outofdate;
906         int ret = -ENOSPC;
907         void *paddr;
908
909         chunks = bitmap->chunks;
910         file = bitmap->file;
911
912         BUG_ON(!file && !bitmap->mddev->bitmap_info.offset);
913
914 #ifdef INJECT_FAULTS_3
915         outofdate = 1;
916 #else
917         outofdate = bitmap->flags & BITMAP_STALE;
918 #endif
919         if (outofdate)
920                 printk(KERN_INFO "%s: bitmap file is out of date, doing full "
921                         "recovery\n", bmname(bitmap));
922
923         bytes = (chunks + 7) / 8;
924
925         num_pages = (bytes + sizeof(bitmap_super_t) + PAGE_SIZE - 1) / PAGE_SIZE;
926
927         if (file && i_size_read(file->f_mapping->host) < bytes + sizeof(bitmap_super_t)) {
928                 printk(KERN_INFO "%s: bitmap file too short %lu < %lu\n",
929                         bmname(bitmap),
930                         (unsigned long) i_size_read(file->f_mapping->host),
931                         bytes + sizeof(bitmap_super_t));
932                 goto err;
933         }
934
935         ret = -ENOMEM;
936
937         bitmap->filemap = kmalloc(sizeof(struct page *) * num_pages, GFP_KERNEL);
938         if (!bitmap->filemap)
939                 goto err;
940
941         /* We need 4 bits per page, rounded up to a multiple of sizeof(unsigned long) */
942         bitmap->filemap_attr = kzalloc(
943                 roundup( DIV_ROUND_UP(num_pages*4, 8), sizeof(unsigned long)),
944                 GFP_KERNEL);
945         if (!bitmap->filemap_attr)
946                 goto err;
947
948         oldindex = ~0L;
949
950         for (i = 0; i < chunks; i++) {
951                 int b;
952                 index = file_page_index(i);
953                 bit = file_page_offset(i);
954                 if (index != oldindex) { /* this is a new page, read it in */
955                         int count;
956                         /* unmap the old page, we're done with it */
957                         if (index == num_pages-1)
958                                 count = bytes + sizeof(bitmap_super_t)
959                                         - index * PAGE_SIZE;
960                         else
961                                 count = PAGE_SIZE;
962                         if (index == 0) {
963                                 /*
964                                  * if we're here then the superblock page
965                                  * contains some bits (PAGE_SIZE != sizeof sb)
966                                  * we've already read it in, so just use it
967                                  */
968                                 page = bitmap->sb_page;
969                                 offset = sizeof(bitmap_super_t);
970                                 if (!file)
971                                         read_sb_page(bitmap->mddev,
972                                                      bitmap->mddev->bitmap_info.offset,
973                                                      page,
974                                                      index, count);
975                         } else if (file) {
976                                 page = read_page(file, index, bitmap, count);
977                                 offset = 0;
978                         } else {
979                                 page = read_sb_page(bitmap->mddev,
980                                                     bitmap->mddev->bitmap_info.offset,
981                                                     NULL,
982                                                     index, count);
983                                 offset = 0;
984                         }
985                         if (IS_ERR(page)) { /* read error */
986                                 ret = PTR_ERR(page);
987                                 goto err;
988                         }
989
990                         oldindex = index;
991                         oldpage = page;
992
993                         bitmap->filemap[bitmap->file_pages++] = page;
994                         bitmap->last_page_size = count;
995
996                         if (outofdate) {
997                                 /*
998                                  * if bitmap is out of date, dirty the
999                                  * whole page and write it out
1000                                  */
1001                                 paddr = kmap_atomic(page, KM_USER0);
1002                                 memset(paddr + offset, 0xff,
1003                                        PAGE_SIZE - offset);
1004                                 kunmap_atomic(paddr, KM_USER0);
1005                                 write_page(bitmap, page, 1);
1006
1007                                 ret = -EIO;
1008                                 if (bitmap->flags & BITMAP_WRITE_ERROR)
1009                                         goto err;
1010                         }
1011                 }
1012                 paddr = kmap_atomic(page, KM_USER0);
1013                 if (bitmap->flags & BITMAP_HOSTENDIAN)
1014                         b = test_bit(bit, paddr);
1015                 else
1016                         b = ext2_test_bit(bit, paddr);
1017                 kunmap_atomic(paddr, KM_USER0);
1018                 if (b) {
1019                         /* if the disk bit is set, set the memory bit */
1020                         int needed = ((sector_t)(i+1) << (CHUNK_BLOCK_SHIFT(bitmap))
1021                                       >= start);
1022                         bitmap_set_memory_bits(bitmap,
1023                                                (sector_t)i << CHUNK_BLOCK_SHIFT(bitmap),
1024                                                needed);
1025                         bit_cnt++;
1026                         set_page_attr(bitmap, page, BITMAP_PAGE_CLEAN);
1027                 }
1028         }
1029
1030         /* everything went OK */
1031         ret = 0;
1032         bitmap_mask_state(bitmap, BITMAP_STALE, MASK_UNSET);
1033
1034         if (bit_cnt) { /* Kick recovery if any bits were set */
1035                 set_bit(MD_RECOVERY_NEEDED, &bitmap->mddev->recovery);
1036                 md_wakeup_thread(bitmap->mddev->thread);
1037         }
1038
1039         printk(KERN_INFO "%s: bitmap initialized from disk: "
1040                 "read %lu/%lu pages, set %lu bits\n",
1041                 bmname(bitmap), bitmap->file_pages, num_pages, bit_cnt);
1042
1043         return 0;
1044
1045  err:
1046         printk(KERN_INFO "%s: bitmap initialisation failed: %d\n",
1047                bmname(bitmap), ret);
1048         return ret;
1049 }
1050
1051 void bitmap_write_all(struct bitmap *bitmap)
1052 {
1053         /* We don't actually write all bitmap blocks here,
1054          * just flag them as needing to be written
1055          */
1056         int i;
1057
1058         for (i=0; i < bitmap->file_pages; i++)
1059                 set_page_attr(bitmap, bitmap->filemap[i],
1060                               BITMAP_PAGE_NEEDWRITE);
1061 }
1062
1063
1064 static void bitmap_count_page(struct bitmap *bitmap, sector_t offset, int inc)
1065 {
1066         sector_t chunk = offset >> CHUNK_BLOCK_SHIFT(bitmap);
1067         unsigned long page = chunk >> PAGE_COUNTER_SHIFT;
1068         bitmap->bp[page].count += inc;
1069 /*
1070         if (page == 0) printk("count page 0, offset %llu: %d gives %d\n",
1071                               (unsigned long long)offset, inc, bitmap->bp[page].count);
1072 */
1073         bitmap_checkfree(bitmap, page);
1074 }
1075 static bitmap_counter_t *bitmap_get_counter(struct bitmap *bitmap,
1076                                             sector_t offset, int *blocks,
1077                                             int create);
1078
1079 /*
1080  * bitmap daemon -- periodically wakes up to clean bits and flush pages
1081  *                      out to disk
1082  */
1083
1084 void bitmap_daemon_work(mddev_t *mddev)
1085 {
1086         struct bitmap *bitmap;
1087         unsigned long j;
1088         unsigned long flags;
1089         struct page *page = NULL, *lastpage = NULL;
1090         int blocks;
1091         void *paddr;
1092
1093         /* Use a mutex to guard daemon_work against
1094          * bitmap_destroy.
1095          */
1096         mutex_lock(&mddev->bitmap_info.mutex);
1097         bitmap = mddev->bitmap;
1098         if (bitmap == NULL) {
1099                 mutex_unlock(&mddev->bitmap_info.mutex);
1100                 return;
1101         }
1102         if (time_before(jiffies, bitmap->daemon_lastrun
1103                         + bitmap->mddev->bitmap_info.daemon_sleep))
1104                 goto done;
1105
1106         bitmap->daemon_lastrun = jiffies;
1107         if (bitmap->allclean) {
1108                 bitmap->mddev->thread->timeout = MAX_SCHEDULE_TIMEOUT;
1109                 goto done;
1110         }
1111         bitmap->allclean = 1;
1112
1113         spin_lock_irqsave(&bitmap->lock, flags);
1114         for (j = 0; j < bitmap->chunks; j++) {
1115                 bitmap_counter_t *bmc;
1116                 if (!bitmap->filemap)
1117                         /* error or shutdown */
1118                         break;
1119
1120                 page = filemap_get_page(bitmap, j);
1121
1122                 if (page != lastpage) {
1123                         /* skip this page unless it's marked as needing cleaning */
1124                         if (!test_page_attr(bitmap, page, BITMAP_PAGE_CLEAN)) {
1125                                 int need_write = test_page_attr(bitmap, page,
1126                                                                 BITMAP_PAGE_NEEDWRITE);
1127                                 if (need_write)
1128                                         clear_page_attr(bitmap, page, BITMAP_PAGE_NEEDWRITE);
1129
1130                                 spin_unlock_irqrestore(&bitmap->lock, flags);
1131                                 if (need_write) {
1132                                         write_page(bitmap, page, 0);
1133                                         bitmap->allclean = 0;
1134                                 }
1135                                 spin_lock_irqsave(&bitmap->lock, flags);
1136                                 j |= (PAGE_BITS - 1);
1137                                 continue;
1138                         }
1139
1140                         /* grab the new page, sync and release the old */
1141                         if (lastpage != NULL) {
1142                                 if (test_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE)) {
1143                                         clear_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE);
1144                                         spin_unlock_irqrestore(&bitmap->lock, flags);
1145                                         write_page(bitmap, lastpage, 0);
1146                                 } else {
1147                                         set_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE);
1148                                         spin_unlock_irqrestore(&bitmap->lock, flags);
1149                                 }
1150                         } else
1151                                 spin_unlock_irqrestore(&bitmap->lock, flags);
1152                         lastpage = page;
1153
1154                         /* We are possibly going to clear some bits, so make
1155                          * sure that events_cleared is up-to-date.
1156                          */
1157                         if (bitmap->need_sync) {
1158                                 bitmap_super_t *sb;
1159                                 bitmap->need_sync = 0;
1160                                 sb = kmap_atomic(bitmap->sb_page, KM_USER0);
1161                                 sb->events_cleared =
1162                                         cpu_to_le64(bitmap->events_cleared);
1163                                 kunmap_atomic(sb, KM_USER0);
1164                                 write_page(bitmap, bitmap->sb_page, 1);
1165                         }
1166                         spin_lock_irqsave(&bitmap->lock, flags);
1167                         clear_page_attr(bitmap, page, BITMAP_PAGE_CLEAN);
1168                 }
1169                 bmc = bitmap_get_counter(bitmap,
1170                                          (sector_t)j << CHUNK_BLOCK_SHIFT(bitmap),
1171                                          &blocks, 0);
1172                 if (bmc) {
1173 /*
1174   if (j < 100) printk("bitmap: j=%lu, *bmc = 0x%x\n", j, *bmc);
1175 */
1176                         if (*bmc)
1177                                 bitmap->allclean = 0;
1178
1179                         if (*bmc == 2) {
1180                                 *bmc=1; /* maybe clear the bit next time */
1181                                 set_page_attr(bitmap, page, BITMAP_PAGE_CLEAN);
1182                         } else if (*bmc == 1) {
1183                                 /* we can clear the bit */
1184                                 *bmc = 0;
1185                                 bitmap_count_page(bitmap,
1186                                                   (sector_t)j << CHUNK_BLOCK_SHIFT(bitmap),
1187                                                   -1);
1188
1189                                 /* clear the bit */
1190                                 paddr = kmap_atomic(page, KM_USER0);
1191                                 if (bitmap->flags & BITMAP_HOSTENDIAN)
1192                                         clear_bit(file_page_offset(j), paddr);
1193                                 else
1194                                         ext2_clear_bit(file_page_offset(j), paddr);
1195                                 kunmap_atomic(paddr, KM_USER0);
1196                         }
1197                 } else
1198                         j |= PAGE_COUNTER_MASK;
1199         }
1200         spin_unlock_irqrestore(&bitmap->lock, flags);
1201
1202         /* now sync the final page */
1203         if (lastpage != NULL) {
1204                 spin_lock_irqsave(&bitmap->lock, flags);
1205                 if (test_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE)) {
1206                         clear_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE);
1207                         spin_unlock_irqrestore(&bitmap->lock, flags);
1208                         write_page(bitmap, lastpage, 0);
1209                 } else {
1210                         set_page_attr(bitmap, lastpage, BITMAP_PAGE_NEEDWRITE);
1211                         spin_unlock_irqrestore(&bitmap->lock, flags);
1212                 }
1213         }
1214
1215  done:
1216         if (bitmap->allclean == 0)
1217                 bitmap->mddev->thread->timeout = 
1218                         bitmap->mddev->bitmap_info.daemon_sleep;
1219         mutex_unlock(&mddev->bitmap_info.mutex);
1220 }
1221
1222 static bitmap_counter_t *bitmap_get_counter(struct bitmap *bitmap,
1223                                             sector_t offset, int *blocks,
1224                                             int create)
1225 __releases(bitmap->lock)
1226 __acquires(bitmap->lock)
1227 {
1228         /* If 'create', we might release the lock and reclaim it.
1229          * The lock must have been taken with interrupts enabled.
1230          * If !create, we don't release the lock.
1231          */
1232         sector_t chunk = offset >> CHUNK_BLOCK_SHIFT(bitmap);
1233         unsigned long page = chunk >> PAGE_COUNTER_SHIFT;
1234         unsigned long pageoff = (chunk & PAGE_COUNTER_MASK) << COUNTER_BYTE_SHIFT;
1235         sector_t csize;
1236
1237         if (bitmap_checkpage(bitmap, page, create) < 0) {
1238                 csize = ((sector_t)1) << (CHUNK_BLOCK_SHIFT(bitmap));
1239                 *blocks = csize - (offset & (csize- 1));
1240                 return NULL;
1241         }
1242         /* now locked ... */
1243
1244         if (bitmap->bp[page].hijacked) { /* hijacked pointer */
1245                 /* should we use the first or second counter field
1246                  * of the hijacked pointer? */
1247                 int hi = (pageoff > PAGE_COUNTER_MASK);
1248                 csize = ((sector_t)1) << (CHUNK_BLOCK_SHIFT(bitmap) +
1249                                           PAGE_COUNTER_SHIFT - 1);
1250                 *blocks = csize - (offset & (csize- 1));
1251                 return  &((bitmap_counter_t *)
1252                           &bitmap->bp[page].map)[hi];
1253         } else { /* page is allocated */
1254                 csize = ((sector_t)1) << (CHUNK_BLOCK_SHIFT(bitmap));
1255                 *blocks = csize - (offset & (csize- 1));
1256                 return (bitmap_counter_t *)
1257                         &(bitmap->bp[page].map[pageoff]);
1258         }
1259 }
1260
1261 int bitmap_startwrite(struct bitmap *bitmap, sector_t offset, unsigned long sectors, int behind)
1262 {
1263         if (!bitmap) return 0;
1264
1265         if (behind) {
1266                 atomic_inc(&bitmap->behind_writes);
1267                 PRINTK(KERN_DEBUG "inc write-behind count %d/%d\n",
1268                   atomic_read(&bitmap->behind_writes), bitmap->max_write_behind);
1269         }
1270
1271         while (sectors) {
1272                 int blocks;
1273                 bitmap_counter_t *bmc;
1274
1275                 spin_lock_irq(&bitmap->lock);
1276                 bmc = bitmap_get_counter(bitmap, offset, &blocks, 1);
1277                 if (!bmc) {
1278                         spin_unlock_irq(&bitmap->lock);
1279                         return 0;
1280                 }
1281
1282                 if (unlikely((*bmc & COUNTER_MAX) == COUNTER_MAX)) {
1283                         DEFINE_WAIT(__wait);
1284                         /* note that it is safe to do the prepare_to_wait
1285                          * after the test as long as we do it before dropping
1286                          * the spinlock.
1287                          */
1288                         prepare_to_wait(&bitmap->overflow_wait, &__wait,
1289                                         TASK_UNINTERRUPTIBLE);
1290                         spin_unlock_irq(&bitmap->lock);
1291                         blk_unplug(bitmap->mddev->queue);
1292                         schedule();
1293                         finish_wait(&bitmap->overflow_wait, &__wait);
1294                         continue;
1295                 }
1296
1297                 switch(*bmc) {
1298                 case 0:
1299                         bitmap_file_set_bit(bitmap, offset);
1300                         bitmap_count_page(bitmap,offset, 1);
1301                         blk_plug_device_unlocked(bitmap->mddev->queue);
1302                         /* fall through */
1303                 case 1:
1304                         *bmc = 2;
1305                 }
1306
1307                 (*bmc)++;
1308
1309                 spin_unlock_irq(&bitmap->lock);
1310
1311                 offset += blocks;
1312                 if (sectors > blocks)
1313                         sectors -= blocks;
1314                 else sectors = 0;
1315         }
1316         bitmap->allclean = 0;
1317         return 0;
1318 }
1319
1320 void bitmap_endwrite(struct bitmap *bitmap, sector_t offset, unsigned long sectors,
1321                      int success, int behind)
1322 {
1323         if (!bitmap) return;
1324         if (behind) {
1325                 atomic_dec(&bitmap->behind_writes);
1326                 PRINTK(KERN_DEBUG "dec write-behind count %d/%d\n",
1327                   atomic_read(&bitmap->behind_writes), bitmap->max_write_behind);
1328         }
1329         if (bitmap->mddev->degraded)
1330                 /* Never clear bits or update events_cleared when degraded */
1331                 success = 0;
1332
1333         while (sectors) {
1334                 int blocks;
1335                 unsigned long flags;
1336                 bitmap_counter_t *bmc;
1337
1338                 spin_lock_irqsave(&bitmap->lock, flags);
1339                 bmc = bitmap_get_counter(bitmap, offset, &blocks, 0);
1340                 if (!bmc) {
1341                         spin_unlock_irqrestore(&bitmap->lock, flags);
1342                         return;
1343                 }
1344
1345                 if (success &&
1346                     bitmap->events_cleared < bitmap->mddev->events) {
1347                         bitmap->events_cleared = bitmap->mddev->events;
1348                         bitmap->need_sync = 1;
1349                 }
1350
1351                 if (!success && ! (*bmc & NEEDED_MASK))
1352                         *bmc |= NEEDED_MASK;
1353
1354                 if ((*bmc & COUNTER_MAX) == COUNTER_MAX)
1355                         wake_up(&bitmap->overflow_wait);
1356
1357                 (*bmc)--;
1358                 if (*bmc <= 2) {
1359                         set_page_attr(bitmap,
1360                                       filemap_get_page(bitmap, offset >> CHUNK_BLOCK_SHIFT(bitmap)),
1361                                       BITMAP_PAGE_CLEAN);
1362                 }
1363                 spin_unlock_irqrestore(&bitmap->lock, flags);
1364                 offset += blocks;
1365                 if (sectors > blocks)
1366                         sectors -= blocks;
1367                 else sectors = 0;
1368         }
1369 }
1370
1371 static int __bitmap_start_sync(struct bitmap *bitmap, sector_t offset, int *blocks,
1372                                int degraded)
1373 {
1374         bitmap_counter_t *bmc;
1375         int rv;
1376         if (bitmap == NULL) {/* FIXME or bitmap set as 'failed' */
1377                 *blocks = 1024;
1378                 return 1; /* always resync if no bitmap */
1379         }
1380         spin_lock_irq(&bitmap->lock);
1381         bmc = bitmap_get_counter(bitmap, offset, blocks, 0);
1382         rv = 0;
1383         if (bmc) {
1384                 /* locked */
1385                 if (RESYNC(*bmc))
1386                         rv = 1;
1387                 else if (NEEDED(*bmc)) {
1388                         rv = 1;
1389                         if (!degraded) { /* don't set/clear bits if degraded */
1390                                 *bmc |= RESYNC_MASK;
1391                                 *bmc &= ~NEEDED_MASK;
1392                         }
1393                 }
1394         }
1395         spin_unlock_irq(&bitmap->lock);
1396         bitmap->allclean = 0;
1397         return rv;
1398 }
1399
1400 int bitmap_start_sync(struct bitmap *bitmap, sector_t offset, int *blocks,
1401                       int degraded)
1402 {
1403         /* bitmap_start_sync must always report on multiples of whole
1404          * pages, otherwise resync (which is very PAGE_SIZE based) will
1405          * get confused.
1406          * So call __bitmap_start_sync repeatedly (if needed) until
1407          * At least PAGE_SIZE>>9 blocks are covered.
1408          * Return the 'or' of the result.
1409          */
1410         int rv = 0;
1411         int blocks1;
1412
1413         *blocks = 0;
1414         while (*blocks < (PAGE_SIZE>>9)) {
1415                 rv |= __bitmap_start_sync(bitmap, offset,
1416                                           &blocks1, degraded);
1417                 offset += blocks1;
1418                 *blocks += blocks1;
1419         }
1420         return rv;
1421 }
1422
1423 void bitmap_end_sync(struct bitmap *bitmap, sector_t offset, int *blocks, int aborted)
1424 {
1425         bitmap_counter_t *bmc;
1426         unsigned long flags;
1427 /*
1428         if (offset == 0) printk("bitmap_end_sync 0 (%d)\n", aborted);
1429 */      if (bitmap == NULL) {
1430                 *blocks = 1024;
1431                 return;
1432         }
1433         spin_lock_irqsave(&bitmap->lock, flags);
1434         bmc = bitmap_get_counter(bitmap, offset, blocks, 0);
1435         if (bmc == NULL)
1436                 goto unlock;
1437         /* locked */
1438 /*
1439         if (offset == 0) printk("bitmap_end sync found 0x%x, blocks %d\n", *bmc, *blocks);
1440 */
1441         if (RESYNC(*bmc)) {
1442                 *bmc &= ~RESYNC_MASK;
1443
1444                 if (!NEEDED(*bmc) && aborted)
1445                         *bmc |= NEEDED_MASK;
1446                 else {
1447                         if (*bmc <= 2) {
1448                                 set_page_attr(bitmap,
1449                                               filemap_get_page(bitmap, offset >> CHUNK_BLOCK_SHIFT(bitmap)),
1450                                               BITMAP_PAGE_CLEAN);
1451                         }
1452                 }
1453         }
1454  unlock:
1455         spin_unlock_irqrestore(&bitmap->lock, flags);
1456         bitmap->allclean = 0;
1457 }
1458
1459 void bitmap_close_sync(struct bitmap *bitmap)
1460 {
1461         /* Sync has finished, and any bitmap chunks that weren't synced
1462          * properly have been aborted.  It remains to us to clear the
1463          * RESYNC bit wherever it is still on
1464          */
1465         sector_t sector = 0;
1466         int blocks;
1467         if (!bitmap)
1468                 return;
1469         while (sector < bitmap->mddev->resync_max_sectors) {
1470                 bitmap_end_sync(bitmap, sector, &blocks, 0);
1471                 sector += blocks;
1472         }
1473 }
1474
1475 void bitmap_cond_end_sync(struct bitmap *bitmap, sector_t sector)
1476 {
1477         sector_t s = 0;
1478         int blocks;
1479
1480         if (!bitmap)
1481                 return;
1482         if (sector == 0) {
1483                 bitmap->last_end_sync = jiffies;
1484                 return;
1485         }
1486         if (time_before(jiffies, (bitmap->last_end_sync
1487                                   + bitmap->mddev->bitmap_info.daemon_sleep)))
1488                 return;
1489         wait_event(bitmap->mddev->recovery_wait,
1490                    atomic_read(&bitmap->mddev->recovery_active) == 0);
1491
1492         bitmap->mddev->curr_resync_completed = bitmap->mddev->curr_resync;
1493         set_bit(MD_CHANGE_CLEAN, &bitmap->mddev->flags);
1494         sector &= ~((1ULL << CHUNK_BLOCK_SHIFT(bitmap)) - 1);
1495         s = 0;
1496         while (s < sector && s < bitmap->mddev->resync_max_sectors) {
1497                 bitmap_end_sync(bitmap, s, &blocks, 0);
1498                 s += blocks;
1499         }
1500         bitmap->last_end_sync = jiffies;
1501         sysfs_notify(&bitmap->mddev->kobj, NULL, "sync_completed");
1502 }
1503
1504 static void bitmap_set_memory_bits(struct bitmap *bitmap, sector_t offset, int needed)
1505 {
1506         /* For each chunk covered by any of these sectors, set the
1507          * counter to 1 and set resync_needed.  They should all
1508          * be 0 at this point
1509          */
1510
1511         int secs;
1512         bitmap_counter_t *bmc;
1513         spin_lock_irq(&bitmap->lock);
1514         bmc = bitmap_get_counter(bitmap, offset, &secs, 1);
1515         if (!bmc) {
1516                 spin_unlock_irq(&bitmap->lock);
1517                 return;
1518         }
1519         if (! *bmc) {
1520                 struct page *page;
1521                 *bmc = 1 | (needed?NEEDED_MASK:0);
1522                 bitmap_count_page(bitmap, offset, 1);
1523                 page = filemap_get_page(bitmap, offset >> CHUNK_BLOCK_SHIFT(bitmap));
1524                 set_page_attr(bitmap, page, BITMAP_PAGE_CLEAN);
1525         }
1526         spin_unlock_irq(&bitmap->lock);
1527         bitmap->allclean = 0;
1528 }
1529
1530 /* dirty the memory and file bits for bitmap chunks "s" to "e" */
1531 void bitmap_dirty_bits(struct bitmap *bitmap, unsigned long s, unsigned long e)
1532 {
1533         unsigned long chunk;
1534
1535         for (chunk = s; chunk <= e; chunk++) {
1536                 sector_t sec = (sector_t)chunk << CHUNK_BLOCK_SHIFT(bitmap);
1537                 bitmap_set_memory_bits(bitmap, sec, 1);
1538                 bitmap_file_set_bit(bitmap, sec);
1539         }
1540 }
1541
1542 /*
1543  * flush out any pending updates
1544  */
1545 void bitmap_flush(mddev_t *mddev)
1546 {
1547         struct bitmap *bitmap = mddev->bitmap;
1548         long sleep;
1549
1550         if (!bitmap) /* there was no bitmap */
1551                 return;
1552
1553         /* run the daemon_work three time to ensure everything is flushed
1554          * that can be
1555          */
1556         sleep = mddev->bitmap_info.daemon_sleep * 2;
1557         bitmap->daemon_lastrun -= sleep;
1558         bitmap_daemon_work(mddev);
1559         bitmap->daemon_lastrun -= sleep;
1560         bitmap_daemon_work(mddev);
1561         bitmap->daemon_lastrun -= sleep;
1562         bitmap_daemon_work(mddev);
1563         bitmap_update_sb(bitmap);
1564 }
1565
1566 /*
1567  * free memory that was allocated
1568  */
1569 static void bitmap_free(struct bitmap *bitmap)
1570 {
1571         unsigned long k, pages;
1572         struct bitmap_page *bp;
1573
1574         if (!bitmap) /* there was no bitmap */
1575                 return;
1576
1577         /* release the bitmap file and kill the daemon */
1578         bitmap_file_put(bitmap);
1579
1580         bp = bitmap->bp;
1581         pages = bitmap->pages;
1582
1583         /* free all allocated memory */
1584
1585         if (bp) /* deallocate the page memory */
1586                 for (k = 0; k < pages; k++)
1587                         if (bp[k].map && !bp[k].hijacked)
1588                                 kfree(bp[k].map);
1589         kfree(bp);
1590         kfree(bitmap);
1591 }
1592
1593 void bitmap_destroy(mddev_t *mddev)
1594 {
1595         struct bitmap *bitmap = mddev->bitmap;
1596
1597         if (!bitmap) /* there was no bitmap */
1598                 return;
1599
1600         mutex_lock(&mddev->bitmap_info.mutex);
1601         mddev->bitmap = NULL; /* disconnect from the md device */
1602         mutex_unlock(&mddev->bitmap_info.mutex);
1603         if (mddev->thread)
1604                 mddev->thread->timeout = MAX_SCHEDULE_TIMEOUT;
1605
1606         bitmap_free(bitmap);
1607 }
1608
1609 /*
1610  * initialize the bitmap structure
1611  * if this returns an error, bitmap_destroy must be called to do clean up
1612  */
1613 int bitmap_create(mddev_t *mddev)
1614 {
1615         struct bitmap *bitmap;
1616         sector_t blocks = mddev->resync_max_sectors;
1617         unsigned long chunks;
1618         unsigned long pages;
1619         struct file *file = mddev->bitmap_info.file;
1620         int err;
1621         sector_t start;
1622
1623         BUILD_BUG_ON(sizeof(bitmap_super_t) != 256);
1624
1625         if (!file && !mddev->bitmap_info.offset) /* bitmap disabled, nothing to do */
1626                 return 0;
1627
1628         BUG_ON(file && mddev->bitmap_info.offset);
1629
1630         bitmap = kzalloc(sizeof(*bitmap), GFP_KERNEL);
1631         if (!bitmap)
1632                 return -ENOMEM;
1633
1634         spin_lock_init(&bitmap->lock);
1635         atomic_set(&bitmap->pending_writes, 0);
1636         init_waitqueue_head(&bitmap->write_wait);
1637         init_waitqueue_head(&bitmap->overflow_wait);
1638
1639         bitmap->mddev = mddev;
1640
1641         bitmap->file = file;
1642         if (file) {
1643                 get_file(file);
1644                 /* As future accesses to this file will use bmap,
1645                  * and bypass the page cache, we must sync the file
1646                  * first.
1647                  */
1648                 vfs_fsync(file, file->f_dentry, 1);
1649         }
1650         /* read superblock from bitmap file (this sets mddev->bitmap_info.chunksize) */
1651         err = bitmap_read_sb(bitmap);
1652         if (err)
1653                 goto error;
1654
1655         bitmap->chunkshift = ffz(~mddev->bitmap_info.chunksize);
1656
1657         /* now that chunksize and chunkshift are set, we can use these macros */
1658         chunks = (blocks + CHUNK_BLOCK_RATIO(bitmap) - 1) >>
1659                         CHUNK_BLOCK_SHIFT(bitmap);
1660         pages = (chunks + PAGE_COUNTER_RATIO - 1) / PAGE_COUNTER_RATIO;
1661
1662         BUG_ON(!pages);
1663
1664         bitmap->chunks = chunks;
1665         bitmap->pages = pages;
1666         bitmap->missing_pages = pages;
1667         bitmap->counter_bits = COUNTER_BITS;
1668
1669         bitmap->syncchunk = ~0UL;
1670
1671 #ifdef INJECT_FATAL_FAULT_1
1672         bitmap->bp = NULL;
1673 #else
1674         bitmap->bp = kzalloc(pages * sizeof(*bitmap->bp), GFP_KERNEL);
1675 #endif
1676         err = -ENOMEM;
1677         if (!bitmap->bp)
1678                 goto error;
1679
1680         /* now that we have some pages available, initialize the in-memory
1681          * bitmap from the on-disk bitmap */
1682         start = 0;
1683         if (mddev->degraded == 0
1684             || bitmap->events_cleared == mddev->events)
1685                 /* no need to keep dirty bits to optimise a re-add of a missing device */
1686                 start = mddev->recovery_cp;
1687         err = bitmap_init_from_disk(bitmap, start);
1688
1689         if (err)
1690                 goto error;
1691
1692         printk(KERN_INFO "created bitmap (%lu pages) for device %s\n",
1693                 pages, bmname(bitmap));
1694
1695         mddev->bitmap = bitmap;
1696
1697         mddev->thread->timeout = mddev->bitmap_info.daemon_sleep;
1698         md_wakeup_thread(mddev->thread);
1699
1700         bitmap_update_sb(bitmap);
1701
1702         return (bitmap->flags & BITMAP_WRITE_ERROR) ? -EIO : 0;
1703
1704  error:
1705         bitmap_free(bitmap);
1706         return err;
1707 }
1708
1709 /* the bitmap API -- for raid personalities */
1710 EXPORT_SYMBOL(bitmap_startwrite);
1711 EXPORT_SYMBOL(bitmap_endwrite);
1712 EXPORT_SYMBOL(bitmap_start_sync);
1713 EXPORT_SYMBOL(bitmap_end_sync);
1714 EXPORT_SYMBOL(bitmap_unplug);
1715 EXPORT_SYMBOL(bitmap_close_sync);
1716 EXPORT_SYMBOL(bitmap_cond_end_sync);