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