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