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