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