md: Don't try to set an array to 'read-auto' if it is already in that state.
[linux-2.6] / drivers / md / md.c
1 /*
2    md.c : Multiple Devices driver for Linux
3           Copyright (C) 1998, 1999, 2000 Ingo Molnar
4
5      completely rewritten, based on the MD driver code from Marc Zyngier
6
7    Changes:
8
9    - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
10    - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
11    - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
12    - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
13    - kmod support by: Cyrus Durgin
14    - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
15    - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
16
17    - lots of fixes and improvements to the RAID1/RAID5 and generic
18      RAID code (such as request based resynchronization):
19
20      Neil Brown <neilb@cse.unsw.edu.au>.
21
22    - persistent bitmap code
23      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
24
25    This program is free software; you can redistribute it and/or modify
26    it under the terms of the GNU General Public License as published by
27    the Free Software Foundation; either version 2, or (at your option)
28    any later version.
29
30    You should have received a copy of the GNU General Public License
31    (for example /usr/src/linux/COPYING); if not, write to the Free
32    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 */
34
35 #include <linux/module.h>
36 #include <linux/kernel.h>
37 #include <linux/kthread.h>
38 #include <linux/linkage.h>
39 #include <linux/raid/md.h>
40 #include <linux/raid/bitmap.h>
41 #include <linux/sysctl.h>
42 #include <linux/buffer_head.h> /* for invalidate_bdev */
43 #include <linux/poll.h>
44 #include <linux/mutex.h>
45 #include <linux/ctype.h>
46 #include <linux/freezer.h>
47
48 #include <linux/init.h>
49
50 #include <linux/file.h>
51
52 #ifdef CONFIG_KMOD
53 #include <linux/kmod.h>
54 #endif
55
56 #include <asm/unaligned.h>
57
58 #define MAJOR_NR MD_MAJOR
59 #define MD_DRIVER
60
61 /* 63 partitions with the alternate major number (mdp) */
62 #define MdpMinorShift 6
63
64 #define DEBUG 0
65 #define dprintk(x...) ((void)(DEBUG && printk(x)))
66
67
68 #ifndef MODULE
69 static void autostart_arrays (int part);
70 #endif
71
72 static LIST_HEAD(pers_list);
73 static DEFINE_SPINLOCK(pers_lock);
74
75 static void md_print_devices(void);
76
77 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
78
79 #define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
80
81 /*
82  * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
83  * is 1000 KB/sec, so the extra system load does not show up that much.
84  * Increase it if you want to have more _guaranteed_ speed. Note that
85  * the RAID driver will use the maximum available bandwidth if the IO
86  * subsystem is idle. There is also an 'absolute maximum' reconstruction
87  * speed limit - in case reconstruction slows down your system despite
88  * idle IO detection.
89  *
90  * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
91  * or /sys/block/mdX/md/sync_speed_{min,max}
92  */
93
94 static int sysctl_speed_limit_min = 1000;
95 static int sysctl_speed_limit_max = 200000;
96 static inline int speed_min(mddev_t *mddev)
97 {
98         return mddev->sync_speed_min ?
99                 mddev->sync_speed_min : sysctl_speed_limit_min;
100 }
101
102 static inline int speed_max(mddev_t *mddev)
103 {
104         return mddev->sync_speed_max ?
105                 mddev->sync_speed_max : sysctl_speed_limit_max;
106 }
107
108 static struct ctl_table_header *raid_table_header;
109
110 static ctl_table raid_table[] = {
111         {
112                 .ctl_name       = DEV_RAID_SPEED_LIMIT_MIN,
113                 .procname       = "speed_limit_min",
114                 .data           = &sysctl_speed_limit_min,
115                 .maxlen         = sizeof(int),
116                 .mode           = S_IRUGO|S_IWUSR,
117                 .proc_handler   = &proc_dointvec,
118         },
119         {
120                 .ctl_name       = DEV_RAID_SPEED_LIMIT_MAX,
121                 .procname       = "speed_limit_max",
122                 .data           = &sysctl_speed_limit_max,
123                 .maxlen         = sizeof(int),
124                 .mode           = S_IRUGO|S_IWUSR,
125                 .proc_handler   = &proc_dointvec,
126         },
127         { .ctl_name = 0 }
128 };
129
130 static ctl_table raid_dir_table[] = {
131         {
132                 .ctl_name       = DEV_RAID,
133                 .procname       = "raid",
134                 .maxlen         = 0,
135                 .mode           = S_IRUGO|S_IXUGO,
136                 .child          = raid_table,
137         },
138         { .ctl_name = 0 }
139 };
140
141 static ctl_table raid_root_table[] = {
142         {
143                 .ctl_name       = CTL_DEV,
144                 .procname       = "dev",
145                 .maxlen         = 0,
146                 .mode           = 0555,
147                 .child          = raid_dir_table,
148         },
149         { .ctl_name = 0 }
150 };
151
152 static struct block_device_operations md_fops;
153
154 static int start_readonly;
155
156 /*
157  * We have a system wide 'event count' that is incremented
158  * on any 'interesting' event, and readers of /proc/mdstat
159  * can use 'poll' or 'select' to find out when the event
160  * count increases.
161  *
162  * Events are:
163  *  start array, stop array, error, add device, remove device,
164  *  start build, activate spare
165  */
166 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
167 static atomic_t md_event_count;
168 void md_new_event(mddev_t *mddev)
169 {
170         atomic_inc(&md_event_count);
171         wake_up(&md_event_waiters);
172 }
173 EXPORT_SYMBOL_GPL(md_new_event);
174
175 /* Alternate version that can be called from interrupts
176  * when calling sysfs_notify isn't needed.
177  */
178 static void md_new_event_inintr(mddev_t *mddev)
179 {
180         atomic_inc(&md_event_count);
181         wake_up(&md_event_waiters);
182 }
183
184 /*
185  * Enables to iterate over all existing md arrays
186  * all_mddevs_lock protects this list.
187  */
188 static LIST_HEAD(all_mddevs);
189 static DEFINE_SPINLOCK(all_mddevs_lock);
190
191
192 /*
193  * iterates through all used mddevs in the system.
194  * We take care to grab the all_mddevs_lock whenever navigating
195  * the list, and to always hold a refcount when unlocked.
196  * Any code which breaks out of this loop while own
197  * a reference to the current mddev and must mddev_put it.
198  */
199 #define for_each_mddev(mddev,tmp)                                       \
200                                                                         \
201         for (({ spin_lock(&all_mddevs_lock);                            \
202                 tmp = all_mddevs.next;                                  \
203                 mddev = NULL;});                                        \
204              ({ if (tmp != &all_mddevs)                                 \
205                         mddev_get(list_entry(tmp, mddev_t, all_mddevs));\
206                 spin_unlock(&all_mddevs_lock);                          \
207                 if (mddev) mddev_put(mddev);                            \
208                 mddev = list_entry(tmp, mddev_t, all_mddevs);           \
209                 tmp != &all_mddevs;});                                  \
210              ({ spin_lock(&all_mddevs_lock);                            \
211                 tmp = tmp->next;})                                      \
212                 )
213
214
215 static int md_fail_request (struct request_queue *q, struct bio *bio)
216 {
217         bio_io_error(bio);
218         return 0;
219 }
220
221 static inline mddev_t *mddev_get(mddev_t *mddev)
222 {
223         atomic_inc(&mddev->active);
224         return mddev;
225 }
226
227 static void mddev_put(mddev_t *mddev)
228 {
229         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
230                 return;
231         if (!mddev->raid_disks && list_empty(&mddev->disks)) {
232                 list_del(&mddev->all_mddevs);
233                 spin_unlock(&all_mddevs_lock);
234                 blk_cleanup_queue(mddev->queue);
235                 kobject_put(&mddev->kobj);
236         } else
237                 spin_unlock(&all_mddevs_lock);
238 }
239
240 static mddev_t * mddev_find(dev_t unit)
241 {
242         mddev_t *mddev, *new = NULL;
243
244  retry:
245         spin_lock(&all_mddevs_lock);
246         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
247                 if (mddev->unit == unit) {
248                         mddev_get(mddev);
249                         spin_unlock(&all_mddevs_lock);
250                         kfree(new);
251                         return mddev;
252                 }
253
254         if (new) {
255                 list_add(&new->all_mddevs, &all_mddevs);
256                 spin_unlock(&all_mddevs_lock);
257                 return new;
258         }
259         spin_unlock(&all_mddevs_lock);
260
261         new = kzalloc(sizeof(*new), GFP_KERNEL);
262         if (!new)
263                 return NULL;
264
265         new->unit = unit;
266         if (MAJOR(unit) == MD_MAJOR)
267                 new->md_minor = MINOR(unit);
268         else
269                 new->md_minor = MINOR(unit) >> MdpMinorShift;
270
271         mutex_init(&new->reconfig_mutex);
272         INIT_LIST_HEAD(&new->disks);
273         INIT_LIST_HEAD(&new->all_mddevs);
274         init_timer(&new->safemode_timer);
275         atomic_set(&new->active, 1);
276         atomic_set(&new->openers, 0);
277         spin_lock_init(&new->write_lock);
278         init_waitqueue_head(&new->sb_wait);
279         init_waitqueue_head(&new->recovery_wait);
280         new->reshape_position = MaxSector;
281         new->resync_min = 0;
282         new->resync_max = MaxSector;
283         new->level = LEVEL_NONE;
284
285         new->queue = blk_alloc_queue(GFP_KERNEL);
286         if (!new->queue) {
287                 kfree(new);
288                 return NULL;
289         }
290         /* Can be unlocked because the queue is new: no concurrency */
291         queue_flag_set_unlocked(QUEUE_FLAG_CLUSTER, new->queue);
292
293         blk_queue_make_request(new->queue, md_fail_request);
294
295         goto retry;
296 }
297
298 static inline int mddev_lock(mddev_t * mddev)
299 {
300         return mutex_lock_interruptible(&mddev->reconfig_mutex);
301 }
302
303 static inline int mddev_trylock(mddev_t * mddev)
304 {
305         return mutex_trylock(&mddev->reconfig_mutex);
306 }
307
308 static inline void mddev_unlock(mddev_t * mddev)
309 {
310         mutex_unlock(&mddev->reconfig_mutex);
311
312         md_wakeup_thread(mddev->thread);
313 }
314
315 static mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
316 {
317         mdk_rdev_t * rdev;
318         struct list_head *tmp;
319
320         rdev_for_each(rdev, tmp, mddev) {
321                 if (rdev->desc_nr == nr)
322                         return rdev;
323         }
324         return NULL;
325 }
326
327 static mdk_rdev_t * find_rdev(mddev_t * mddev, dev_t dev)
328 {
329         struct list_head *tmp;
330         mdk_rdev_t *rdev;
331
332         rdev_for_each(rdev, tmp, mddev) {
333                 if (rdev->bdev->bd_dev == dev)
334                         return rdev;
335         }
336         return NULL;
337 }
338
339 static struct mdk_personality *find_pers(int level, char *clevel)
340 {
341         struct mdk_personality *pers;
342         list_for_each_entry(pers, &pers_list, list) {
343                 if (level != LEVEL_NONE && pers->level == level)
344                         return pers;
345                 if (strcmp(pers->name, clevel)==0)
346                         return pers;
347         }
348         return NULL;
349 }
350
351 /* return the offset of the super block in 512byte sectors */
352 static inline sector_t calc_dev_sboffset(struct block_device *bdev)
353 {
354         sector_t num_sectors = bdev->bd_inode->i_size / 512;
355         return MD_NEW_SIZE_SECTORS(num_sectors);
356 }
357
358 static sector_t calc_num_sectors(mdk_rdev_t *rdev, unsigned chunk_size)
359 {
360         sector_t num_sectors = rdev->sb_start;
361
362         if (chunk_size)
363                 num_sectors &= ~((sector_t)chunk_size/512 - 1);
364         return num_sectors;
365 }
366
367 static int alloc_disk_sb(mdk_rdev_t * rdev)
368 {
369         if (rdev->sb_page)
370                 MD_BUG();
371
372         rdev->sb_page = alloc_page(GFP_KERNEL);
373         if (!rdev->sb_page) {
374                 printk(KERN_ALERT "md: out of memory.\n");
375                 return -ENOMEM;
376         }
377
378         return 0;
379 }
380
381 static void free_disk_sb(mdk_rdev_t * rdev)
382 {
383         if (rdev->sb_page) {
384                 put_page(rdev->sb_page);
385                 rdev->sb_loaded = 0;
386                 rdev->sb_page = NULL;
387                 rdev->sb_start = 0;
388                 rdev->size = 0;
389         }
390 }
391
392
393 static void super_written(struct bio *bio, int error)
394 {
395         mdk_rdev_t *rdev = bio->bi_private;
396         mddev_t *mddev = rdev->mddev;
397
398         if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
399                 printk("md: super_written gets error=%d, uptodate=%d\n",
400                        error, test_bit(BIO_UPTODATE, &bio->bi_flags));
401                 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
402                 md_error(mddev, rdev);
403         }
404
405         if (atomic_dec_and_test(&mddev->pending_writes))
406                 wake_up(&mddev->sb_wait);
407         bio_put(bio);
408 }
409
410 static void super_written_barrier(struct bio *bio, int error)
411 {
412         struct bio *bio2 = bio->bi_private;
413         mdk_rdev_t *rdev = bio2->bi_private;
414         mddev_t *mddev = rdev->mddev;
415
416         if (!test_bit(BIO_UPTODATE, &bio->bi_flags) &&
417             error == -EOPNOTSUPP) {
418                 unsigned long flags;
419                 /* barriers don't appear to be supported :-( */
420                 set_bit(BarriersNotsupp, &rdev->flags);
421                 mddev->barriers_work = 0;
422                 spin_lock_irqsave(&mddev->write_lock, flags);
423                 bio2->bi_next = mddev->biolist;
424                 mddev->biolist = bio2;
425                 spin_unlock_irqrestore(&mddev->write_lock, flags);
426                 wake_up(&mddev->sb_wait);
427                 bio_put(bio);
428         } else {
429                 bio_put(bio2);
430                 bio->bi_private = rdev;
431                 super_written(bio, error);
432         }
433 }
434
435 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
436                    sector_t sector, int size, struct page *page)
437 {
438         /* write first size bytes of page to sector of rdev
439          * Increment mddev->pending_writes before returning
440          * and decrement it on completion, waking up sb_wait
441          * if zero is reached.
442          * If an error occurred, call md_error
443          *
444          * As we might need to resubmit the request if BIO_RW_BARRIER
445          * causes ENOTSUPP, we allocate a spare bio...
446          */
447         struct bio *bio = bio_alloc(GFP_NOIO, 1);
448         int rw = (1<<BIO_RW) | (1<<BIO_RW_SYNC);
449
450         bio->bi_bdev = rdev->bdev;
451         bio->bi_sector = sector;
452         bio_add_page(bio, page, size, 0);
453         bio->bi_private = rdev;
454         bio->bi_end_io = super_written;
455         bio->bi_rw = rw;
456
457         atomic_inc(&mddev->pending_writes);
458         if (!test_bit(BarriersNotsupp, &rdev->flags)) {
459                 struct bio *rbio;
460                 rw |= (1<<BIO_RW_BARRIER);
461                 rbio = bio_clone(bio, GFP_NOIO);
462                 rbio->bi_private = bio;
463                 rbio->bi_end_io = super_written_barrier;
464                 submit_bio(rw, rbio);
465         } else
466                 submit_bio(rw, bio);
467 }
468
469 void md_super_wait(mddev_t *mddev)
470 {
471         /* wait for all superblock writes that were scheduled to complete.
472          * if any had to be retried (due to BARRIER problems), retry them
473          */
474         DEFINE_WAIT(wq);
475         for(;;) {
476                 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
477                 if (atomic_read(&mddev->pending_writes)==0)
478                         break;
479                 while (mddev->biolist) {
480                         struct bio *bio;
481                         spin_lock_irq(&mddev->write_lock);
482                         bio = mddev->biolist;
483                         mddev->biolist = bio->bi_next ;
484                         bio->bi_next = NULL;
485                         spin_unlock_irq(&mddev->write_lock);
486                         submit_bio(bio->bi_rw, bio);
487                 }
488                 schedule();
489         }
490         finish_wait(&mddev->sb_wait, &wq);
491 }
492
493 static void bi_complete(struct bio *bio, int error)
494 {
495         complete((struct completion*)bio->bi_private);
496 }
497
498 int sync_page_io(struct block_device *bdev, sector_t sector, int size,
499                    struct page *page, int rw)
500 {
501         struct bio *bio = bio_alloc(GFP_NOIO, 1);
502         struct completion event;
503         int ret;
504
505         rw |= (1 << BIO_RW_SYNC);
506
507         bio->bi_bdev = bdev;
508         bio->bi_sector = sector;
509         bio_add_page(bio, page, size, 0);
510         init_completion(&event);
511         bio->bi_private = &event;
512         bio->bi_end_io = bi_complete;
513         submit_bio(rw, bio);
514         wait_for_completion(&event);
515
516         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
517         bio_put(bio);
518         return ret;
519 }
520 EXPORT_SYMBOL_GPL(sync_page_io);
521
522 static int read_disk_sb(mdk_rdev_t * rdev, int size)
523 {
524         char b[BDEVNAME_SIZE];
525         if (!rdev->sb_page) {
526                 MD_BUG();
527                 return -EINVAL;
528         }
529         if (rdev->sb_loaded)
530                 return 0;
531
532
533         if (!sync_page_io(rdev->bdev, rdev->sb_start, size, rdev->sb_page, READ))
534                 goto fail;
535         rdev->sb_loaded = 1;
536         return 0;
537
538 fail:
539         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
540                 bdevname(rdev->bdev,b));
541         return -EINVAL;
542 }
543
544 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
545 {
546         return  sb1->set_uuid0 == sb2->set_uuid0 &&
547                 sb1->set_uuid1 == sb2->set_uuid1 &&
548                 sb1->set_uuid2 == sb2->set_uuid2 &&
549                 sb1->set_uuid3 == sb2->set_uuid3;
550 }
551
552 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
553 {
554         int ret;
555         mdp_super_t *tmp1, *tmp2;
556
557         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
558         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
559
560         if (!tmp1 || !tmp2) {
561                 ret = 0;
562                 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
563                 goto abort;
564         }
565
566         *tmp1 = *sb1;
567         *tmp2 = *sb2;
568
569         /*
570          * nr_disks is not constant
571          */
572         tmp1->nr_disks = 0;
573         tmp2->nr_disks = 0;
574
575         ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
576 abort:
577         kfree(tmp1);
578         kfree(tmp2);
579         return ret;
580 }
581
582
583 static u32 md_csum_fold(u32 csum)
584 {
585         csum = (csum & 0xffff) + (csum >> 16);
586         return (csum & 0xffff) + (csum >> 16);
587 }
588
589 static unsigned int calc_sb_csum(mdp_super_t * sb)
590 {
591         u64 newcsum = 0;
592         u32 *sb32 = (u32*)sb;
593         int i;
594         unsigned int disk_csum, csum;
595
596         disk_csum = sb->sb_csum;
597         sb->sb_csum = 0;
598
599         for (i = 0; i < MD_SB_BYTES/4 ; i++)
600                 newcsum += sb32[i];
601         csum = (newcsum & 0xffffffff) + (newcsum>>32);
602
603
604 #ifdef CONFIG_ALPHA
605         /* This used to use csum_partial, which was wrong for several
606          * reasons including that different results are returned on
607          * different architectures.  It isn't critical that we get exactly
608          * the same return value as before (we always csum_fold before
609          * testing, and that removes any differences).  However as we
610          * know that csum_partial always returned a 16bit value on
611          * alphas, do a fold to maximise conformity to previous behaviour.
612          */
613         sb->sb_csum = md_csum_fold(disk_csum);
614 #else
615         sb->sb_csum = disk_csum;
616 #endif
617         return csum;
618 }
619
620
621 /*
622  * Handle superblock details.
623  * We want to be able to handle multiple superblock formats
624  * so we have a common interface to them all, and an array of
625  * different handlers.
626  * We rely on user-space to write the initial superblock, and support
627  * reading and updating of superblocks.
628  * Interface methods are:
629  *   int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
630  *      loads and validates a superblock on dev.
631  *      if refdev != NULL, compare superblocks on both devices
632  *    Return:
633  *      0 - dev has a superblock that is compatible with refdev
634  *      1 - dev has a superblock that is compatible and newer than refdev
635  *          so dev should be used as the refdev in future
636  *     -EINVAL superblock incompatible or invalid
637  *     -othererror e.g. -EIO
638  *
639  *   int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
640  *      Verify that dev is acceptable into mddev.
641  *       The first time, mddev->raid_disks will be 0, and data from
642  *       dev should be merged in.  Subsequent calls check that dev
643  *       is new enough.  Return 0 or -EINVAL
644  *
645  *   void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
646  *     Update the superblock for rdev with data in mddev
647  *     This does not write to disc.
648  *
649  */
650
651 struct super_type  {
652         char                *name;
653         struct module       *owner;
654         int                 (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev,
655                                           int minor_version);
656         int                 (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
657         void                (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
658         unsigned long long  (*rdev_size_change)(mdk_rdev_t *rdev,
659                                                 sector_t num_sectors);
660 };
661
662 /*
663  * load_super for 0.90.0 
664  */
665 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
666 {
667         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
668         mdp_super_t *sb;
669         int ret;
670
671         /*
672          * Calculate the position of the superblock (512byte sectors),
673          * it's at the end of the disk.
674          *
675          * It also happens to be a multiple of 4Kb.
676          */
677         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
678
679         ret = read_disk_sb(rdev, MD_SB_BYTES);
680         if (ret) return ret;
681
682         ret = -EINVAL;
683
684         bdevname(rdev->bdev, b);
685         sb = (mdp_super_t*)page_address(rdev->sb_page);
686
687         if (sb->md_magic != MD_SB_MAGIC) {
688                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
689                        b);
690                 goto abort;
691         }
692
693         if (sb->major_version != 0 ||
694             sb->minor_version < 90 ||
695             sb->minor_version > 91) {
696                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
697                         sb->major_version, sb->minor_version,
698                         b);
699                 goto abort;
700         }
701
702         if (sb->raid_disks <= 0)
703                 goto abort;
704
705         if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
706                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
707                         b);
708                 goto abort;
709         }
710
711         rdev->preferred_minor = sb->md_minor;
712         rdev->data_offset = 0;
713         rdev->sb_size = MD_SB_BYTES;
714
715         if (sb->state & (1<<MD_SB_BITMAP_PRESENT)) {
716                 if (sb->level != 1 && sb->level != 4
717                     && sb->level != 5 && sb->level != 6
718                     && sb->level != 10) {
719                         /* FIXME use a better test */
720                         printk(KERN_WARNING
721                                "md: bitmaps not supported for this level.\n");
722                         goto abort;
723                 }
724         }
725
726         if (sb->level == LEVEL_MULTIPATH)
727                 rdev->desc_nr = -1;
728         else
729                 rdev->desc_nr = sb->this_disk.number;
730
731         if (!refdev) {
732                 ret = 1;
733         } else {
734                 __u64 ev1, ev2;
735                 mdp_super_t *refsb = (mdp_super_t*)page_address(refdev->sb_page);
736                 if (!uuid_equal(refsb, sb)) {
737                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
738                                 b, bdevname(refdev->bdev,b2));
739                         goto abort;
740                 }
741                 if (!sb_equal(refsb, sb)) {
742                         printk(KERN_WARNING "md: %s has same UUID"
743                                " but different superblock to %s\n",
744                                b, bdevname(refdev->bdev, b2));
745                         goto abort;
746                 }
747                 ev1 = md_event(sb);
748                 ev2 = md_event(refsb);
749                 if (ev1 > ev2)
750                         ret = 1;
751                 else 
752                         ret = 0;
753         }
754         rdev->size = calc_num_sectors(rdev, sb->chunk_size) / 2;
755
756         if (rdev->size < sb->size && sb->level > 1)
757                 /* "this cannot possibly happen" ... */
758                 ret = -EINVAL;
759
760  abort:
761         return ret;
762 }
763
764 /*
765  * validate_super for 0.90.0
766  */
767 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
768 {
769         mdp_disk_t *desc;
770         mdp_super_t *sb = (mdp_super_t *)page_address(rdev->sb_page);
771         __u64 ev1 = md_event(sb);
772
773         rdev->raid_disk = -1;
774         clear_bit(Faulty, &rdev->flags);
775         clear_bit(In_sync, &rdev->flags);
776         clear_bit(WriteMostly, &rdev->flags);
777         clear_bit(BarriersNotsupp, &rdev->flags);
778
779         if (mddev->raid_disks == 0) {
780                 mddev->major_version = 0;
781                 mddev->minor_version = sb->minor_version;
782                 mddev->patch_version = sb->patch_version;
783                 mddev->external = 0;
784                 mddev->chunk_size = sb->chunk_size;
785                 mddev->ctime = sb->ctime;
786                 mddev->utime = sb->utime;
787                 mddev->level = sb->level;
788                 mddev->clevel[0] = 0;
789                 mddev->layout = sb->layout;
790                 mddev->raid_disks = sb->raid_disks;
791                 mddev->size = sb->size;
792                 mddev->events = ev1;
793                 mddev->bitmap_offset = 0;
794                 mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
795
796                 if (mddev->minor_version >= 91) {
797                         mddev->reshape_position = sb->reshape_position;
798                         mddev->delta_disks = sb->delta_disks;
799                         mddev->new_level = sb->new_level;
800                         mddev->new_layout = sb->new_layout;
801                         mddev->new_chunk = sb->new_chunk;
802                 } else {
803                         mddev->reshape_position = MaxSector;
804                         mddev->delta_disks = 0;
805                         mddev->new_level = mddev->level;
806                         mddev->new_layout = mddev->layout;
807                         mddev->new_chunk = mddev->chunk_size;
808                 }
809
810                 if (sb->state & (1<<MD_SB_CLEAN))
811                         mddev->recovery_cp = MaxSector;
812                 else {
813                         if (sb->events_hi == sb->cp_events_hi && 
814                                 sb->events_lo == sb->cp_events_lo) {
815                                 mddev->recovery_cp = sb->recovery_cp;
816                         } else
817                                 mddev->recovery_cp = 0;
818                 }
819
820                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
821                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
822                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
823                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
824
825                 mddev->max_disks = MD_SB_DISKS;
826
827                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
828                     mddev->bitmap_file == NULL)
829                         mddev->bitmap_offset = mddev->default_bitmap_offset;
830
831         } else if (mddev->pers == NULL) {
832                 /* Insist on good event counter while assembling */
833                 ++ev1;
834                 if (ev1 < mddev->events) 
835                         return -EINVAL;
836         } else if (mddev->bitmap) {
837                 /* if adding to array with a bitmap, then we can accept an
838                  * older device ... but not too old.
839                  */
840                 if (ev1 < mddev->bitmap->events_cleared)
841                         return 0;
842         } else {
843                 if (ev1 < mddev->events)
844                         /* just a hot-add of a new device, leave raid_disk at -1 */
845                         return 0;
846         }
847
848         if (mddev->level != LEVEL_MULTIPATH) {
849                 desc = sb->disks + rdev->desc_nr;
850
851                 if (desc->state & (1<<MD_DISK_FAULTY))
852                         set_bit(Faulty, &rdev->flags);
853                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
854                             desc->raid_disk < mddev->raid_disks */) {
855                         set_bit(In_sync, &rdev->flags);
856                         rdev->raid_disk = desc->raid_disk;
857                 }
858                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
859                         set_bit(WriteMostly, &rdev->flags);
860         } else /* MULTIPATH are always insync */
861                 set_bit(In_sync, &rdev->flags);
862         return 0;
863 }
864
865 /*
866  * sync_super for 0.90.0
867  */
868 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
869 {
870         mdp_super_t *sb;
871         struct list_head *tmp;
872         mdk_rdev_t *rdev2;
873         int next_spare = mddev->raid_disks;
874
875
876         /* make rdev->sb match mddev data..
877          *
878          * 1/ zero out disks
879          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
880          * 3/ any empty disks < next_spare become removed
881          *
882          * disks[0] gets initialised to REMOVED because
883          * we cannot be sure from other fields if it has
884          * been initialised or not.
885          */
886         int i;
887         int active=0, working=0,failed=0,spare=0,nr_disks=0;
888
889         rdev->sb_size = MD_SB_BYTES;
890
891         sb = (mdp_super_t*)page_address(rdev->sb_page);
892
893         memset(sb, 0, sizeof(*sb));
894
895         sb->md_magic = MD_SB_MAGIC;
896         sb->major_version = mddev->major_version;
897         sb->patch_version = mddev->patch_version;
898         sb->gvalid_words  = 0; /* ignored */
899         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
900         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
901         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
902         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
903
904         sb->ctime = mddev->ctime;
905         sb->level = mddev->level;
906         sb->size  = mddev->size;
907         sb->raid_disks = mddev->raid_disks;
908         sb->md_minor = mddev->md_minor;
909         sb->not_persistent = 0;
910         sb->utime = mddev->utime;
911         sb->state = 0;
912         sb->events_hi = (mddev->events>>32);
913         sb->events_lo = (u32)mddev->events;
914
915         if (mddev->reshape_position == MaxSector)
916                 sb->minor_version = 90;
917         else {
918                 sb->minor_version = 91;
919                 sb->reshape_position = mddev->reshape_position;
920                 sb->new_level = mddev->new_level;
921                 sb->delta_disks = mddev->delta_disks;
922                 sb->new_layout = mddev->new_layout;
923                 sb->new_chunk = mddev->new_chunk;
924         }
925         mddev->minor_version = sb->minor_version;
926         if (mddev->in_sync)
927         {
928                 sb->recovery_cp = mddev->recovery_cp;
929                 sb->cp_events_hi = (mddev->events>>32);
930                 sb->cp_events_lo = (u32)mddev->events;
931                 if (mddev->recovery_cp == MaxSector)
932                         sb->state = (1<< MD_SB_CLEAN);
933         } else
934                 sb->recovery_cp = 0;
935
936         sb->layout = mddev->layout;
937         sb->chunk_size = mddev->chunk_size;
938
939         if (mddev->bitmap && mddev->bitmap_file == NULL)
940                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
941
942         sb->disks[0].state = (1<<MD_DISK_REMOVED);
943         rdev_for_each(rdev2, tmp, mddev) {
944                 mdp_disk_t *d;
945                 int desc_nr;
946                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
947                     && !test_bit(Faulty, &rdev2->flags))
948                         desc_nr = rdev2->raid_disk;
949                 else
950                         desc_nr = next_spare++;
951                 rdev2->desc_nr = desc_nr;
952                 d = &sb->disks[rdev2->desc_nr];
953                 nr_disks++;
954                 d->number = rdev2->desc_nr;
955                 d->major = MAJOR(rdev2->bdev->bd_dev);
956                 d->minor = MINOR(rdev2->bdev->bd_dev);
957                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
958                     && !test_bit(Faulty, &rdev2->flags))
959                         d->raid_disk = rdev2->raid_disk;
960                 else
961                         d->raid_disk = rdev2->desc_nr; /* compatibility */
962                 if (test_bit(Faulty, &rdev2->flags))
963                         d->state = (1<<MD_DISK_FAULTY);
964                 else if (test_bit(In_sync, &rdev2->flags)) {
965                         d->state = (1<<MD_DISK_ACTIVE);
966                         d->state |= (1<<MD_DISK_SYNC);
967                         active++;
968                         working++;
969                 } else {
970                         d->state = 0;
971                         spare++;
972                         working++;
973                 }
974                 if (test_bit(WriteMostly, &rdev2->flags))
975                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
976         }
977         /* now set the "removed" and "faulty" bits on any missing devices */
978         for (i=0 ; i < mddev->raid_disks ; i++) {
979                 mdp_disk_t *d = &sb->disks[i];
980                 if (d->state == 0 && d->number == 0) {
981                         d->number = i;
982                         d->raid_disk = i;
983                         d->state = (1<<MD_DISK_REMOVED);
984                         d->state |= (1<<MD_DISK_FAULTY);
985                         failed++;
986                 }
987         }
988         sb->nr_disks = nr_disks;
989         sb->active_disks = active;
990         sb->working_disks = working;
991         sb->failed_disks = failed;
992         sb->spare_disks = spare;
993
994         sb->this_disk = sb->disks[rdev->desc_nr];
995         sb->sb_csum = calc_sb_csum(sb);
996 }
997
998 /*
999  * rdev_size_change for 0.90.0
1000  */
1001 static unsigned long long
1002 super_90_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1003 {
1004         if (num_sectors && num_sectors < rdev->mddev->size * 2)
1005                 return 0; /* component must fit device */
1006         if (rdev->mddev->bitmap_offset)
1007                 return 0; /* can't move bitmap */
1008         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
1009         if (!num_sectors || num_sectors > rdev->sb_start)
1010                 num_sectors = rdev->sb_start;
1011         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1012                        rdev->sb_page);
1013         md_super_wait(rdev->mddev);
1014         return num_sectors / 2; /* kB for sysfs */
1015 }
1016
1017
1018 /*
1019  * version 1 superblock
1020  */
1021
1022 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1023 {
1024         __le32 disk_csum;
1025         u32 csum;
1026         unsigned long long newcsum;
1027         int size = 256 + le32_to_cpu(sb->max_dev)*2;
1028         __le32 *isuper = (__le32*)sb;
1029         int i;
1030
1031         disk_csum = sb->sb_csum;
1032         sb->sb_csum = 0;
1033         newcsum = 0;
1034         for (i=0; size>=4; size -= 4 )
1035                 newcsum += le32_to_cpu(*isuper++);
1036
1037         if (size == 2)
1038                 newcsum += le16_to_cpu(*(__le16*) isuper);
1039
1040         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1041         sb->sb_csum = disk_csum;
1042         return cpu_to_le32(csum);
1043 }
1044
1045 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
1046 {
1047         struct mdp_superblock_1 *sb;
1048         int ret;
1049         sector_t sb_start;
1050         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1051         int bmask;
1052
1053         /*
1054          * Calculate the position of the superblock in 512byte sectors.
1055          * It is always aligned to a 4K boundary and
1056          * depeding on minor_version, it can be:
1057          * 0: At least 8K, but less than 12K, from end of device
1058          * 1: At start of device
1059          * 2: 4K from start of device.
1060          */
1061         switch(minor_version) {
1062         case 0:
1063                 sb_start = rdev->bdev->bd_inode->i_size >> 9;
1064                 sb_start -= 8*2;
1065                 sb_start &= ~(sector_t)(4*2-1);
1066                 break;
1067         case 1:
1068                 sb_start = 0;
1069                 break;
1070         case 2:
1071                 sb_start = 8;
1072                 break;
1073         default:
1074                 return -EINVAL;
1075         }
1076         rdev->sb_start = sb_start;
1077
1078         /* superblock is rarely larger than 1K, but it can be larger,
1079          * and it is safe to read 4k, so we do that
1080          */
1081         ret = read_disk_sb(rdev, 4096);
1082         if (ret) return ret;
1083
1084
1085         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1086
1087         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1088             sb->major_version != cpu_to_le32(1) ||
1089             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1090             le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1091             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1092                 return -EINVAL;
1093
1094         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1095                 printk("md: invalid superblock checksum on %s\n",
1096                         bdevname(rdev->bdev,b));
1097                 return -EINVAL;
1098         }
1099         if (le64_to_cpu(sb->data_size) < 10) {
1100                 printk("md: data_size too small on %s\n",
1101                        bdevname(rdev->bdev,b));
1102                 return -EINVAL;
1103         }
1104         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET)) {
1105                 if (sb->level != cpu_to_le32(1) &&
1106                     sb->level != cpu_to_le32(4) &&
1107                     sb->level != cpu_to_le32(5) &&
1108                     sb->level != cpu_to_le32(6) &&
1109                     sb->level != cpu_to_le32(10)) {
1110                         printk(KERN_WARNING
1111                                "md: bitmaps not supported for this level.\n");
1112                         return -EINVAL;
1113                 }
1114         }
1115
1116         rdev->preferred_minor = 0xffff;
1117         rdev->data_offset = le64_to_cpu(sb->data_offset);
1118         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1119
1120         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1121         bmask = queue_hardsect_size(rdev->bdev->bd_disk->queue)-1;
1122         if (rdev->sb_size & bmask)
1123                 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1124
1125         if (minor_version
1126             && rdev->data_offset < sb_start + (rdev->sb_size/512))
1127                 return -EINVAL;
1128
1129         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1130                 rdev->desc_nr = -1;
1131         else
1132                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1133
1134         if (!refdev) {
1135                 ret = 1;
1136         } else {
1137                 __u64 ev1, ev2;
1138                 struct mdp_superblock_1 *refsb = 
1139                         (struct mdp_superblock_1*)page_address(refdev->sb_page);
1140
1141                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1142                     sb->level != refsb->level ||
1143                     sb->layout != refsb->layout ||
1144                     sb->chunksize != refsb->chunksize) {
1145                         printk(KERN_WARNING "md: %s has strangely different"
1146                                 " superblock to %s\n",
1147                                 bdevname(rdev->bdev,b),
1148                                 bdevname(refdev->bdev,b2));
1149                         return -EINVAL;
1150                 }
1151                 ev1 = le64_to_cpu(sb->events);
1152                 ev2 = le64_to_cpu(refsb->events);
1153
1154                 if (ev1 > ev2)
1155                         ret = 1;
1156                 else
1157                         ret = 0;
1158         }
1159         if (minor_version)
1160                 rdev->size = ((rdev->bdev->bd_inode->i_size>>9) - le64_to_cpu(sb->data_offset)) / 2;
1161         else
1162                 rdev->size = rdev->sb_start / 2;
1163         if (rdev->size < le64_to_cpu(sb->data_size)/2)
1164                 return -EINVAL;
1165         rdev->size = le64_to_cpu(sb->data_size)/2;
1166         if (le32_to_cpu(sb->chunksize))
1167                 rdev->size &= ~((sector_t)le32_to_cpu(sb->chunksize)/2 - 1);
1168
1169         if (le64_to_cpu(sb->size) > rdev->size*2)
1170                 return -EINVAL;
1171         return ret;
1172 }
1173
1174 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1175 {
1176         struct mdp_superblock_1 *sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1177         __u64 ev1 = le64_to_cpu(sb->events);
1178
1179         rdev->raid_disk = -1;
1180         clear_bit(Faulty, &rdev->flags);
1181         clear_bit(In_sync, &rdev->flags);
1182         clear_bit(WriteMostly, &rdev->flags);
1183         clear_bit(BarriersNotsupp, &rdev->flags);
1184
1185         if (mddev->raid_disks == 0) {
1186                 mddev->major_version = 1;
1187                 mddev->patch_version = 0;
1188                 mddev->external = 0;
1189                 mddev->chunk_size = le32_to_cpu(sb->chunksize) << 9;
1190                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1191                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1192                 mddev->level = le32_to_cpu(sb->level);
1193                 mddev->clevel[0] = 0;
1194                 mddev->layout = le32_to_cpu(sb->layout);
1195                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1196                 mddev->size = le64_to_cpu(sb->size)/2;
1197                 mddev->events = ev1;
1198                 mddev->bitmap_offset = 0;
1199                 mddev->default_bitmap_offset = 1024 >> 9;
1200                 
1201                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1202                 memcpy(mddev->uuid, sb->set_uuid, 16);
1203
1204                 mddev->max_disks =  (4096-256)/2;
1205
1206                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1207                     mddev->bitmap_file == NULL )
1208                         mddev->bitmap_offset = (__s32)le32_to_cpu(sb->bitmap_offset);
1209
1210                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1211                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1212                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1213                         mddev->new_level = le32_to_cpu(sb->new_level);
1214                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1215                         mddev->new_chunk = le32_to_cpu(sb->new_chunk)<<9;
1216                 } else {
1217                         mddev->reshape_position = MaxSector;
1218                         mddev->delta_disks = 0;
1219                         mddev->new_level = mddev->level;
1220                         mddev->new_layout = mddev->layout;
1221                         mddev->new_chunk = mddev->chunk_size;
1222                 }
1223
1224         } else if (mddev->pers == NULL) {
1225                 /* Insist of good event counter while assembling */
1226                 ++ev1;
1227                 if (ev1 < mddev->events)
1228                         return -EINVAL;
1229         } else if (mddev->bitmap) {
1230                 /* If adding to array with a bitmap, then we can accept an
1231                  * older device, but not too old.
1232                  */
1233                 if (ev1 < mddev->bitmap->events_cleared)
1234                         return 0;
1235         } else {
1236                 if (ev1 < mddev->events)
1237                         /* just a hot-add of a new device, leave raid_disk at -1 */
1238                         return 0;
1239         }
1240         if (mddev->level != LEVEL_MULTIPATH) {
1241                 int role;
1242                 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1243                 switch(role) {
1244                 case 0xffff: /* spare */
1245                         break;
1246                 case 0xfffe: /* faulty */
1247                         set_bit(Faulty, &rdev->flags);
1248                         break;
1249                 default:
1250                         if ((le32_to_cpu(sb->feature_map) &
1251                              MD_FEATURE_RECOVERY_OFFSET))
1252                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1253                         else
1254                                 set_bit(In_sync, &rdev->flags);
1255                         rdev->raid_disk = role;
1256                         break;
1257                 }
1258                 if (sb->devflags & WriteMostly1)
1259                         set_bit(WriteMostly, &rdev->flags);
1260         } else /* MULTIPATH are always insync */
1261                 set_bit(In_sync, &rdev->flags);
1262
1263         return 0;
1264 }
1265
1266 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1267 {
1268         struct mdp_superblock_1 *sb;
1269         struct list_head *tmp;
1270         mdk_rdev_t *rdev2;
1271         int max_dev, i;
1272         /* make rdev->sb match mddev and rdev data. */
1273
1274         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1275
1276         sb->feature_map = 0;
1277         sb->pad0 = 0;
1278         sb->recovery_offset = cpu_to_le64(0);
1279         memset(sb->pad1, 0, sizeof(sb->pad1));
1280         memset(sb->pad2, 0, sizeof(sb->pad2));
1281         memset(sb->pad3, 0, sizeof(sb->pad3));
1282
1283         sb->utime = cpu_to_le64((__u64)mddev->utime);
1284         sb->events = cpu_to_le64(mddev->events);
1285         if (mddev->in_sync)
1286                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1287         else
1288                 sb->resync_offset = cpu_to_le64(0);
1289
1290         sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1291
1292         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1293         sb->size = cpu_to_le64(mddev->size<<1);
1294
1295         if (mddev->bitmap && mddev->bitmap_file == NULL) {
1296                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_offset);
1297                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1298         }
1299
1300         if (rdev->raid_disk >= 0 &&
1301             !test_bit(In_sync, &rdev->flags) &&
1302             rdev->recovery_offset > 0) {
1303                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1304                 sb->recovery_offset = cpu_to_le64(rdev->recovery_offset);
1305         }
1306
1307         if (mddev->reshape_position != MaxSector) {
1308                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1309                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1310                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1311                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1312                 sb->new_level = cpu_to_le32(mddev->new_level);
1313                 sb->new_chunk = cpu_to_le32(mddev->new_chunk>>9);
1314         }
1315
1316         max_dev = 0;
1317         rdev_for_each(rdev2, tmp, mddev)
1318                 if (rdev2->desc_nr+1 > max_dev)
1319                         max_dev = rdev2->desc_nr+1;
1320
1321         if (max_dev > le32_to_cpu(sb->max_dev))
1322                 sb->max_dev = cpu_to_le32(max_dev);
1323         for (i=0; i<max_dev;i++)
1324                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1325         
1326         rdev_for_each(rdev2, tmp, mddev) {
1327                 i = rdev2->desc_nr;
1328                 if (test_bit(Faulty, &rdev2->flags))
1329                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1330                 else if (test_bit(In_sync, &rdev2->flags))
1331                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1332                 else if (rdev2->raid_disk >= 0 && rdev2->recovery_offset > 0)
1333                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1334                 else
1335                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1336         }
1337
1338         sb->sb_csum = calc_sb_1_csum(sb);
1339 }
1340
1341 static unsigned long long
1342 super_1_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1343 {
1344         struct mdp_superblock_1 *sb;
1345         sector_t max_sectors;
1346         if (num_sectors && num_sectors < rdev->mddev->size * 2)
1347                 return 0; /* component must fit device */
1348         if (rdev->sb_start < rdev->data_offset) {
1349                 /* minor versions 1 and 2; superblock before data */
1350                 max_sectors = rdev->bdev->bd_inode->i_size >> 9;
1351                 max_sectors -= rdev->data_offset;
1352                 if (!num_sectors || num_sectors > max_sectors)
1353                         num_sectors = max_sectors;
1354         } else if (rdev->mddev->bitmap_offset) {
1355                 /* minor version 0 with bitmap we can't move */
1356                 return 0;
1357         } else {
1358                 /* minor version 0; superblock after data */
1359                 sector_t sb_start;
1360                 sb_start = (rdev->bdev->bd_inode->i_size >> 9) - 8*2;
1361                 sb_start &= ~(sector_t)(4*2 - 1);
1362                 max_sectors = rdev->size * 2 + sb_start - rdev->sb_start;
1363                 if (!num_sectors || num_sectors > max_sectors)
1364                         num_sectors = max_sectors;
1365                 rdev->sb_start = sb_start;
1366         }
1367         sb = (struct mdp_superblock_1 *) page_address(rdev->sb_page);
1368         sb->data_size = cpu_to_le64(num_sectors);
1369         sb->super_offset = rdev->sb_start;
1370         sb->sb_csum = calc_sb_1_csum(sb);
1371         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1372                        rdev->sb_page);
1373         md_super_wait(rdev->mddev);
1374         return num_sectors / 2; /* kB for sysfs */
1375 }
1376
1377 static struct super_type super_types[] = {
1378         [0] = {
1379                 .name   = "0.90.0",
1380                 .owner  = THIS_MODULE,
1381                 .load_super         = super_90_load,
1382                 .validate_super     = super_90_validate,
1383                 .sync_super         = super_90_sync,
1384                 .rdev_size_change   = super_90_rdev_size_change,
1385         },
1386         [1] = {
1387                 .name   = "md-1",
1388                 .owner  = THIS_MODULE,
1389                 .load_super         = super_1_load,
1390                 .validate_super     = super_1_validate,
1391                 .sync_super         = super_1_sync,
1392                 .rdev_size_change   = super_1_rdev_size_change,
1393         },
1394 };
1395
1396 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1397 {
1398         mdk_rdev_t *rdev, *rdev2;
1399
1400         rcu_read_lock();
1401         rdev_for_each_rcu(rdev, mddev1)
1402                 rdev_for_each_rcu(rdev2, mddev2)
1403                         if (rdev->bdev->bd_contains ==
1404                             rdev2->bdev->bd_contains) {
1405                                 rcu_read_unlock();
1406                                 return 1;
1407                         }
1408         rcu_read_unlock();
1409         return 0;
1410 }
1411
1412 static LIST_HEAD(pending_raid_disks);
1413
1414 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1415 {
1416         char b[BDEVNAME_SIZE];
1417         struct kobject *ko;
1418         char *s;
1419         int err;
1420
1421         if (rdev->mddev) {
1422                 MD_BUG();
1423                 return -EINVAL;
1424         }
1425
1426         /* prevent duplicates */
1427         if (find_rdev(mddev, rdev->bdev->bd_dev))
1428                 return -EEXIST;
1429
1430         /* make sure rdev->size exceeds mddev->size */
1431         if (rdev->size && (mddev->size == 0 || rdev->size < mddev->size)) {
1432                 if (mddev->pers) {
1433                         /* Cannot change size, so fail
1434                          * If mddev->level <= 0, then we don't care
1435                          * about aligning sizes (e.g. linear)
1436                          */
1437                         if (mddev->level > 0)
1438                                 return -ENOSPC;
1439                 } else
1440                         mddev->size = rdev->size;
1441         }
1442
1443         /* Verify rdev->desc_nr is unique.
1444          * If it is -1, assign a free number, else
1445          * check number is not in use
1446          */
1447         if (rdev->desc_nr < 0) {
1448                 int choice = 0;
1449                 if (mddev->pers) choice = mddev->raid_disks;
1450                 while (find_rdev_nr(mddev, choice))
1451                         choice++;
1452                 rdev->desc_nr = choice;
1453         } else {
1454                 if (find_rdev_nr(mddev, rdev->desc_nr))
1455                         return -EBUSY;
1456         }
1457         bdevname(rdev->bdev,b);
1458         while ( (s=strchr(b, '/')) != NULL)
1459                 *s = '!';
1460
1461         rdev->mddev = mddev;
1462         printk(KERN_INFO "md: bind<%s>\n", b);
1463
1464         if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
1465                 goto fail;
1466
1467         ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
1468         if ((err = sysfs_create_link(&rdev->kobj, ko, "block"))) {
1469                 kobject_del(&rdev->kobj);
1470                 goto fail;
1471         }
1472         list_add_rcu(&rdev->same_set, &mddev->disks);
1473         bd_claim_by_disk(rdev->bdev, rdev->bdev->bd_holder, mddev->gendisk);
1474         return 0;
1475
1476  fail:
1477         printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
1478                b, mdname(mddev));
1479         return err;
1480 }
1481
1482 static void md_delayed_delete(struct work_struct *ws)
1483 {
1484         mdk_rdev_t *rdev = container_of(ws, mdk_rdev_t, del_work);
1485         kobject_del(&rdev->kobj);
1486         kobject_put(&rdev->kobj);
1487 }
1488
1489 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
1490 {
1491         char b[BDEVNAME_SIZE];
1492         if (!rdev->mddev) {
1493                 MD_BUG();
1494                 return;
1495         }
1496         bd_release_from_disk(rdev->bdev, rdev->mddev->gendisk);
1497         list_del_rcu(&rdev->same_set);
1498         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
1499         rdev->mddev = NULL;
1500         sysfs_remove_link(&rdev->kobj, "block");
1501
1502         /* We need to delay this, otherwise we can deadlock when
1503          * writing to 'remove' to "dev/state".  We also need
1504          * to delay it due to rcu usage.
1505          */
1506         synchronize_rcu();
1507         INIT_WORK(&rdev->del_work, md_delayed_delete);
1508         kobject_get(&rdev->kobj);
1509         schedule_work(&rdev->del_work);
1510 }
1511
1512 /*
1513  * prevent the device from being mounted, repartitioned or
1514  * otherwise reused by a RAID array (or any other kernel
1515  * subsystem), by bd_claiming the device.
1516  */
1517 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev, int shared)
1518 {
1519         int err = 0;
1520         struct block_device *bdev;
1521         char b[BDEVNAME_SIZE];
1522
1523         bdev = open_by_devnum(dev, FMODE_READ|FMODE_WRITE);
1524         if (IS_ERR(bdev)) {
1525                 printk(KERN_ERR "md: could not open %s.\n",
1526                         __bdevname(dev, b));
1527                 return PTR_ERR(bdev);
1528         }
1529         err = bd_claim(bdev, shared ? (mdk_rdev_t *)lock_rdev : rdev);
1530         if (err) {
1531                 printk(KERN_ERR "md: could not bd_claim %s.\n",
1532                         bdevname(bdev, b));
1533                 blkdev_put(bdev);
1534                 return err;
1535         }
1536         if (!shared)
1537                 set_bit(AllReserved, &rdev->flags);
1538         rdev->bdev = bdev;
1539         return err;
1540 }
1541
1542 static void unlock_rdev(mdk_rdev_t *rdev)
1543 {
1544         struct block_device *bdev = rdev->bdev;
1545         rdev->bdev = NULL;
1546         if (!bdev)
1547                 MD_BUG();
1548         bd_release(bdev);
1549         blkdev_put(bdev);
1550 }
1551
1552 void md_autodetect_dev(dev_t dev);
1553
1554 static void export_rdev(mdk_rdev_t * rdev)
1555 {
1556         char b[BDEVNAME_SIZE];
1557         printk(KERN_INFO "md: export_rdev(%s)\n",
1558                 bdevname(rdev->bdev,b));
1559         if (rdev->mddev)
1560                 MD_BUG();
1561         free_disk_sb(rdev);
1562 #ifndef MODULE
1563         if (test_bit(AutoDetected, &rdev->flags))
1564                 md_autodetect_dev(rdev->bdev->bd_dev);
1565 #endif
1566         unlock_rdev(rdev);
1567         kobject_put(&rdev->kobj);
1568 }
1569
1570 static void kick_rdev_from_array(mdk_rdev_t * rdev)
1571 {
1572         unbind_rdev_from_array(rdev);
1573         export_rdev(rdev);
1574 }
1575
1576 static void export_array(mddev_t *mddev)
1577 {
1578         struct list_head *tmp;
1579         mdk_rdev_t *rdev;
1580
1581         rdev_for_each(rdev, tmp, mddev) {
1582                 if (!rdev->mddev) {
1583                         MD_BUG();
1584                         continue;
1585                 }
1586                 kick_rdev_from_array(rdev);
1587         }
1588         if (!list_empty(&mddev->disks))
1589                 MD_BUG();
1590         mddev->raid_disks = 0;
1591         mddev->major_version = 0;
1592 }
1593
1594 static void print_desc(mdp_disk_t *desc)
1595 {
1596         printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
1597                 desc->major,desc->minor,desc->raid_disk,desc->state);
1598 }
1599
1600 static void print_sb(mdp_super_t *sb)
1601 {
1602         int i;
1603
1604         printk(KERN_INFO 
1605                 "md:  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
1606                 sb->major_version, sb->minor_version, sb->patch_version,
1607                 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
1608                 sb->ctime);
1609         printk(KERN_INFO "md:     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
1610                 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
1611                 sb->md_minor, sb->layout, sb->chunk_size);
1612         printk(KERN_INFO "md:     UT:%08x ST:%d AD:%d WD:%d"
1613                 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
1614                 sb->utime, sb->state, sb->active_disks, sb->working_disks,
1615                 sb->failed_disks, sb->spare_disks,
1616                 sb->sb_csum, (unsigned long)sb->events_lo);
1617
1618         printk(KERN_INFO);
1619         for (i = 0; i < MD_SB_DISKS; i++) {
1620                 mdp_disk_t *desc;
1621
1622                 desc = sb->disks + i;
1623                 if (desc->number || desc->major || desc->minor ||
1624                     desc->raid_disk || (desc->state && (desc->state != 4))) {
1625                         printk("     D %2d: ", i);
1626                         print_desc(desc);
1627                 }
1628         }
1629         printk(KERN_INFO "md:     THIS: ");
1630         print_desc(&sb->this_disk);
1631
1632 }
1633
1634 static void print_rdev(mdk_rdev_t *rdev)
1635 {
1636         char b[BDEVNAME_SIZE];
1637         printk(KERN_INFO "md: rdev %s, SZ:%08llu F:%d S:%d DN:%u\n",
1638                 bdevname(rdev->bdev,b), (unsigned long long)rdev->size,
1639                 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
1640                 rdev->desc_nr);
1641         if (rdev->sb_loaded) {
1642                 printk(KERN_INFO "md: rdev superblock:\n");
1643                 print_sb((mdp_super_t*)page_address(rdev->sb_page));
1644         } else
1645                 printk(KERN_INFO "md: no rdev superblock!\n");
1646 }
1647
1648 static void md_print_devices(void)
1649 {
1650         struct list_head *tmp, *tmp2;
1651         mdk_rdev_t *rdev;
1652         mddev_t *mddev;
1653         char b[BDEVNAME_SIZE];
1654
1655         printk("\n");
1656         printk("md:     **********************************\n");
1657         printk("md:     * <COMPLETE RAID STATE PRINTOUT> *\n");
1658         printk("md:     **********************************\n");
1659         for_each_mddev(mddev, tmp) {
1660
1661                 if (mddev->bitmap)
1662                         bitmap_print_sb(mddev->bitmap);
1663                 else
1664                         printk("%s: ", mdname(mddev));
1665                 rdev_for_each(rdev, tmp2, mddev)
1666                         printk("<%s>", bdevname(rdev->bdev,b));
1667                 printk("\n");
1668
1669                 rdev_for_each(rdev, tmp2, mddev)
1670                         print_rdev(rdev);
1671         }
1672         printk("md:     **********************************\n");
1673         printk("\n");
1674 }
1675
1676
1677 static void sync_sbs(mddev_t * mddev, int nospares)
1678 {
1679         /* Update each superblock (in-memory image), but
1680          * if we are allowed to, skip spares which already
1681          * have the right event counter, or have one earlier
1682          * (which would mean they aren't being marked as dirty
1683          * with the rest of the array)
1684          */
1685         mdk_rdev_t *rdev;
1686         struct list_head *tmp;
1687
1688         rdev_for_each(rdev, tmp, mddev) {
1689                 if (rdev->sb_events == mddev->events ||
1690                     (nospares &&
1691                      rdev->raid_disk < 0 &&
1692                      (rdev->sb_events&1)==0 &&
1693                      rdev->sb_events+1 == mddev->events)) {
1694                         /* Don't update this superblock */
1695                         rdev->sb_loaded = 2;
1696                 } else {
1697                         super_types[mddev->major_version].
1698                                 sync_super(mddev, rdev);
1699                         rdev->sb_loaded = 1;
1700                 }
1701         }
1702 }
1703
1704 static void md_update_sb(mddev_t * mddev, int force_change)
1705 {
1706         struct list_head *tmp;
1707         mdk_rdev_t *rdev;
1708         int sync_req;
1709         int nospares = 0;
1710
1711         if (mddev->external)
1712                 return;
1713 repeat:
1714         spin_lock_irq(&mddev->write_lock);
1715
1716         set_bit(MD_CHANGE_PENDING, &mddev->flags);
1717         if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
1718                 force_change = 1;
1719         if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
1720                 /* just a clean<-> dirty transition, possibly leave spares alone,
1721                  * though if events isn't the right even/odd, we will have to do
1722                  * spares after all
1723                  */
1724                 nospares = 1;
1725         if (force_change)
1726                 nospares = 0;
1727         if (mddev->degraded)
1728                 /* If the array is degraded, then skipping spares is both
1729                  * dangerous and fairly pointless.
1730                  * Dangerous because a device that was removed from the array
1731                  * might have a event_count that still looks up-to-date,
1732                  * so it can be re-added without a resync.
1733                  * Pointless because if there are any spares to skip,
1734                  * then a recovery will happen and soon that array won't
1735                  * be degraded any more and the spare can go back to sleep then.
1736                  */
1737                 nospares = 0;
1738
1739         sync_req = mddev->in_sync;
1740         mddev->utime = get_seconds();
1741
1742         /* If this is just a dirty<->clean transition, and the array is clean
1743          * and 'events' is odd, we can roll back to the previous clean state */
1744         if (nospares
1745             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
1746             && (mddev->events & 1)
1747             && mddev->events != 1)
1748                 mddev->events--;
1749         else {
1750                 /* otherwise we have to go forward and ... */
1751                 mddev->events ++;
1752                 if (!mddev->in_sync || mddev->recovery_cp != MaxSector) { /* not clean */
1753                         /* .. if the array isn't clean, insist on an odd 'events' */
1754                         if ((mddev->events&1)==0) {
1755                                 mddev->events++;
1756                                 nospares = 0;
1757                         }
1758                 } else {
1759                         /* otherwise insist on an even 'events' (for clean states) */
1760                         if ((mddev->events&1)) {
1761                                 mddev->events++;
1762                                 nospares = 0;
1763                         }
1764                 }
1765         }
1766
1767         if (!mddev->events) {
1768                 /*
1769                  * oops, this 64-bit counter should never wrap.
1770                  * Either we are in around ~1 trillion A.C., assuming
1771                  * 1 reboot per second, or we have a bug:
1772                  */
1773                 MD_BUG();
1774                 mddev->events --;
1775         }
1776
1777         /*
1778          * do not write anything to disk if using
1779          * nonpersistent superblocks
1780          */
1781         if (!mddev->persistent) {
1782                 if (!mddev->external)
1783                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
1784
1785                 spin_unlock_irq(&mddev->write_lock);
1786                 wake_up(&mddev->sb_wait);
1787                 return;
1788         }
1789         sync_sbs(mddev, nospares);
1790         spin_unlock_irq(&mddev->write_lock);
1791
1792         dprintk(KERN_INFO 
1793                 "md: updating %s RAID superblock on device (in sync %d)\n",
1794                 mdname(mddev),mddev->in_sync);
1795
1796         bitmap_update_sb(mddev->bitmap);
1797         rdev_for_each(rdev, tmp, mddev) {
1798                 char b[BDEVNAME_SIZE];
1799                 dprintk(KERN_INFO "md: ");
1800                 if (rdev->sb_loaded != 1)
1801                         continue; /* no noise on spare devices */
1802                 if (test_bit(Faulty, &rdev->flags))
1803                         dprintk("(skipping faulty ");
1804
1805                 dprintk("%s ", bdevname(rdev->bdev,b));
1806                 if (!test_bit(Faulty, &rdev->flags)) {
1807                         md_super_write(mddev,rdev,
1808                                        rdev->sb_start, rdev->sb_size,
1809                                        rdev->sb_page);
1810                         dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
1811                                 bdevname(rdev->bdev,b),
1812                                 (unsigned long long)rdev->sb_start);
1813                         rdev->sb_events = mddev->events;
1814
1815                 } else
1816                         dprintk(")\n");
1817                 if (mddev->level == LEVEL_MULTIPATH)
1818                         /* only need to write one superblock... */
1819                         break;
1820         }
1821         md_super_wait(mddev);
1822         /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
1823
1824         spin_lock_irq(&mddev->write_lock);
1825         if (mddev->in_sync != sync_req ||
1826             test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
1827                 /* have to write it out again */
1828                 spin_unlock_irq(&mddev->write_lock);
1829                 goto repeat;
1830         }
1831         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
1832         spin_unlock_irq(&mddev->write_lock);
1833         wake_up(&mddev->sb_wait);
1834
1835 }
1836
1837 /* words written to sysfs files may, or may not, be \n terminated.
1838  * We want to accept with case. For this we use cmd_match.
1839  */
1840 static int cmd_match(const char *cmd, const char *str)
1841 {
1842         /* See if cmd, written into a sysfs file, matches
1843          * str.  They must either be the same, or cmd can
1844          * have a trailing newline
1845          */
1846         while (*cmd && *str && *cmd == *str) {
1847                 cmd++;
1848                 str++;
1849         }
1850         if (*cmd == '\n')
1851                 cmd++;
1852         if (*str || *cmd)
1853                 return 0;
1854         return 1;
1855 }
1856
1857 struct rdev_sysfs_entry {
1858         struct attribute attr;
1859         ssize_t (*show)(mdk_rdev_t *, char *);
1860         ssize_t (*store)(mdk_rdev_t *, const char *, size_t);
1861 };
1862
1863 static ssize_t
1864 state_show(mdk_rdev_t *rdev, char *page)
1865 {
1866         char *sep = "";
1867         size_t len = 0;
1868
1869         if (test_bit(Faulty, &rdev->flags)) {
1870                 len+= sprintf(page+len, "%sfaulty",sep);
1871                 sep = ",";
1872         }
1873         if (test_bit(In_sync, &rdev->flags)) {
1874                 len += sprintf(page+len, "%sin_sync",sep);
1875                 sep = ",";
1876         }
1877         if (test_bit(WriteMostly, &rdev->flags)) {
1878                 len += sprintf(page+len, "%swrite_mostly",sep);
1879                 sep = ",";
1880         }
1881         if (test_bit(Blocked, &rdev->flags)) {
1882                 len += sprintf(page+len, "%sblocked", sep);
1883                 sep = ",";
1884         }
1885         if (!test_bit(Faulty, &rdev->flags) &&
1886             !test_bit(In_sync, &rdev->flags)) {
1887                 len += sprintf(page+len, "%sspare", sep);
1888                 sep = ",";
1889         }
1890         return len+sprintf(page+len, "\n");
1891 }
1892
1893 static ssize_t
1894 state_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1895 {
1896         /* can write
1897          *  faulty  - simulates and error
1898          *  remove  - disconnects the device
1899          *  writemostly - sets write_mostly
1900          *  -writemostly - clears write_mostly
1901          *  blocked - sets the Blocked flag
1902          *  -blocked - clears the Blocked flag
1903          */
1904         int err = -EINVAL;
1905         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
1906                 md_error(rdev->mddev, rdev);
1907                 err = 0;
1908         } else if (cmd_match(buf, "remove")) {
1909                 if (rdev->raid_disk >= 0)
1910                         err = -EBUSY;
1911                 else {
1912                         mddev_t *mddev = rdev->mddev;
1913                         kick_rdev_from_array(rdev);
1914                         if (mddev->pers)
1915                                 md_update_sb(mddev, 1);
1916                         md_new_event(mddev);
1917                         err = 0;
1918                 }
1919         } else if (cmd_match(buf, "writemostly")) {
1920                 set_bit(WriteMostly, &rdev->flags);
1921                 err = 0;
1922         } else if (cmd_match(buf, "-writemostly")) {
1923                 clear_bit(WriteMostly, &rdev->flags);
1924                 err = 0;
1925         } else if (cmd_match(buf, "blocked")) {
1926                 set_bit(Blocked, &rdev->flags);
1927                 err = 0;
1928         } else if (cmd_match(buf, "-blocked")) {
1929                 clear_bit(Blocked, &rdev->flags);
1930                 wake_up(&rdev->blocked_wait);
1931                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
1932                 md_wakeup_thread(rdev->mddev->thread);
1933
1934                 err = 0;
1935         }
1936         if (!err)
1937                 sysfs_notify(&rdev->kobj, NULL, "state");
1938         return err ? err : len;
1939 }
1940 static struct rdev_sysfs_entry rdev_state =
1941 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
1942
1943 static ssize_t
1944 errors_show(mdk_rdev_t *rdev, char *page)
1945 {
1946         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
1947 }
1948
1949 static ssize_t
1950 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1951 {
1952         char *e;
1953         unsigned long n = simple_strtoul(buf, &e, 10);
1954         if (*buf && (*e == 0 || *e == '\n')) {
1955                 atomic_set(&rdev->corrected_errors, n);
1956                 return len;
1957         }
1958         return -EINVAL;
1959 }
1960 static struct rdev_sysfs_entry rdev_errors =
1961 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
1962
1963 static ssize_t
1964 slot_show(mdk_rdev_t *rdev, char *page)
1965 {
1966         if (rdev->raid_disk < 0)
1967                 return sprintf(page, "none\n");
1968         else
1969                 return sprintf(page, "%d\n", rdev->raid_disk);
1970 }
1971
1972 static ssize_t
1973 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1974 {
1975         char *e;
1976         int err;
1977         char nm[20];
1978         int slot = simple_strtoul(buf, &e, 10);
1979         if (strncmp(buf, "none", 4)==0)
1980                 slot = -1;
1981         else if (e==buf || (*e && *e!= '\n'))
1982                 return -EINVAL;
1983         if (rdev->mddev->pers && slot == -1) {
1984                 /* Setting 'slot' on an active array requires also
1985                  * updating the 'rd%d' link, and communicating
1986                  * with the personality with ->hot_*_disk.
1987                  * For now we only support removing
1988                  * failed/spare devices.  This normally happens automatically,
1989                  * but not when the metadata is externally managed.
1990                  */
1991                 if (rdev->raid_disk == -1)
1992                         return -EEXIST;
1993                 /* personality does all needed checks */
1994                 if (rdev->mddev->pers->hot_add_disk == NULL)
1995                         return -EINVAL;
1996                 err = rdev->mddev->pers->
1997                         hot_remove_disk(rdev->mddev, rdev->raid_disk);
1998                 if (err)
1999                         return err;
2000                 sprintf(nm, "rd%d", rdev->raid_disk);
2001                 sysfs_remove_link(&rdev->mddev->kobj, nm);
2002                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2003                 md_wakeup_thread(rdev->mddev->thread);
2004         } else if (rdev->mddev->pers) {
2005                 mdk_rdev_t *rdev2;
2006                 struct list_head *tmp;
2007                 /* Activating a spare .. or possibly reactivating
2008                  * if we every get bitmaps working here.
2009                  */
2010
2011                 if (rdev->raid_disk != -1)
2012                         return -EBUSY;
2013
2014                 if (rdev->mddev->pers->hot_add_disk == NULL)
2015                         return -EINVAL;
2016
2017                 rdev_for_each(rdev2, tmp, rdev->mddev)
2018                         if (rdev2->raid_disk == slot)
2019                                 return -EEXIST;
2020
2021                 rdev->raid_disk = slot;
2022                 if (test_bit(In_sync, &rdev->flags))
2023                         rdev->saved_raid_disk = slot;
2024                 else
2025                         rdev->saved_raid_disk = -1;
2026                 err = rdev->mddev->pers->
2027                         hot_add_disk(rdev->mddev, rdev);
2028                 if (err) {
2029                         rdev->raid_disk = -1;
2030                         return err;
2031                 } else
2032                         sysfs_notify(&rdev->kobj, NULL, "state");
2033                 sprintf(nm, "rd%d", rdev->raid_disk);
2034                 if (sysfs_create_link(&rdev->mddev->kobj, &rdev->kobj, nm))
2035                         printk(KERN_WARNING
2036                                "md: cannot register "
2037                                "%s for %s\n",
2038                                nm, mdname(rdev->mddev));
2039
2040                 /* don't wakeup anyone, leave that to userspace. */
2041         } else {
2042                 if (slot >= rdev->mddev->raid_disks)
2043                         return -ENOSPC;
2044                 rdev->raid_disk = slot;
2045                 /* assume it is working */
2046                 clear_bit(Faulty, &rdev->flags);
2047                 clear_bit(WriteMostly, &rdev->flags);
2048                 set_bit(In_sync, &rdev->flags);
2049                 sysfs_notify(&rdev->kobj, NULL, "state");
2050         }
2051         return len;
2052 }
2053
2054
2055 static struct rdev_sysfs_entry rdev_slot =
2056 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2057
2058 static ssize_t
2059 offset_show(mdk_rdev_t *rdev, char *page)
2060 {
2061         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2062 }
2063
2064 static ssize_t
2065 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2066 {
2067         char *e;
2068         unsigned long long offset = simple_strtoull(buf, &e, 10);
2069         if (e==buf || (*e && *e != '\n'))
2070                 return -EINVAL;
2071         if (rdev->mddev->pers && rdev->raid_disk >= 0)
2072                 return -EBUSY;
2073         if (rdev->size && rdev->mddev->external)
2074                 /* Must set offset before size, so overlap checks
2075                  * can be sane */
2076                 return -EBUSY;
2077         rdev->data_offset = offset;
2078         return len;
2079 }
2080
2081 static struct rdev_sysfs_entry rdev_offset =
2082 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2083
2084 static ssize_t
2085 rdev_size_show(mdk_rdev_t *rdev, char *page)
2086 {
2087         return sprintf(page, "%llu\n", (unsigned long long)rdev->size);
2088 }
2089
2090 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2091 {
2092         /* check if two start/length pairs overlap */
2093         if (s1+l1 <= s2)
2094                 return 0;
2095         if (s2+l2 <= s1)
2096                 return 0;
2097         return 1;
2098 }
2099
2100 static ssize_t
2101 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2102 {
2103         unsigned long long size;
2104         unsigned long long oldsize = rdev->size;
2105         mddev_t *my_mddev = rdev->mddev;
2106
2107         if (strict_strtoull(buf, 10, &size) < 0)
2108                 return -EINVAL;
2109         if (my_mddev->pers && rdev->raid_disk >= 0) {
2110                 if (my_mddev->persistent) {
2111                         size = super_types[my_mddev->major_version].
2112                                 rdev_size_change(rdev, size * 2);
2113                         if (!size)
2114                                 return -EBUSY;
2115                 } else if (!size) {
2116                         size = (rdev->bdev->bd_inode->i_size >> 10);
2117                         size -= rdev->data_offset/2;
2118                 }
2119         }
2120         if (size < my_mddev->size)
2121                 return -EINVAL; /* component must fit device */
2122
2123         rdev->size = size;
2124         if (size > oldsize && my_mddev->external) {
2125                 /* need to check that all other rdevs with the same ->bdev
2126                  * do not overlap.  We need to unlock the mddev to avoid
2127                  * a deadlock.  We have already changed rdev->size, and if
2128                  * we have to change it back, we will have the lock again.
2129                  */
2130                 mddev_t *mddev;
2131                 int overlap = 0;
2132                 struct list_head *tmp, *tmp2;
2133
2134                 mddev_unlock(my_mddev);
2135                 for_each_mddev(mddev, tmp) {
2136                         mdk_rdev_t *rdev2;
2137
2138                         mddev_lock(mddev);
2139                         rdev_for_each(rdev2, tmp2, mddev)
2140                                 if (test_bit(AllReserved, &rdev2->flags) ||
2141                                     (rdev->bdev == rdev2->bdev &&
2142                                      rdev != rdev2 &&
2143                                      overlaps(rdev->data_offset, rdev->size * 2,
2144                                               rdev2->data_offset,
2145                                               rdev2->size * 2))) {
2146                                         overlap = 1;
2147                                         break;
2148                                 }
2149                         mddev_unlock(mddev);
2150                         if (overlap) {
2151                                 mddev_put(mddev);
2152                                 break;
2153                         }
2154                 }
2155                 mddev_lock(my_mddev);
2156                 if (overlap) {
2157                         /* Someone else could have slipped in a size
2158                          * change here, but doing so is just silly.
2159                          * We put oldsize back because we *know* it is
2160                          * safe, and trust userspace not to race with
2161                          * itself
2162                          */
2163                         rdev->size = oldsize;
2164                         return -EBUSY;
2165                 }
2166         }
2167         return len;
2168 }
2169
2170 static struct rdev_sysfs_entry rdev_size =
2171 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2172
2173 static struct attribute *rdev_default_attrs[] = {
2174         &rdev_state.attr,
2175         &rdev_errors.attr,
2176         &rdev_slot.attr,
2177         &rdev_offset.attr,
2178         &rdev_size.attr,
2179         NULL,
2180 };
2181 static ssize_t
2182 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2183 {
2184         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2185         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2186         mddev_t *mddev = rdev->mddev;
2187         ssize_t rv;
2188
2189         if (!entry->show)
2190                 return -EIO;
2191
2192         rv = mddev ? mddev_lock(mddev) : -EBUSY;
2193         if (!rv) {
2194                 if (rdev->mddev == NULL)
2195                         rv = -EBUSY;
2196                 else
2197                         rv = entry->show(rdev, page);
2198                 mddev_unlock(mddev);
2199         }
2200         return rv;
2201 }
2202
2203 static ssize_t
2204 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
2205               const char *page, size_t length)
2206 {
2207         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2208         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2209         ssize_t rv;
2210         mddev_t *mddev = rdev->mddev;
2211
2212         if (!entry->store)
2213                 return -EIO;
2214         if (!capable(CAP_SYS_ADMIN))
2215                 return -EACCES;
2216         rv = mddev ? mddev_lock(mddev): -EBUSY;
2217         if (!rv) {
2218                 if (rdev->mddev == NULL)
2219                         rv = -EBUSY;
2220                 else
2221                         rv = entry->store(rdev, page, length);
2222                 mddev_unlock(mddev);
2223         }
2224         return rv;
2225 }
2226
2227 static void rdev_free(struct kobject *ko)
2228 {
2229         mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
2230         kfree(rdev);
2231 }
2232 static struct sysfs_ops rdev_sysfs_ops = {
2233         .show           = rdev_attr_show,
2234         .store          = rdev_attr_store,
2235 };
2236 static struct kobj_type rdev_ktype = {
2237         .release        = rdev_free,
2238         .sysfs_ops      = &rdev_sysfs_ops,
2239         .default_attrs  = rdev_default_attrs,
2240 };
2241
2242 /*
2243  * Import a device. If 'super_format' >= 0, then sanity check the superblock
2244  *
2245  * mark the device faulty if:
2246  *
2247  *   - the device is nonexistent (zero size)
2248  *   - the device has no valid superblock
2249  *
2250  * a faulty rdev _never_ has rdev->sb set.
2251  */
2252 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
2253 {
2254         char b[BDEVNAME_SIZE];
2255         int err;
2256         mdk_rdev_t *rdev;
2257         sector_t size;
2258
2259         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
2260         if (!rdev) {
2261                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
2262                 return ERR_PTR(-ENOMEM);
2263         }
2264
2265         if ((err = alloc_disk_sb(rdev)))
2266                 goto abort_free;
2267
2268         err = lock_rdev(rdev, newdev, super_format == -2);
2269         if (err)
2270                 goto abort_free;
2271
2272         kobject_init(&rdev->kobj, &rdev_ktype);
2273
2274         rdev->desc_nr = -1;
2275         rdev->saved_raid_disk = -1;
2276         rdev->raid_disk = -1;
2277         rdev->flags = 0;
2278         rdev->data_offset = 0;
2279         rdev->sb_events = 0;
2280         atomic_set(&rdev->nr_pending, 0);
2281         atomic_set(&rdev->read_errors, 0);
2282         atomic_set(&rdev->corrected_errors, 0);
2283
2284         size = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
2285         if (!size) {
2286                 printk(KERN_WARNING 
2287                         "md: %s has zero or unknown size, marking faulty!\n",
2288                         bdevname(rdev->bdev,b));
2289                 err = -EINVAL;
2290                 goto abort_free;
2291         }
2292
2293         if (super_format >= 0) {
2294                 err = super_types[super_format].
2295                         load_super(rdev, NULL, super_minor);
2296                 if (err == -EINVAL) {
2297                         printk(KERN_WARNING
2298                                 "md: %s does not have a valid v%d.%d "
2299                                "superblock, not importing!\n",
2300                                 bdevname(rdev->bdev,b),
2301                                super_format, super_minor);
2302                         goto abort_free;
2303                 }
2304                 if (err < 0) {
2305                         printk(KERN_WARNING 
2306                                 "md: could not read %s's sb, not importing!\n",
2307                                 bdevname(rdev->bdev,b));
2308                         goto abort_free;
2309                 }
2310         }
2311
2312         INIT_LIST_HEAD(&rdev->same_set);
2313         init_waitqueue_head(&rdev->blocked_wait);
2314
2315         return rdev;
2316
2317 abort_free:
2318         if (rdev->sb_page) {
2319                 if (rdev->bdev)
2320                         unlock_rdev(rdev);
2321                 free_disk_sb(rdev);
2322         }
2323         kfree(rdev);
2324         return ERR_PTR(err);
2325 }
2326
2327 /*
2328  * Check a full RAID array for plausibility
2329  */
2330
2331
2332 static void analyze_sbs(mddev_t * mddev)
2333 {
2334         int i;
2335         struct list_head *tmp;
2336         mdk_rdev_t *rdev, *freshest;
2337         char b[BDEVNAME_SIZE];
2338
2339         freshest = NULL;
2340         rdev_for_each(rdev, tmp, mddev)
2341                 switch (super_types[mddev->major_version].
2342                         load_super(rdev, freshest, mddev->minor_version)) {
2343                 case 1:
2344                         freshest = rdev;
2345                         break;
2346                 case 0:
2347                         break;
2348                 default:
2349                         printk( KERN_ERR \
2350                                 "md: fatal superblock inconsistency in %s"
2351                                 " -- removing from array\n", 
2352                                 bdevname(rdev->bdev,b));
2353                         kick_rdev_from_array(rdev);
2354                 }
2355
2356
2357         super_types[mddev->major_version].
2358                 validate_super(mddev, freshest);
2359
2360         i = 0;
2361         rdev_for_each(rdev, tmp, mddev) {
2362                 if (rdev != freshest)
2363                         if (super_types[mddev->major_version].
2364                             validate_super(mddev, rdev)) {
2365                                 printk(KERN_WARNING "md: kicking non-fresh %s"
2366                                         " from array!\n",
2367                                         bdevname(rdev->bdev,b));
2368                                 kick_rdev_from_array(rdev);
2369                                 continue;
2370                         }
2371                 if (mddev->level == LEVEL_MULTIPATH) {
2372                         rdev->desc_nr = i++;
2373                         rdev->raid_disk = rdev->desc_nr;
2374                         set_bit(In_sync, &rdev->flags);
2375                 } else if (rdev->raid_disk >= mddev->raid_disks) {
2376                         rdev->raid_disk = -1;
2377                         clear_bit(In_sync, &rdev->flags);
2378                 }
2379         }
2380
2381
2382
2383         if (mddev->recovery_cp != MaxSector &&
2384             mddev->level >= 1)
2385                 printk(KERN_ERR "md: %s: raid array is not clean"
2386                        " -- starting background reconstruction\n",
2387                        mdname(mddev));
2388
2389 }
2390
2391 static void md_safemode_timeout(unsigned long data);
2392
2393 static ssize_t
2394 safe_delay_show(mddev_t *mddev, char *page)
2395 {
2396         int msec = (mddev->safemode_delay*1000)/HZ;
2397         return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
2398 }
2399 static ssize_t
2400 safe_delay_store(mddev_t *mddev, const char *cbuf, size_t len)
2401 {
2402         int scale=1;
2403         int dot=0;
2404         int i;
2405         unsigned long msec;
2406         char buf[30];
2407         char *e;
2408         /* remove a period, and count digits after it */
2409         if (len >= sizeof(buf))
2410                 return -EINVAL;
2411         strlcpy(buf, cbuf, len);
2412         buf[len] = 0;
2413         for (i=0; i<len; i++) {
2414                 if (dot) {
2415                         if (isdigit(buf[i])) {
2416                                 buf[i-1] = buf[i];
2417                                 scale *= 10;
2418                         }
2419                         buf[i] = 0;
2420                 } else if (buf[i] == '.') {
2421                         dot=1;
2422                         buf[i] = 0;
2423                 }
2424         }
2425         msec = simple_strtoul(buf, &e, 10);
2426         if (e == buf || (*e && *e != '\n'))
2427                 return -EINVAL;
2428         msec = (msec * 1000) / scale;
2429         if (msec == 0)
2430                 mddev->safemode_delay = 0;
2431         else {
2432                 unsigned long old_delay = mddev->safemode_delay;
2433                 mddev->safemode_delay = (msec*HZ)/1000;
2434                 if (mddev->safemode_delay == 0)
2435                         mddev->safemode_delay = 1;
2436                 if (mddev->safemode_delay < old_delay)
2437                         md_safemode_timeout((unsigned long)mddev);
2438         }
2439         return len;
2440 }
2441 static struct md_sysfs_entry md_safe_delay =
2442 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
2443
2444 static ssize_t
2445 level_show(mddev_t *mddev, char *page)
2446 {
2447         struct mdk_personality *p = mddev->pers;
2448         if (p)
2449                 return sprintf(page, "%s\n", p->name);
2450         else if (mddev->clevel[0])
2451                 return sprintf(page, "%s\n", mddev->clevel);
2452         else if (mddev->level != LEVEL_NONE)
2453                 return sprintf(page, "%d\n", mddev->level);
2454         else
2455                 return 0;
2456 }
2457
2458 static ssize_t
2459 level_store(mddev_t *mddev, const char *buf, size_t len)
2460 {
2461         ssize_t rv = len;
2462         if (mddev->pers)
2463                 return -EBUSY;
2464         if (len == 0)
2465                 return 0;
2466         if (len >= sizeof(mddev->clevel))
2467                 return -ENOSPC;
2468         strncpy(mddev->clevel, buf, len);
2469         if (mddev->clevel[len-1] == '\n')
2470                 len--;
2471         mddev->clevel[len] = 0;
2472         mddev->level = LEVEL_NONE;
2473         return rv;
2474 }
2475
2476 static struct md_sysfs_entry md_level =
2477 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
2478
2479
2480 static ssize_t
2481 layout_show(mddev_t *mddev, char *page)
2482 {
2483         /* just a number, not meaningful for all levels */
2484         if (mddev->reshape_position != MaxSector &&
2485             mddev->layout != mddev->new_layout)
2486                 return sprintf(page, "%d (%d)\n",
2487                                mddev->new_layout, mddev->layout);
2488         return sprintf(page, "%d\n", mddev->layout);
2489 }
2490
2491 static ssize_t
2492 layout_store(mddev_t *mddev, const char *buf, size_t len)
2493 {
2494         char *e;
2495         unsigned long n = simple_strtoul(buf, &e, 10);
2496
2497         if (!*buf || (*e && *e != '\n'))
2498                 return -EINVAL;
2499
2500         if (mddev->pers)
2501                 return -EBUSY;
2502         if (mddev->reshape_position != MaxSector)
2503                 mddev->new_layout = n;
2504         else
2505                 mddev->layout = n;
2506         return len;
2507 }
2508 static struct md_sysfs_entry md_layout =
2509 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
2510
2511
2512 static ssize_t
2513 raid_disks_show(mddev_t *mddev, char *page)
2514 {
2515         if (mddev->raid_disks == 0)
2516                 return 0;
2517         if (mddev->reshape_position != MaxSector &&
2518             mddev->delta_disks != 0)
2519                 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
2520                                mddev->raid_disks - mddev->delta_disks);
2521         return sprintf(page, "%d\n", mddev->raid_disks);
2522 }
2523
2524 static int update_raid_disks(mddev_t *mddev, int raid_disks);
2525
2526 static ssize_t
2527 raid_disks_store(mddev_t *mddev, const char *buf, size_t len)
2528 {
2529         char *e;
2530         int rv = 0;
2531         unsigned long n = simple_strtoul(buf, &e, 10);
2532
2533         if (!*buf || (*e && *e != '\n'))
2534                 return -EINVAL;
2535
2536         if (mddev->pers)
2537                 rv = update_raid_disks(mddev, n);
2538         else if (mddev->reshape_position != MaxSector) {
2539                 int olddisks = mddev->raid_disks - mddev->delta_disks;
2540                 mddev->delta_disks = n - olddisks;
2541                 mddev->raid_disks = n;
2542         } else
2543                 mddev->raid_disks = n;
2544         return rv ? rv : len;
2545 }
2546 static struct md_sysfs_entry md_raid_disks =
2547 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
2548
2549 static ssize_t
2550 chunk_size_show(mddev_t *mddev, char *page)
2551 {
2552         if (mddev->reshape_position != MaxSector &&
2553             mddev->chunk_size != mddev->new_chunk)
2554                 return sprintf(page, "%d (%d)\n", mddev->new_chunk,
2555                                mddev->chunk_size);
2556         return sprintf(page, "%d\n", mddev->chunk_size);
2557 }
2558
2559 static ssize_t
2560 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
2561 {
2562         /* can only set chunk_size if array is not yet active */
2563         char *e;
2564         unsigned long n = simple_strtoul(buf, &e, 10);
2565
2566         if (!*buf || (*e && *e != '\n'))
2567                 return -EINVAL;
2568
2569         if (mddev->pers)
2570                 return -EBUSY;
2571         else if (mddev->reshape_position != MaxSector)
2572                 mddev->new_chunk = n;
2573         else
2574                 mddev->chunk_size = n;
2575         return len;
2576 }
2577 static struct md_sysfs_entry md_chunk_size =
2578 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
2579
2580 static ssize_t
2581 resync_start_show(mddev_t *mddev, char *page)
2582 {
2583         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
2584 }
2585
2586 static ssize_t
2587 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
2588 {
2589         char *e;
2590         unsigned long long n = simple_strtoull(buf, &e, 10);
2591
2592         if (mddev->pers)
2593                 return -EBUSY;
2594         if (!*buf || (*e && *e != '\n'))
2595                 return -EINVAL;
2596
2597         mddev->recovery_cp = n;
2598         return len;
2599 }
2600 static struct md_sysfs_entry md_resync_start =
2601 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
2602
2603 /*
2604  * The array state can be:
2605  *
2606  * clear
2607  *     No devices, no size, no level
2608  *     Equivalent to STOP_ARRAY ioctl
2609  * inactive
2610  *     May have some settings, but array is not active
2611  *        all IO results in error
2612  *     When written, doesn't tear down array, but just stops it
2613  * suspended (not supported yet)
2614  *     All IO requests will block. The array can be reconfigured.
2615  *     Writing this, if accepted, will block until array is quiescent
2616  * readonly
2617  *     no resync can happen.  no superblocks get written.
2618  *     write requests fail
2619  * read-auto
2620  *     like readonly, but behaves like 'clean' on a write request.
2621  *
2622  * clean - no pending writes, but otherwise active.
2623  *     When written to inactive array, starts without resync
2624  *     If a write request arrives then
2625  *       if metadata is known, mark 'dirty' and switch to 'active'.
2626  *       if not known, block and switch to write-pending
2627  *     If written to an active array that has pending writes, then fails.
2628  * active
2629  *     fully active: IO and resync can be happening.
2630  *     When written to inactive array, starts with resync
2631  *
2632  * write-pending
2633  *     clean, but writes are blocked waiting for 'active' to be written.
2634  *
2635  * active-idle
2636  *     like active, but no writes have been seen for a while (100msec).
2637  *
2638  */
2639 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
2640                    write_pending, active_idle, bad_word};
2641 static char *array_states[] = {
2642         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
2643         "write-pending", "active-idle", NULL };
2644
2645 static int match_word(const char *word, char **list)
2646 {
2647         int n;
2648         for (n=0; list[n]; n++)
2649                 if (cmd_match(word, list[n]))
2650                         break;
2651         return n;
2652 }
2653
2654 static ssize_t
2655 array_state_show(mddev_t *mddev, char *page)
2656 {
2657         enum array_state st = inactive;
2658
2659         if (mddev->pers)
2660                 switch(mddev->ro) {
2661                 case 1:
2662                         st = readonly;
2663                         break;
2664                 case 2:
2665                         st = read_auto;
2666                         break;
2667                 case 0:
2668                         if (mddev->in_sync)
2669                                 st = clean;
2670                         else if (test_bit(MD_CHANGE_CLEAN, &mddev->flags))
2671                                 st = write_pending;
2672                         else if (mddev->safemode)
2673                                 st = active_idle;
2674                         else
2675                                 st = active;
2676                 }
2677         else {
2678                 if (list_empty(&mddev->disks) &&
2679                     mddev->raid_disks == 0 &&
2680                     mddev->size == 0)
2681                         st = clear;
2682                 else
2683                         st = inactive;
2684         }
2685         return sprintf(page, "%s\n", array_states[st]);
2686 }
2687
2688 static int do_md_stop(mddev_t * mddev, int ro, int is_open);
2689 static int do_md_run(mddev_t * mddev);
2690 static int restart_array(mddev_t *mddev);
2691
2692 static ssize_t
2693 array_state_store(mddev_t *mddev, const char *buf, size_t len)
2694 {
2695         int err = -EINVAL;
2696         enum array_state st = match_word(buf, array_states);
2697         switch(st) {
2698         case bad_word:
2699                 break;
2700         case clear:
2701                 /* stopping an active array */
2702                 if (atomic_read(&mddev->openers) > 0)
2703                         return -EBUSY;
2704                 err = do_md_stop(mddev, 0, 0);
2705                 break;
2706         case inactive:
2707                 /* stopping an active array */
2708                 if (mddev->pers) {
2709                         if (atomic_read(&mddev->openers) > 0)
2710                                 return -EBUSY;
2711                         err = do_md_stop(mddev, 2, 0);
2712                 } else
2713                         err = 0; /* already inactive */
2714                 break;
2715         case suspended:
2716                 break; /* not supported yet */
2717         case readonly:
2718                 if (mddev->pers)
2719                         err = do_md_stop(mddev, 1, 0);
2720                 else {
2721                         mddev->ro = 1;
2722                         set_disk_ro(mddev->gendisk, 1);
2723                         err = do_md_run(mddev);
2724                 }
2725                 break;
2726         case read_auto:
2727                 if (mddev->pers) {
2728                         if (mddev->ro == 0)
2729                                 err = do_md_stop(mddev, 1, 0);
2730                         else if (mddev->ro == 1)
2731                                 err = restart_array(mddev);
2732                         if (err == 0) {
2733                                 mddev->ro = 2;
2734                                 set_disk_ro(mddev->gendisk, 0);
2735                         }
2736                 } else {
2737                         mddev->ro = 2;
2738                         err = do_md_run(mddev);
2739                 }
2740                 break;
2741         case clean:
2742                 if (mddev->pers) {
2743                         restart_array(mddev);
2744                         spin_lock_irq(&mddev->write_lock);
2745                         if (atomic_read(&mddev->writes_pending) == 0) {
2746                                 if (mddev->in_sync == 0) {
2747                                         mddev->in_sync = 1;
2748                                         if (mddev->safemode == 1)
2749                                                 mddev->safemode = 0;
2750                                         if (mddev->persistent)
2751                                                 set_bit(MD_CHANGE_CLEAN,
2752                                                         &mddev->flags);
2753                                 }
2754                                 err = 0;
2755                         } else
2756                                 err = -EBUSY;
2757                         spin_unlock_irq(&mddev->write_lock);
2758                 } else {
2759                         mddev->ro = 0;
2760                         mddev->recovery_cp = MaxSector;
2761                         err = do_md_run(mddev);
2762                 }
2763                 break;
2764         case active:
2765                 if (mddev->pers) {
2766                         restart_array(mddev);
2767                         if (mddev->external)
2768                                 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2769                         wake_up(&mddev->sb_wait);
2770                         err = 0;
2771                 } else {
2772                         mddev->ro = 0;
2773                         set_disk_ro(mddev->gendisk, 0);
2774                         err = do_md_run(mddev);
2775                 }
2776                 break;
2777         case write_pending:
2778         case active_idle:
2779                 /* these cannot be set */
2780                 break;
2781         }
2782         if (err)
2783                 return err;
2784         else {
2785                 sysfs_notify(&mddev->kobj, NULL, "array_state");
2786                 return len;
2787         }
2788 }
2789 static struct md_sysfs_entry md_array_state =
2790 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
2791
2792 static ssize_t
2793 null_show(mddev_t *mddev, char *page)
2794 {
2795         return -EINVAL;
2796 }
2797
2798 static ssize_t
2799 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
2800 {
2801         /* buf must be %d:%d\n? giving major and minor numbers */
2802         /* The new device is added to the array.
2803          * If the array has a persistent superblock, we read the
2804          * superblock to initialise info and check validity.
2805          * Otherwise, only checking done is that in bind_rdev_to_array,
2806          * which mainly checks size.
2807          */
2808         char *e;
2809         int major = simple_strtoul(buf, &e, 10);
2810         int minor;
2811         dev_t dev;
2812         mdk_rdev_t *rdev;
2813         int err;
2814
2815         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
2816                 return -EINVAL;
2817         minor = simple_strtoul(e+1, &e, 10);
2818         if (*e && *e != '\n')
2819                 return -EINVAL;
2820         dev = MKDEV(major, minor);
2821         if (major != MAJOR(dev) ||
2822             minor != MINOR(dev))
2823                 return -EOVERFLOW;
2824
2825
2826         if (mddev->persistent) {
2827                 rdev = md_import_device(dev, mddev->major_version,
2828                                         mddev->minor_version);
2829                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
2830                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
2831                                                        mdk_rdev_t, same_set);
2832                         err = super_types[mddev->major_version]
2833                                 .load_super(rdev, rdev0, mddev->minor_version);
2834                         if (err < 0)
2835                                 goto out;
2836                 }
2837         } else if (mddev->external)
2838                 rdev = md_import_device(dev, -2, -1);
2839         else
2840                 rdev = md_import_device(dev, -1, -1);
2841
2842         if (IS_ERR(rdev))
2843                 return PTR_ERR(rdev);
2844         err = bind_rdev_to_array(rdev, mddev);
2845  out:
2846         if (err)
2847                 export_rdev(rdev);
2848         return err ? err : len;
2849 }
2850
2851 static struct md_sysfs_entry md_new_device =
2852 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
2853
2854 static ssize_t
2855 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
2856 {
2857         char *end;
2858         unsigned long chunk, end_chunk;
2859
2860         if (!mddev->bitmap)
2861                 goto out;
2862         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
2863         while (*buf) {
2864                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
2865                 if (buf == end) break;
2866                 if (*end == '-') { /* range */
2867                         buf = end + 1;
2868                         end_chunk = simple_strtoul(buf, &end, 0);
2869                         if (buf == end) break;
2870                 }
2871                 if (*end && !isspace(*end)) break;
2872                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
2873                 buf = end;
2874                 while (isspace(*buf)) buf++;
2875         }
2876         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
2877 out:
2878         return len;
2879 }
2880
2881 static struct md_sysfs_entry md_bitmap =
2882 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
2883
2884 static ssize_t
2885 size_show(mddev_t *mddev, char *page)
2886 {
2887         return sprintf(page, "%llu\n", (unsigned long long)mddev->size);
2888 }
2889
2890 static int update_size(mddev_t *mddev, sector_t num_sectors);
2891
2892 static ssize_t
2893 size_store(mddev_t *mddev, const char *buf, size_t len)
2894 {
2895         /* If array is inactive, we can reduce the component size, but
2896          * not increase it (except from 0).
2897          * If array is active, we can try an on-line resize
2898          */
2899         char *e;
2900         int err = 0;
2901         unsigned long long size = simple_strtoull(buf, &e, 10);
2902         if (!*buf || *buf == '\n' ||
2903             (*e && *e != '\n'))
2904                 return -EINVAL;
2905
2906         if (mddev->pers) {
2907                 err = update_size(mddev, size * 2);
2908                 md_update_sb(mddev, 1);
2909         } else {
2910                 if (mddev->size == 0 ||
2911                     mddev->size > size)
2912                         mddev->size = size;
2913                 else
2914                         err = -ENOSPC;
2915         }
2916         return err ? err : len;
2917 }
2918
2919 static struct md_sysfs_entry md_size =
2920 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
2921
2922
2923 /* Metdata version.
2924  * This is one of
2925  *   'none' for arrays with no metadata (good luck...)
2926  *   'external' for arrays with externally managed metadata,
2927  * or N.M for internally known formats
2928  */
2929 static ssize_t
2930 metadata_show(mddev_t *mddev, char *page)
2931 {
2932         if (mddev->persistent)
2933                 return sprintf(page, "%d.%d\n",
2934                                mddev->major_version, mddev->minor_version);
2935         else if (mddev->external)
2936                 return sprintf(page, "external:%s\n", mddev->metadata_type);
2937         else
2938                 return sprintf(page, "none\n");
2939 }
2940
2941 static ssize_t
2942 metadata_store(mddev_t *mddev, const char *buf, size_t len)
2943 {
2944         int major, minor;
2945         char *e;
2946         /* Changing the details of 'external' metadata is
2947          * always permitted.  Otherwise there must be
2948          * no devices attached to the array.
2949          */
2950         if (mddev->external && strncmp(buf, "external:", 9) == 0)
2951                 ;
2952         else if (!list_empty(&mddev->disks))
2953                 return -EBUSY;
2954
2955         if (cmd_match(buf, "none")) {
2956                 mddev->persistent = 0;
2957                 mddev->external = 0;
2958                 mddev->major_version = 0;
2959                 mddev->minor_version = 90;
2960                 return len;
2961         }
2962         if (strncmp(buf, "external:", 9) == 0) {
2963                 size_t namelen = len-9;
2964                 if (namelen >= sizeof(mddev->metadata_type))
2965                         namelen = sizeof(mddev->metadata_type)-1;
2966                 strncpy(mddev->metadata_type, buf+9, namelen);
2967                 mddev->metadata_type[namelen] = 0;
2968                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
2969                         mddev->metadata_type[--namelen] = 0;
2970                 mddev->persistent = 0;
2971                 mddev->external = 1;
2972                 mddev->major_version = 0;
2973                 mddev->minor_version = 90;
2974                 return len;
2975         }
2976         major = simple_strtoul(buf, &e, 10);
2977         if (e==buf || *e != '.')
2978                 return -EINVAL;
2979         buf = e+1;
2980         minor = simple_strtoul(buf, &e, 10);
2981         if (e==buf || (*e && *e != '\n') )
2982                 return -EINVAL;
2983         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
2984                 return -ENOENT;
2985         mddev->major_version = major;
2986         mddev->minor_version = minor;
2987         mddev->persistent = 1;
2988         mddev->external = 0;
2989         return len;
2990 }
2991
2992 static struct md_sysfs_entry md_metadata =
2993 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
2994
2995 static ssize_t
2996 action_show(mddev_t *mddev, char *page)
2997 {
2998         char *type = "idle";
2999         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3000             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
3001                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
3002                         type = "reshape";
3003                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
3004                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
3005                                 type = "resync";
3006                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
3007                                 type = "check";
3008                         else
3009                                 type = "repair";
3010                 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
3011                         type = "recover";
3012         }
3013         return sprintf(page, "%s\n", type);
3014 }
3015
3016 static ssize_t
3017 action_store(mddev_t *mddev, const char *page, size_t len)
3018 {
3019         if (!mddev->pers || !mddev->pers->sync_request)
3020                 return -EINVAL;
3021
3022         if (cmd_match(page, "idle")) {
3023                 if (mddev->sync_thread) {
3024                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3025                         md_unregister_thread(mddev->sync_thread);
3026                         mddev->sync_thread = NULL;
3027                         mddev->recovery = 0;
3028                 }
3029         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3030                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
3031                 return -EBUSY;
3032         else if (cmd_match(page, "resync"))
3033                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3034         else if (cmd_match(page, "recover")) {
3035                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
3036                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3037         } else if (cmd_match(page, "reshape")) {
3038                 int err;
3039                 if (mddev->pers->start_reshape == NULL)
3040                         return -EINVAL;
3041                 err = mddev->pers->start_reshape(mddev);
3042                 if (err)
3043                         return err;
3044                 sysfs_notify(&mddev->kobj, NULL, "degraded");
3045         } else {
3046                 if (cmd_match(page, "check"))
3047                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3048                 else if (!cmd_match(page, "repair"))
3049                         return -EINVAL;
3050                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
3051                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3052         }
3053         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3054         md_wakeup_thread(mddev->thread);
3055         sysfs_notify(&mddev->kobj, NULL, "sync_action");
3056         return len;
3057 }
3058
3059 static ssize_t
3060 mismatch_cnt_show(mddev_t *mddev, char *page)
3061 {
3062         return sprintf(page, "%llu\n",
3063                        (unsigned long long) mddev->resync_mismatches);
3064 }
3065
3066 static struct md_sysfs_entry md_scan_mode =
3067 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
3068
3069
3070 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
3071
3072 static ssize_t
3073 sync_min_show(mddev_t *mddev, char *page)
3074 {
3075         return sprintf(page, "%d (%s)\n", speed_min(mddev),
3076                        mddev->sync_speed_min ? "local": "system");
3077 }
3078
3079 static ssize_t
3080 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
3081 {
3082         int min;
3083         char *e;
3084         if (strncmp(buf, "system", 6)==0) {
3085                 mddev->sync_speed_min = 0;
3086                 return len;
3087         }
3088         min = simple_strtoul(buf, &e, 10);
3089         if (buf == e || (*e && *e != '\n') || min <= 0)
3090                 return -EINVAL;
3091         mddev->sync_speed_min = min;
3092         return len;
3093 }
3094
3095 static struct md_sysfs_entry md_sync_min =
3096 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
3097
3098 static ssize_t
3099 sync_max_show(mddev_t *mddev, char *page)
3100 {
3101         return sprintf(page, "%d (%s)\n", speed_max(mddev),
3102                        mddev->sync_speed_max ? "local": "system");
3103 }
3104
3105 static ssize_t
3106 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
3107 {
3108         int max;
3109         char *e;
3110         if (strncmp(buf, "system", 6)==0) {
3111                 mddev->sync_speed_max = 0;
3112                 return len;
3113         }
3114         max = simple_strtoul(buf, &e, 10);
3115         if (buf == e || (*e && *e != '\n') || max <= 0)
3116                 return -EINVAL;
3117         mddev->sync_speed_max = max;
3118         return len;
3119 }
3120
3121 static struct md_sysfs_entry md_sync_max =
3122 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
3123
3124 static ssize_t
3125 degraded_show(mddev_t *mddev, char *page)
3126 {
3127         return sprintf(page, "%d\n", mddev->degraded);
3128 }
3129 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
3130
3131 static ssize_t
3132 sync_force_parallel_show(mddev_t *mddev, char *page)
3133 {
3134         return sprintf(page, "%d\n", mddev->parallel_resync);
3135 }
3136
3137 static ssize_t
3138 sync_force_parallel_store(mddev_t *mddev, const char *buf, size_t len)
3139 {
3140         long n;
3141
3142         if (strict_strtol(buf, 10, &n))
3143                 return -EINVAL;
3144
3145         if (n != 0 && n != 1)
3146                 return -EINVAL;
3147
3148         mddev->parallel_resync = n;
3149
3150         if (mddev->sync_thread)
3151                 wake_up(&resync_wait);
3152
3153         return len;
3154 }
3155
3156 /* force parallel resync, even with shared block devices */
3157 static struct md_sysfs_entry md_sync_force_parallel =
3158 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
3159        sync_force_parallel_show, sync_force_parallel_store);
3160
3161 static ssize_t
3162 sync_speed_show(mddev_t *mddev, char *page)
3163 {
3164         unsigned long resync, dt, db;
3165         resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
3166         dt = (jiffies - mddev->resync_mark) / HZ;
3167         if (!dt) dt++;
3168         db = resync - mddev->resync_mark_cnt;
3169         return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
3170 }
3171
3172 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
3173
3174 static ssize_t
3175 sync_completed_show(mddev_t *mddev, char *page)
3176 {
3177         unsigned long max_blocks, resync;
3178
3179         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
3180                 max_blocks = mddev->resync_max_sectors;
3181         else
3182                 max_blocks = mddev->size << 1;
3183
3184         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
3185         return sprintf(page, "%lu / %lu\n", resync, max_blocks);
3186 }
3187
3188 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
3189
3190 static ssize_t
3191 min_sync_show(mddev_t *mddev, char *page)
3192 {
3193         return sprintf(page, "%llu\n",
3194                        (unsigned long long)mddev->resync_min);
3195 }
3196 static ssize_t
3197 min_sync_store(mddev_t *mddev, const char *buf, size_t len)
3198 {
3199         unsigned long long min;
3200         if (strict_strtoull(buf, 10, &min))
3201                 return -EINVAL;
3202         if (min > mddev->resync_max)
3203                 return -EINVAL;
3204         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3205                 return -EBUSY;
3206
3207         /* Must be a multiple of chunk_size */
3208         if (mddev->chunk_size) {
3209                 if (min & (sector_t)((mddev->chunk_size>>9)-1))
3210                         return -EINVAL;
3211         }
3212         mddev->resync_min = min;
3213
3214         return len;
3215 }
3216
3217 static struct md_sysfs_entry md_min_sync =
3218 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
3219
3220 static ssize_t
3221 max_sync_show(mddev_t *mddev, char *page)
3222 {
3223         if (mddev->resync_max == MaxSector)
3224                 return sprintf(page, "max\n");
3225         else
3226                 return sprintf(page, "%llu\n",
3227                                (unsigned long long)mddev->resync_max);
3228 }
3229 static ssize_t
3230 max_sync_store(mddev_t *mddev, const char *buf, size_t len)
3231 {
3232         if (strncmp(buf, "max", 3) == 0)
3233                 mddev->resync_max = MaxSector;
3234         else {
3235                 unsigned long long max;
3236                 if (strict_strtoull(buf, 10, &max))
3237                         return -EINVAL;
3238                 if (max < mddev->resync_min)
3239                         return -EINVAL;
3240                 if (max < mddev->resync_max &&
3241                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3242                         return -EBUSY;
3243
3244                 /* Must be a multiple of chunk_size */
3245                 if (mddev->chunk_size) {
3246                         if (max & (sector_t)((mddev->chunk_size>>9)-1))
3247                                 return -EINVAL;
3248                 }
3249                 mddev->resync_max = max;
3250         }
3251         wake_up(&mddev->recovery_wait);
3252         return len;
3253 }
3254
3255 static struct md_sysfs_entry md_max_sync =
3256 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
3257
3258 static ssize_t
3259 suspend_lo_show(mddev_t *mddev, char *page)
3260 {
3261         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
3262 }
3263
3264 static ssize_t
3265 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
3266 {
3267         char *e;
3268         unsigned long long new = simple_strtoull(buf, &e, 10);
3269
3270         if (mddev->pers->quiesce == NULL)
3271                 return -EINVAL;
3272         if (buf == e || (*e && *e != '\n'))
3273                 return -EINVAL;
3274         if (new >= mddev->suspend_hi ||
3275             (new > mddev->suspend_lo && new < mddev->suspend_hi)) {
3276                 mddev->suspend_lo = new;
3277                 mddev->pers->quiesce(mddev, 2);
3278                 return len;
3279         } else
3280                 return -EINVAL;
3281 }
3282 static struct md_sysfs_entry md_suspend_lo =
3283 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
3284
3285
3286 static ssize_t
3287 suspend_hi_show(mddev_t *mddev, char *page)
3288 {
3289         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
3290 }
3291
3292 static ssize_t
3293 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
3294 {
3295         char *e;
3296         unsigned long long new = simple_strtoull(buf, &e, 10);
3297
3298         if (mddev->pers->quiesce == NULL)
3299                 return -EINVAL;
3300         if (buf == e || (*e && *e != '\n'))
3301                 return -EINVAL;
3302         if ((new <= mddev->suspend_lo && mddev->suspend_lo >= mddev->suspend_hi) ||
3303             (new > mddev->suspend_lo && new > mddev->suspend_hi)) {
3304                 mddev->suspend_hi = new;
3305                 mddev->pers->quiesce(mddev, 1);
3306                 mddev->pers->quiesce(mddev, 0);
3307                 return len;
3308         } else
3309                 return -EINVAL;
3310 }
3311 static struct md_sysfs_entry md_suspend_hi =
3312 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
3313
3314 static ssize_t
3315 reshape_position_show(mddev_t *mddev, char *page)
3316 {
3317         if (mddev->reshape_position != MaxSector)
3318                 return sprintf(page, "%llu\n",
3319                                (unsigned long long)mddev->reshape_position);
3320         strcpy(page, "none\n");
3321         return 5;
3322 }
3323
3324 static ssize_t
3325 reshape_position_store(mddev_t *mddev, const char *buf, size_t len)
3326 {
3327         char *e;
3328         unsigned long long new = simple_strtoull(buf, &e, 10);
3329         if (mddev->pers)
3330                 return -EBUSY;
3331         if (buf == e || (*e && *e != '\n'))
3332                 return -EINVAL;
3333         mddev->reshape_position = new;
3334         mddev->delta_disks = 0;
3335         mddev->new_level = mddev->level;
3336         mddev->new_layout = mddev->layout;
3337         mddev->new_chunk = mddev->chunk_size;
3338         return len;
3339 }
3340
3341 static struct md_sysfs_entry md_reshape_position =
3342 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
3343        reshape_position_store);
3344
3345
3346 static struct attribute *md_default_attrs[] = {
3347         &md_level.attr,
3348         &md_layout.attr,
3349         &md_raid_disks.attr,
3350         &md_chunk_size.attr,
3351         &md_size.attr,
3352         &md_resync_start.attr,
3353         &md_metadata.attr,
3354         &md_new_device.attr,
3355         &md_safe_delay.attr,
3356         &md_array_state.attr,
3357         &md_reshape_position.attr,
3358         NULL,
3359 };
3360
3361 static struct attribute *md_redundancy_attrs[] = {
3362         &md_scan_mode.attr,
3363         &md_mismatches.attr,
3364         &md_sync_min.attr,
3365         &md_sync_max.attr,
3366         &md_sync_speed.attr,
3367         &md_sync_force_parallel.attr,
3368         &md_sync_completed.attr,
3369         &md_min_sync.attr,
3370         &md_max_sync.attr,
3371         &md_suspend_lo.attr,
3372         &md_suspend_hi.attr,
3373         &md_bitmap.attr,
3374         &md_degraded.attr,
3375         NULL,
3376 };
3377 static struct attribute_group md_redundancy_group = {
3378         .name = NULL,
3379         .attrs = md_redundancy_attrs,
3380 };
3381
3382
3383 static ssize_t
3384 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3385 {
3386         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3387         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3388         ssize_t rv;
3389
3390         if (!entry->show)
3391                 return -EIO;
3392         rv = mddev_lock(mddev);
3393         if (!rv) {
3394                 rv = entry->show(mddev, page);
3395                 mddev_unlock(mddev);
3396         }
3397         return rv;
3398 }
3399
3400 static ssize_t
3401 md_attr_store(struct kobject *kobj, struct attribute *attr,
3402               const char *page, size_t length)
3403 {
3404         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3405         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3406         ssize_t rv;
3407
3408         if (!entry->store)
3409                 return -EIO;
3410         if (!capable(CAP_SYS_ADMIN))
3411                 return -EACCES;
3412         rv = mddev_lock(mddev);
3413         if (!rv) {
3414                 rv = entry->store(mddev, page, length);
3415                 mddev_unlock(mddev);
3416         }
3417         return rv;
3418 }
3419
3420 static void md_free(struct kobject *ko)
3421 {
3422         mddev_t *mddev = container_of(ko, mddev_t, kobj);
3423         kfree(mddev);
3424 }
3425
3426 static struct sysfs_ops md_sysfs_ops = {
3427         .show   = md_attr_show,
3428         .store  = md_attr_store,
3429 };
3430 static struct kobj_type md_ktype = {
3431         .release        = md_free,
3432         .sysfs_ops      = &md_sysfs_ops,
3433         .default_attrs  = md_default_attrs,
3434 };
3435
3436 int mdp_major = 0;
3437
3438 static struct kobject *md_probe(dev_t dev, int *part, void *data)
3439 {
3440         static DEFINE_MUTEX(disks_mutex);
3441         mddev_t *mddev = mddev_find(dev);
3442         struct gendisk *disk;
3443         int partitioned = (MAJOR(dev) != MD_MAJOR);
3444         int shift = partitioned ? MdpMinorShift : 0;
3445         int unit = MINOR(dev) >> shift;
3446         int error;
3447
3448         if (!mddev)
3449                 return NULL;
3450
3451         mutex_lock(&disks_mutex);
3452         if (mddev->gendisk) {
3453                 mutex_unlock(&disks_mutex);
3454                 mddev_put(mddev);
3455                 return NULL;
3456         }
3457         disk = alloc_disk(1 << shift);
3458         if (!disk) {
3459                 mutex_unlock(&disks_mutex);
3460                 mddev_put(mddev);
3461                 return NULL;
3462         }
3463         disk->major = MAJOR(dev);
3464         disk->first_minor = unit << shift;
3465         if (partitioned)
3466                 sprintf(disk->disk_name, "md_d%d", unit);
3467         else
3468                 sprintf(disk->disk_name, "md%d", unit);
3469         disk->fops = &md_fops;
3470         disk->private_data = mddev;
3471         disk->queue = mddev->queue;
3472         add_disk(disk);
3473         mddev->gendisk = disk;
3474         error = kobject_init_and_add(&mddev->kobj, &md_ktype,
3475                                      &disk_to_dev(disk)->kobj, "%s", "md");
3476         mutex_unlock(&disks_mutex);
3477         if (error)
3478                 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
3479                        disk->disk_name);
3480         else
3481                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
3482         return NULL;
3483 }
3484
3485 static void md_safemode_timeout(unsigned long data)
3486 {
3487         mddev_t *mddev = (mddev_t *) data;
3488
3489         if (!atomic_read(&mddev->writes_pending)) {
3490                 mddev->safemode = 1;
3491                 if (mddev->external)
3492                         set_bit(MD_NOTIFY_ARRAY_STATE, &mddev->flags);
3493         }
3494         md_wakeup_thread(mddev->thread);
3495 }
3496
3497 static int start_dirty_degraded;
3498
3499 static int do_md_run(mddev_t * mddev)
3500 {
3501         int err;
3502         int chunk_size;
3503         struct list_head *tmp;
3504         mdk_rdev_t *rdev;
3505         struct gendisk *disk;
3506         struct mdk_personality *pers;
3507         char b[BDEVNAME_SIZE];
3508
3509         if (list_empty(&mddev->disks))
3510                 /* cannot run an array with no devices.. */
3511                 return -EINVAL;
3512
3513         if (mddev->pers)
3514                 return -EBUSY;
3515
3516         /*
3517          * Analyze all RAID superblock(s)
3518          */
3519         if (!mddev->raid_disks) {
3520                 if (!mddev->persistent)
3521                         return -EINVAL;
3522                 analyze_sbs(mddev);
3523         }
3524
3525         chunk_size = mddev->chunk_size;
3526
3527         if (chunk_size) {
3528                 if (chunk_size > MAX_CHUNK_SIZE) {
3529                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
3530                                 chunk_size, MAX_CHUNK_SIZE);
3531                         return -EINVAL;
3532                 }
3533                 /*
3534                  * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
3535                  */
3536                 if ( (1 << ffz(~chunk_size)) != chunk_size) {
3537                         printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
3538                         return -EINVAL;
3539                 }
3540                 if (chunk_size < PAGE_SIZE) {
3541                         printk(KERN_ERR "too small chunk_size: %d < %ld\n",
3542                                 chunk_size, PAGE_SIZE);
3543                         return -EINVAL;
3544                 }
3545
3546                 /* devices must have minimum size of one chunk */
3547                 rdev_for_each(rdev, tmp, mddev) {
3548                         if (test_bit(Faulty, &rdev->flags))
3549                                 continue;
3550                         if (rdev->size < chunk_size / 1024) {
3551                                 printk(KERN_WARNING
3552                                         "md: Dev %s smaller than chunk_size:"
3553                                         " %lluk < %dk\n",
3554                                         bdevname(rdev->bdev,b),
3555                                         (unsigned long long)rdev->size,
3556                                         chunk_size / 1024);
3557                                 return -EINVAL;
3558                         }
3559                 }
3560         }
3561
3562 #ifdef CONFIG_KMOD
3563         if (mddev->level != LEVEL_NONE)
3564                 request_module("md-level-%d", mddev->level);
3565         else if (mddev->clevel[0])
3566                 request_module("md-%s", mddev->clevel);
3567 #endif
3568
3569         /*
3570          * Drop all container device buffers, from now on
3571          * the only valid external interface is through the md
3572          * device.
3573          */
3574         rdev_for_each(rdev, tmp, mddev) {
3575                 if (test_bit(Faulty, &rdev->flags))
3576                         continue;
3577                 sync_blockdev(rdev->bdev);
3578                 invalidate_bdev(rdev->bdev);
3579
3580                 /* perform some consistency tests on the device.
3581                  * We don't want the data to overlap the metadata,
3582                  * Internal Bitmap issues has handled elsewhere.
3583                  */
3584                 if (rdev->data_offset < rdev->sb_start) {
3585                         if (mddev->size &&
3586                             rdev->data_offset + mddev->size*2
3587                             > rdev->sb_start) {
3588                                 printk("md: %s: data overlaps metadata\n",
3589                                        mdname(mddev));
3590                                 return -EINVAL;
3591                         }
3592                 } else {
3593                         if (rdev->sb_start + rdev->sb_size/512
3594                             > rdev->data_offset) {
3595                                 printk("md: %s: metadata overlaps data\n",
3596                                        mdname(mddev));
3597                                 return -EINVAL;
3598                         }
3599                 }
3600                 sysfs_notify(&rdev->kobj, NULL, "state");
3601         }
3602
3603         md_probe(mddev->unit, NULL, NULL);
3604         disk = mddev->gendisk;
3605         if (!disk)
3606                 return -ENOMEM;
3607
3608         spin_lock(&pers_lock);
3609         pers = find_pers(mddev->level, mddev->clevel);
3610         if (!pers || !try_module_get(pers->owner)) {
3611                 spin_unlock(&pers_lock);
3612                 if (mddev->level != LEVEL_NONE)
3613                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
3614                                mddev->level);
3615                 else
3616                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
3617                                mddev->clevel);
3618                 return -EINVAL;
3619         }
3620         mddev->pers = pers;
3621         spin_unlock(&pers_lock);
3622         mddev->level = pers->level;
3623         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3624
3625         if (mddev->reshape_position != MaxSector &&
3626             pers->start_reshape == NULL) {
3627                 /* This personality cannot handle reshaping... */
3628                 mddev->pers = NULL;
3629                 module_put(pers->owner);
3630                 return -EINVAL;
3631         }
3632
3633         if (pers->sync_request) {
3634                 /* Warn if this is a potentially silly
3635                  * configuration.
3636                  */
3637                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
3638                 mdk_rdev_t *rdev2;
3639                 struct list_head *tmp2;
3640                 int warned = 0;
3641                 rdev_for_each(rdev, tmp, mddev) {
3642                         rdev_for_each(rdev2, tmp2, mddev) {
3643                                 if (rdev < rdev2 &&
3644                                     rdev->bdev->bd_contains ==
3645                                     rdev2->bdev->bd_contains) {
3646                                         printk(KERN_WARNING
3647                                                "%s: WARNING: %s appears to be"
3648                                                " on the same physical disk as"
3649                                                " %s.\n",
3650                                                mdname(mddev),
3651                                                bdevname(rdev->bdev,b),
3652                                                bdevname(rdev2->bdev,b2));
3653                                         warned = 1;
3654                                 }
3655                         }
3656                 }
3657                 if (warned)
3658                         printk(KERN_WARNING
3659                                "True protection against single-disk"
3660                                " failure might be compromised.\n");
3661         }
3662
3663         mddev->recovery = 0;
3664         mddev->resync_max_sectors = mddev->size << 1; /* may be over-ridden by personality */
3665         mddev->barriers_work = 1;
3666         mddev->ok_start_degraded = start_dirty_degraded;
3667
3668         if (start_readonly)
3669                 mddev->ro = 2; /* read-only, but switch on first write */
3670
3671         err = mddev->pers->run(mddev);
3672         if (err)
3673                 printk(KERN_ERR "md: pers->run() failed ...\n");
3674         else if (mddev->pers->sync_request) {
3675                 err = bitmap_create(mddev);
3676                 if (err) {
3677                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
3678                                mdname(mddev), err);
3679                         mddev->pers->stop(mddev);
3680                 }
3681         }
3682         if (err) {
3683                 module_put(mddev->pers->owner);
3684                 mddev->pers = NULL;
3685                 bitmap_destroy(mddev);
3686                 return err;
3687         }
3688         if (mddev->pers->sync_request) {
3689                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3690                         printk(KERN_WARNING
3691                                "md: cannot register extra attributes for %s\n",
3692                                mdname(mddev));
3693         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
3694                 mddev->ro = 0;
3695
3696         atomic_set(&mddev->writes_pending,0);
3697         mddev->safemode = 0;
3698         mddev->safemode_timer.function = md_safemode_timeout;
3699         mddev->safemode_timer.data = (unsigned long) mddev;
3700         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
3701         mddev->in_sync = 1;
3702
3703         rdev_for_each(rdev, tmp, mddev)
3704                 if (rdev->raid_disk >= 0) {
3705                         char nm[20];
3706                         sprintf(nm, "rd%d", rdev->raid_disk);
3707                         if (sysfs_create_link(&mddev->kobj, &rdev->kobj, nm))
3708                                 printk("md: cannot register %s for %s\n",
3709                                        nm, mdname(mddev));
3710                 }
3711         
3712         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3713         
3714         if (mddev->flags)
3715                 md_update_sb(mddev, 0);
3716
3717         set_capacity(disk, mddev->array_sectors);
3718
3719         /* If we call blk_queue_make_request here, it will
3720          * re-initialise max_sectors etc which may have been
3721          * refined inside -> run.  So just set the bits we need to set.
3722          * Most initialisation happended when we called
3723          * blk_queue_make_request(..., md_fail_request)
3724          * earlier.
3725          */
3726         mddev->queue->queuedata = mddev;
3727         mddev->queue->make_request_fn = mddev->pers->make_request;
3728
3729         /* If there is a partially-recovered drive we need to
3730          * start recovery here.  If we leave it to md_check_recovery,
3731          * it will remove the drives and not do the right thing
3732          */
3733         if (mddev->degraded && !mddev->sync_thread) {
3734                 struct list_head *rtmp;
3735                 int spares = 0;
3736                 rdev_for_each(rdev, rtmp, mddev)
3737                         if (rdev->raid_disk >= 0 &&
3738                             !test_bit(In_sync, &rdev->flags) &&
3739                             !test_bit(Faulty, &rdev->flags))
3740                                 /* complete an interrupted recovery */
3741                                 spares++;
3742                 if (spares && mddev->pers->sync_request) {
3743                         mddev->recovery = 0;
3744                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3745                         mddev->sync_thread = md_register_thread(md_do_sync,
3746                                                                 mddev,
3747                                                                 "%s_resync");
3748                         if (!mddev->sync_thread) {
3749                                 printk(KERN_ERR "%s: could not start resync"
3750                                        " thread...\n",
3751                                        mdname(mddev));
3752                                 /* leave the spares where they are, it shouldn't hurt */
3753                                 mddev->recovery = 0;
3754                         }
3755                 }
3756         }
3757         md_wakeup_thread(mddev->thread);
3758         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
3759
3760         mddev->changed = 1;
3761         md_new_event(mddev);
3762         sysfs_notify(&mddev->kobj, NULL, "array_state");
3763         sysfs_notify(&mddev->kobj, NULL, "sync_action");
3764         sysfs_notify(&mddev->kobj, NULL, "degraded");
3765         kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
3766         return 0;
3767 }
3768
3769 static int restart_array(mddev_t *mddev)
3770 {
3771         struct gendisk *disk = mddev->gendisk;
3772
3773         /* Complain if it has no devices */
3774         if (list_empty(&mddev->disks))
3775                 return -ENXIO;
3776         if (!mddev->pers)
3777                 return -EINVAL;
3778         if (!mddev->ro)
3779                 return -EBUSY;
3780         mddev->safemode = 0;
3781         mddev->ro = 0;
3782         set_disk_ro(disk, 0);
3783         printk(KERN_INFO "md: %s switched to read-write mode.\n",
3784                 mdname(mddev));
3785         /* Kick recovery or resync if necessary */
3786         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3787         md_wakeup_thread(mddev->thread);
3788         md_wakeup_thread(mddev->sync_thread);
3789         sysfs_notify(&mddev->kobj, NULL, "array_state");
3790         return 0;
3791 }
3792
3793 /* similar to deny_write_access, but accounts for our holding a reference
3794  * to the file ourselves */
3795 static int deny_bitmap_write_access(struct file * file)
3796 {
3797         struct inode *inode = file->f_mapping->host;
3798
3799         spin_lock(&inode->i_lock);
3800         if (atomic_read(&inode->i_writecount) > 1) {
3801                 spin_unlock(&inode->i_lock);
3802                 return -ETXTBSY;
3803         }
3804         atomic_set(&inode->i_writecount, -1);
3805         spin_unlock(&inode->i_lock);
3806
3807         return 0;
3808 }
3809
3810 static void restore_bitmap_write_access(struct file *file)
3811 {
3812         struct inode *inode = file->f_mapping->host;
3813
3814         spin_lock(&inode->i_lock);
3815         atomic_set(&inode->i_writecount, 1);
3816         spin_unlock(&inode->i_lock);
3817 }
3818
3819 /* mode:
3820  *   0 - completely stop and dis-assemble array
3821  *   1 - switch to readonly
3822  *   2 - stop but do not disassemble array
3823  */
3824 static int do_md_stop(mddev_t * mddev, int mode, int is_open)
3825 {
3826         int err = 0;
3827         struct gendisk *disk = mddev->gendisk;
3828
3829         if (atomic_read(&mddev->openers) > is_open) {
3830                 printk("md: %s still in use.\n",mdname(mddev));
3831                 return -EBUSY;
3832         }
3833
3834         if (mddev->pers) {
3835
3836                 if (mddev->sync_thread) {
3837                         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3838                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3839                         md_unregister_thread(mddev->sync_thread);
3840                         mddev->sync_thread = NULL;
3841                 }
3842
3843                 del_timer_sync(&mddev->safemode_timer);
3844
3845                 switch(mode) {
3846                 case 1: /* readonly */
3847                         err  = -ENXIO;
3848                         if (mddev->ro==1)
3849                                 goto out;
3850                         mddev->ro = 1;
3851                         break;
3852                 case 0: /* disassemble */
3853                 case 2: /* stop */
3854                         bitmap_flush(mddev);
3855                         md_super_wait(mddev);
3856                         if (mddev->ro)
3857                                 set_disk_ro(disk, 0);
3858                         blk_queue_make_request(mddev->queue, md_fail_request);
3859                         mddev->pers->stop(mddev);
3860                         mddev->queue->merge_bvec_fn = NULL;
3861                         mddev->queue->unplug_fn = NULL;
3862                         mddev->queue->backing_dev_info.congested_fn = NULL;
3863                         if (mddev->pers->sync_request)
3864                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
3865
3866                         module_put(mddev->pers->owner);
3867                         mddev->pers = NULL;
3868                         /* tell userspace to handle 'inactive' */
3869                         sysfs_notify(&mddev->kobj, NULL, "array_state");
3870
3871                         set_capacity(disk, 0);
3872                         mddev->changed = 1;
3873
3874                         if (mddev->ro)
3875                                 mddev->ro = 0;
3876                 }
3877                 if (!mddev->in_sync || mddev->flags) {
3878                         /* mark array as shutdown cleanly */
3879                         mddev->in_sync = 1;
3880                         md_update_sb(mddev, 1);
3881                 }
3882                 if (mode == 1)
3883                         set_disk_ro(disk, 1);
3884                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3885         }
3886
3887         /*
3888          * Free resources if final stop
3889          */
3890         if (mode == 0) {
3891                 mdk_rdev_t *rdev;
3892                 struct list_head *tmp;
3893
3894                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
3895
3896                 bitmap_destroy(mddev);
3897                 if (mddev->bitmap_file) {
3898                         restore_bitmap_write_access(mddev->bitmap_file);
3899                         fput(mddev->bitmap_file);
3900                         mddev->bitmap_file = NULL;
3901                 }
3902                 mddev->bitmap_offset = 0;
3903
3904                 rdev_for_each(rdev, tmp, mddev)
3905                         if (rdev->raid_disk >= 0) {
3906                                 char nm[20];
3907                                 sprintf(nm, "rd%d", rdev->raid_disk);
3908                                 sysfs_remove_link(&mddev->kobj, nm);
3909                         }
3910
3911                 /* make sure all md_delayed_delete calls have finished */
3912                 flush_scheduled_work();
3913
3914                 export_array(mddev);
3915
3916                 mddev->array_sectors = 0;
3917                 mddev->size = 0;
3918                 mddev->raid_disks = 0;
3919                 mddev->recovery_cp = 0;
3920                 mddev->resync_min = 0;
3921                 mddev->resync_max = MaxSector;
3922                 mddev->reshape_position = MaxSector;
3923                 mddev->external = 0;
3924                 mddev->persistent = 0;
3925                 mddev->level = LEVEL_NONE;
3926                 mddev->clevel[0] = 0;
3927                 mddev->flags = 0;
3928                 mddev->ro = 0;
3929                 mddev->metadata_type[0] = 0;
3930                 mddev->chunk_size = 0;
3931                 mddev->ctime = mddev->utime = 0;
3932                 mddev->layout = 0;
3933                 mddev->max_disks = 0;
3934                 mddev->events = 0;
3935                 mddev->delta_disks = 0;
3936                 mddev->new_level = LEVEL_NONE;
3937                 mddev->new_layout = 0;
3938                 mddev->new_chunk = 0;
3939                 mddev->curr_resync = 0;
3940                 mddev->resync_mismatches = 0;
3941                 mddev->suspend_lo = mddev->suspend_hi = 0;
3942                 mddev->sync_speed_min = mddev->sync_speed_max = 0;
3943                 mddev->recovery = 0;
3944                 mddev->in_sync = 0;
3945                 mddev->changed = 0;
3946                 mddev->degraded = 0;
3947                 mddev->barriers_work = 0;
3948                 mddev->safemode = 0;
3949
3950         } else if (mddev->pers)
3951                 printk(KERN_INFO "md: %s switched to read-only mode.\n",
3952                         mdname(mddev));
3953         err = 0;
3954         md_new_event(mddev);
3955         sysfs_notify(&mddev->kobj, NULL, "array_state");
3956 out:
3957         return err;
3958 }
3959
3960 #ifndef MODULE
3961 static void autorun_array(mddev_t *mddev)
3962 {
3963         mdk_rdev_t *rdev;
3964         struct list_head *tmp;
3965         int err;
3966
3967         if (list_empty(&mddev->disks))
3968                 return;
3969
3970         printk(KERN_INFO "md: running: ");
3971
3972         rdev_for_each(rdev, tmp, mddev) {
3973                 char b[BDEVNAME_SIZE];
3974                 printk("<%s>", bdevname(rdev->bdev,b));
3975         }
3976         printk("\n");
3977
3978         err = do_md_run (mddev);
3979         if (err) {
3980                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
3981                 do_md_stop (mddev, 0, 0);
3982         }
3983 }
3984
3985 /*
3986  * lets try to run arrays based on all disks that have arrived
3987  * until now. (those are in pending_raid_disks)
3988  *
3989  * the method: pick the first pending disk, collect all disks with
3990  * the same UUID, remove all from the pending list and put them into
3991  * the 'same_array' list. Then order this list based on superblock
3992  * update time (freshest comes first), kick out 'old' disks and
3993  * compare superblocks. If everything's fine then run it.
3994  *
3995  * If "unit" is allocated, then bump its reference count
3996  */
3997 static void autorun_devices(int part)
3998 {
3999         struct list_head *tmp;
4000         mdk_rdev_t *rdev0, *rdev;
4001         mddev_t *mddev;
4002         char b[BDEVNAME_SIZE];
4003
4004         printk(KERN_INFO "md: autorun ...\n");
4005         while (!list_empty(&pending_raid_disks)) {
4006                 int unit;
4007                 dev_t dev;
4008                 LIST_HEAD(candidates);
4009                 rdev0 = list_entry(pending_raid_disks.next,
4010                                          mdk_rdev_t, same_set);
4011
4012                 printk(KERN_INFO "md: considering %s ...\n",
4013                         bdevname(rdev0->bdev,b));
4014                 INIT_LIST_HEAD(&candidates);
4015                 rdev_for_each_list(rdev, tmp, pending_raid_disks)
4016                         if (super_90_load(rdev, rdev0, 0) >= 0) {
4017                                 printk(KERN_INFO "md:  adding %s ...\n",
4018                                         bdevname(rdev->bdev,b));
4019                                 list_move(&rdev->same_set, &candidates);
4020                         }
4021                 /*
4022                  * now we have a set of devices, with all of them having
4023                  * mostly sane superblocks. It's time to allocate the
4024                  * mddev.
4025                  */
4026                 if (part) {
4027                         dev = MKDEV(mdp_major,
4028                                     rdev0->preferred_minor << MdpMinorShift);
4029                         unit = MINOR(dev) >> MdpMinorShift;
4030                 } else {
4031                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
4032                         unit = MINOR(dev);
4033                 }
4034                 if (rdev0->preferred_minor != unit) {
4035                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
4036                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
4037                         break;
4038                 }
4039
4040                 md_probe(dev, NULL, NULL);
4041                 mddev = mddev_find(dev);
4042                 if (!mddev || !mddev->gendisk) {
4043                         if (mddev)
4044                                 mddev_put(mddev);
4045                         printk(KERN_ERR
4046                                 "md: cannot allocate memory for md drive.\n");
4047                         break;
4048                 }
4049                 if (mddev_lock(mddev)) 
4050                         printk(KERN_WARNING "md: %s locked, cannot run\n",
4051                                mdname(mddev));
4052                 else if (mddev->raid_disks || mddev->major_version
4053                          || !list_empty(&mddev->disks)) {
4054                         printk(KERN_WARNING 
4055                                 "md: %s already running, cannot run %s\n",
4056                                 mdname(mddev), bdevname(rdev0->bdev,b));
4057                         mddev_unlock(mddev);
4058                 } else {
4059                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
4060                         mddev->persistent = 1;
4061                         rdev_for_each_list(rdev, tmp, candidates) {
4062                                 list_del_init(&rdev->same_set);
4063                                 if (bind_rdev_to_array(rdev, mddev))
4064                                         export_rdev(rdev);
4065                         }
4066                         autorun_array(mddev);
4067                         mddev_unlock(mddev);
4068                 }
4069                 /* on success, candidates will be empty, on error
4070                  * it won't...
4071                  */
4072                 rdev_for_each_list(rdev, tmp, candidates) {
4073                         list_del_init(&rdev->same_set);
4074                         export_rdev(rdev);
4075                 }
4076                 mddev_put(mddev);
4077         }
4078         printk(KERN_INFO "md: ... autorun DONE.\n");
4079 }
4080 #endif /* !MODULE */
4081
4082 static int get_version(void __user * arg)
4083 {
4084         mdu_version_t ver;
4085
4086         ver.major = MD_MAJOR_VERSION;
4087         ver.minor = MD_MINOR_VERSION;
4088         ver.patchlevel = MD_PATCHLEVEL_VERSION;
4089
4090         if (copy_to_user(arg, &ver, sizeof(ver)))
4091                 return -EFAULT;
4092
4093         return 0;
4094 }
4095
4096 static int get_array_info(mddev_t * mddev, void __user * arg)
4097 {
4098         mdu_array_info_t info;
4099         int nr,working,active,failed,spare;
4100         mdk_rdev_t *rdev;
4101         struct list_head *tmp;
4102
4103         nr=working=active=failed=spare=0;
4104         rdev_for_each(rdev, tmp, mddev) {
4105                 nr++;
4106                 if (test_bit(Faulty, &rdev->flags))
4107                         failed++;
4108                 else {
4109                         working++;
4110                         if (test_bit(In_sync, &rdev->flags))
4111                                 active++;       
4112                         else
4113                                 spare++;
4114                 }
4115         }
4116
4117         info.major_version = mddev->major_version;
4118         info.minor_version = mddev->minor_version;
4119         info.patch_version = MD_PATCHLEVEL_VERSION;
4120         info.ctime         = mddev->ctime;
4121         info.level         = mddev->level;
4122         info.size          = mddev->size;
4123         if (info.size != mddev->size) /* overflow */
4124                 info.size = -1;
4125         info.nr_disks      = nr;
4126         info.raid_disks    = mddev->raid_disks;
4127         info.md_minor      = mddev->md_minor;
4128         info.not_persistent= !mddev->persistent;
4129
4130         info.utime         = mddev->utime;
4131         info.state         = 0;
4132         if (mddev->in_sync)
4133                 info.state = (1<<MD_SB_CLEAN);
4134         if (mddev->bitmap && mddev->bitmap_offset)
4135                 info.state = (1<<MD_SB_BITMAP_PRESENT);
4136         info.active_disks  = active;
4137         info.working_disks = working;
4138         info.failed_disks  = failed;
4139         info.spare_disks   = spare;
4140
4141         info.layout        = mddev->layout;
4142         info.chunk_size    = mddev->chunk_size;
4143
4144         if (copy_to_user(arg, &info, sizeof(info)))
4145                 return -EFAULT;
4146
4147         return 0;
4148 }
4149
4150 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
4151 {
4152         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
4153         char *ptr, *buf = NULL;
4154         int err = -ENOMEM;
4155
4156         if (md_allow_write(mddev))
4157                 file = kmalloc(sizeof(*file), GFP_NOIO);
4158         else
4159                 file = kmalloc(sizeof(*file), GFP_KERNEL);
4160
4161         if (!file)
4162                 goto out;
4163
4164         /* bitmap disabled, zero the first byte and copy out */
4165         if (!mddev->bitmap || !mddev->bitmap->file) {
4166                 file->pathname[0] = '\0';
4167                 goto copy_out;
4168         }
4169
4170         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
4171         if (!buf)
4172                 goto out;
4173
4174         ptr = d_path(&mddev->bitmap->file->f_path, buf, sizeof(file->pathname));
4175         if (IS_ERR(ptr))
4176                 goto out;
4177
4178         strcpy(file->pathname, ptr);
4179
4180 copy_out:
4181         err = 0;
4182         if (copy_to_user(arg, file, sizeof(*file)))
4183                 err = -EFAULT;
4184 out:
4185         kfree(buf);
4186         kfree(file);
4187         return err;
4188 }
4189
4190 static int get_disk_info(mddev_t * mddev, void __user * arg)
4191 {
4192         mdu_disk_info_t info;
4193         mdk_rdev_t *rdev;
4194
4195         if (copy_from_user(&info, arg, sizeof(info)))
4196                 return -EFAULT;
4197
4198         rdev = find_rdev_nr(mddev, info.number);
4199         if (rdev) {
4200                 info.major = MAJOR(rdev->bdev->bd_dev);
4201                 info.minor = MINOR(rdev->bdev->bd_dev);
4202                 info.raid_disk = rdev->raid_disk;
4203                 info.state = 0;
4204                 if (test_bit(Faulty, &rdev->flags))
4205                         info.state |= (1<<MD_DISK_FAULTY);
4206                 else if (test_bit(In_sync, &rdev->flags)) {
4207                         info.state |= (1<<MD_DISK_ACTIVE);
4208                         info.state |= (1<<MD_DISK_SYNC);
4209                 }
4210                 if (test_bit(WriteMostly, &rdev->flags))
4211                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
4212         } else {
4213                 info.major = info.minor = 0;
4214                 info.raid_disk = -1;
4215                 info.state = (1<<MD_DISK_REMOVED);
4216         }
4217
4218         if (copy_to_user(arg, &info, sizeof(info)))
4219                 return -EFAULT;
4220
4221         return 0;
4222 }
4223
4224 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
4225 {
4226         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4227         mdk_rdev_t *rdev;
4228         dev_t dev = MKDEV(info->major,info->minor);
4229
4230         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
4231                 return -EOVERFLOW;
4232
4233         if (!mddev->raid_disks) {
4234                 int err;
4235                 /* expecting a device which has a superblock */
4236                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
4237                 if (IS_ERR(rdev)) {
4238                         printk(KERN_WARNING 
4239                                 "md: md_import_device returned %ld\n",
4240                                 PTR_ERR(rdev));
4241                         return PTR_ERR(rdev);
4242                 }
4243                 if (!list_empty(&mddev->disks)) {
4244                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
4245                                                         mdk_rdev_t, same_set);
4246                         int err = super_types[mddev->major_version]
4247                                 .load_super(rdev, rdev0, mddev->minor_version);
4248                         if (err < 0) {
4249                                 printk(KERN_WARNING 
4250                                         "md: %s has different UUID to %s\n",
4251                                         bdevname(rdev->bdev,b), 
4252                                         bdevname(rdev0->bdev,b2));
4253                                 export_rdev(rdev);
4254                                 return -EINVAL;
4255                         }
4256                 }
4257                 err = bind_rdev_to_array(rdev, mddev);
4258                 if (err)
4259                         export_rdev(rdev);
4260                 return err;
4261         }
4262
4263         /*
4264          * add_new_disk can be used once the array is assembled
4265          * to add "hot spares".  They must already have a superblock
4266          * written
4267          */
4268         if (mddev->pers) {
4269                 int err;
4270                 if (!mddev->pers->hot_add_disk) {
4271                         printk(KERN_WARNING 
4272                                 "%s: personality does not support diskops!\n",
4273                                mdname(mddev));
4274                         return -EINVAL;
4275                 }
4276                 if (mddev->persistent)
4277                         rdev = md_import_device(dev, mddev->major_version,
4278                                                 mddev->minor_version);
4279                 else
4280                         rdev = md_import_device(dev, -1, -1);
4281                 if (IS_ERR(rdev)) {
4282                         printk(KERN_WARNING 
4283                                 "md: md_import_device returned %ld\n",
4284                                 PTR_ERR(rdev));
4285                         return PTR_ERR(rdev);
4286                 }
4287                 /* set save_raid_disk if appropriate */
4288                 if (!mddev->persistent) {
4289                         if (info->state & (1<<MD_DISK_SYNC)  &&
4290                             info->raid_disk < mddev->raid_disks)
4291                                 rdev->raid_disk = info->raid_disk;
4292                         else
4293                                 rdev->raid_disk = -1;
4294                 } else
4295                         super_types[mddev->major_version].
4296                                 validate_super(mddev, rdev);
4297                 rdev->saved_raid_disk = rdev->raid_disk;
4298
4299                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
4300                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
4301                         set_bit(WriteMostly, &rdev->flags);
4302
4303                 rdev->raid_disk = -1;
4304                 err = bind_rdev_to_array(rdev, mddev);
4305                 if (!err && !mddev->pers->hot_remove_disk) {
4306                         /* If there is hot_add_disk but no hot_remove_disk
4307                          * then added disks for geometry changes,
4308                          * and should be added immediately.
4309                          */
4310                         super_types[mddev->major_version].
4311                                 validate_super(mddev, rdev);
4312                         err = mddev->pers->hot_add_disk(mddev, rdev);
4313                         if (err)
4314                                 unbind_rdev_from_array(rdev);
4315                 }
4316                 if (err)
4317                         export_rdev(rdev);
4318                 else
4319                         sysfs_notify(&rdev->kobj, NULL, "state");
4320
4321                 md_update_sb(mddev, 1);
4322                 if (mddev->degraded)
4323                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4324                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4325                 md_wakeup_thread(mddev->thread);
4326                 return err;
4327         }
4328
4329         /* otherwise, add_new_disk is only allowed
4330          * for major_version==0 superblocks
4331          */
4332         if (mddev->major_version != 0) {
4333                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
4334                        mdname(mddev));
4335                 return -EINVAL;
4336         }
4337
4338         if (!(info->state & (1<<MD_DISK_FAULTY))) {
4339                 int err;
4340                 rdev = md_import_device (dev, -1, 0);
4341                 if (IS_ERR(rdev)) {
4342                         printk(KERN_WARNING 
4343                                 "md: error, md_import_device() returned %ld\n",
4344                                 PTR_ERR(rdev));
4345                         return PTR_ERR(rdev);
4346                 }
4347                 rdev->desc_nr = info->number;
4348                 if (info->raid_disk < mddev->raid_disks)
4349                         rdev->raid_disk = info->raid_disk;
4350                 else
4351                         rdev->raid_disk = -1;
4352
4353                 if (rdev->raid_disk < mddev->raid_disks)
4354                         if (info->state & (1<<MD_DISK_SYNC))
4355                                 set_bit(In_sync, &rdev->flags);
4356
4357                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
4358                         set_bit(WriteMostly, &rdev->flags);
4359
4360                 if (!mddev->persistent) {
4361                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
4362                         rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
4363                 } else 
4364                         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
4365                 rdev->size = calc_num_sectors(rdev, mddev->chunk_size) / 2;
4366
4367                 err = bind_rdev_to_array(rdev, mddev);
4368                 if (err) {
4369                         export_rdev(rdev);
4370                         return err;
4371                 }
4372         }
4373
4374         return 0;
4375 }
4376
4377 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
4378 {
4379         char b[BDEVNAME_SIZE];
4380         mdk_rdev_t *rdev;
4381
4382         rdev = find_rdev(mddev, dev);
4383         if (!rdev)
4384                 return -ENXIO;
4385
4386         if (rdev->raid_disk >= 0)
4387                 goto busy;
4388
4389         kick_rdev_from_array(rdev);
4390         md_update_sb(mddev, 1);
4391         md_new_event(mddev);
4392
4393         return 0;
4394 busy:
4395         printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
4396                 bdevname(rdev->bdev,b), mdname(mddev));
4397         return -EBUSY;
4398 }
4399
4400 static int hot_add_disk(mddev_t * mddev, dev_t dev)
4401 {
4402         char b[BDEVNAME_SIZE];
4403         int err;
4404         mdk_rdev_t *rdev;
4405
4406         if (!mddev->pers)
4407                 return -ENODEV;
4408
4409         if (mddev->major_version != 0) {
4410                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
4411                         " version-0 superblocks.\n",
4412                         mdname(mddev));
4413                 return -EINVAL;
4414         }
4415         if (!mddev->pers->hot_add_disk) {
4416                 printk(KERN_WARNING 
4417                         "%s: personality does not support diskops!\n",
4418                         mdname(mddev));
4419                 return -EINVAL;
4420         }
4421
4422         rdev = md_import_device (dev, -1, 0);
4423         if (IS_ERR(rdev)) {
4424                 printk(KERN_WARNING 
4425                         "md: error, md_import_device() returned %ld\n",
4426                         PTR_ERR(rdev));
4427                 return -EINVAL;
4428         }
4429
4430         if (mddev->persistent)
4431                 rdev->sb_start = calc_dev_sboffset(rdev->bdev);
4432         else
4433                 rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
4434
4435         rdev->size = calc_num_sectors(rdev, mddev->chunk_size) / 2;
4436
4437         if (test_bit(Faulty, &rdev->flags)) {
4438                 printk(KERN_WARNING 
4439                         "md: can not hot-add faulty %s disk to %s!\n",
4440                         bdevname(rdev->bdev,b), mdname(mddev));
4441                 err = -EINVAL;
4442                 goto abort_export;
4443         }
4444         clear_bit(In_sync, &rdev->flags);
4445         rdev->desc_nr = -1;
4446         rdev->saved_raid_disk = -1;
4447         err = bind_rdev_to_array(rdev, mddev);
4448         if (err)
4449                 goto abort_export;
4450
4451         /*
4452          * The rest should better be atomic, we can have disk failures
4453          * noticed in interrupt contexts ...
4454          */
4455
4456         if (rdev->desc_nr == mddev->max_disks) {
4457                 printk(KERN_WARNING "%s: can not hot-add to full array!\n",
4458                         mdname(mddev));
4459                 err = -EBUSY;
4460                 goto abort_unbind_export;
4461         }
4462
4463         rdev->raid_disk = -1;
4464
4465         md_update_sb(mddev, 1);
4466
4467         /*
4468          * Kick recovery, maybe this spare has to be added to the
4469          * array immediately.
4470          */
4471         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4472         md_wakeup_thread(mddev->thread);
4473         md_new_event(mddev);
4474         return 0;
4475
4476 abort_unbind_export:
4477         unbind_rdev_from_array(rdev);
4478
4479 abort_export:
4480         export_rdev(rdev);
4481         return err;
4482 }
4483
4484 static int set_bitmap_file(mddev_t *mddev, int fd)
4485 {
4486         int err;
4487
4488         if (mddev->pers) {
4489                 if (!mddev->pers->quiesce)
4490                         return -EBUSY;
4491                 if (mddev->recovery || mddev->sync_thread)
4492                         return -EBUSY;
4493                 /* we should be able to change the bitmap.. */
4494         }
4495
4496
4497         if (fd >= 0) {
4498                 if (mddev->bitmap)
4499                         return -EEXIST; /* cannot add when bitmap is present */
4500                 mddev->bitmap_file = fget(fd);
4501
4502                 if (mddev->bitmap_file == NULL) {
4503                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
4504                                mdname(mddev));
4505                         return -EBADF;
4506                 }
4507
4508                 err = deny_bitmap_write_access(mddev->bitmap_file);
4509                 if (err) {
4510                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
4511                                mdname(mddev));
4512                         fput(mddev->bitmap_file);
4513                         mddev->bitmap_file = NULL;
4514                         return err;
4515                 }
4516                 mddev->bitmap_offset = 0; /* file overrides offset */
4517         } else if (mddev->bitmap == NULL)
4518                 return -ENOENT; /* cannot remove what isn't there */
4519         err = 0;
4520         if (mddev->pers) {
4521                 mddev->pers->quiesce(mddev, 1);
4522                 if (fd >= 0)
4523                         err = bitmap_create(mddev);
4524                 if (fd < 0 || err) {
4525                         bitmap_destroy(mddev);
4526                         fd = -1; /* make sure to put the file */
4527                 }
4528                 mddev->pers->quiesce(mddev, 0);
4529         }
4530         if (fd < 0) {
4531                 if (mddev->bitmap_file) {
4532                         restore_bitmap_write_access(mddev->bitmap_file);
4533                         fput(mddev->bitmap_file);
4534                 }
4535                 mddev->bitmap_file = NULL;
4536         }
4537
4538         return err;
4539 }
4540
4541 /*
4542  * set_array_info is used two different ways
4543  * The original usage is when creating a new array.
4544  * In this usage, raid_disks is > 0 and it together with
4545  *  level, size, not_persistent,layout,chunksize determine the
4546  *  shape of the array.
4547  *  This will always create an array with a type-0.90.0 superblock.
4548  * The newer usage is when assembling an array.
4549  *  In this case raid_disks will be 0, and the major_version field is
4550  *  use to determine which style super-blocks are to be found on the devices.
4551  *  The minor and patch _version numbers are also kept incase the
4552  *  super_block handler wishes to interpret them.
4553  */
4554 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
4555 {
4556
4557         if (info->raid_disks == 0) {
4558                 /* just setting version number for superblock loading */
4559                 if (info->major_version < 0 ||
4560                     info->major_version >= ARRAY_SIZE(super_types) ||
4561                     super_types[info->major_version].name == NULL) {
4562                         /* maybe try to auto-load a module? */
4563                         printk(KERN_INFO 
4564                                 "md: superblock version %d not known\n",
4565                                 info->major_version);
4566                         return -EINVAL;
4567                 }
4568                 mddev->major_version = info->major_version;
4569                 mddev->minor_version = info->minor_version;
4570                 mddev->patch_version = info->patch_version;
4571                 mddev->persistent = !info->not_persistent;
4572                 return 0;
4573         }
4574         mddev->major_version = MD_MAJOR_VERSION;
4575         mddev->minor_version = MD_MINOR_VERSION;
4576         mddev->patch_version = MD_PATCHLEVEL_VERSION;
4577         mddev->ctime         = get_seconds();
4578
4579         mddev->level         = info->level;
4580         mddev->clevel[0]     = 0;
4581         mddev->size          = info->size;
4582         mddev->raid_disks    = info->raid_disks;
4583         /* don't set md_minor, it is determined by which /dev/md* was
4584          * openned
4585          */
4586         if (info->state & (1<<MD_SB_CLEAN))
4587                 mddev->recovery_cp = MaxSector;
4588         else
4589                 mddev->recovery_cp = 0;
4590         mddev->persistent    = ! info->not_persistent;
4591         mddev->external      = 0;
4592
4593         mddev->layout        = info->layout;
4594         mddev->chunk_size    = info->chunk_size;
4595
4596         mddev->max_disks     = MD_SB_DISKS;
4597
4598         if (mddev->persistent)
4599                 mddev->flags         = 0;
4600         set_bit(MD_CHANGE_DEVS, &mddev->flags);
4601
4602         mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
4603         mddev->bitmap_offset = 0;
4604
4605         mddev->reshape_position = MaxSector;
4606
4607         /*
4608          * Generate a 128 bit UUID
4609          */
4610         get_random_bytes(mddev->uuid, 16);
4611
4612         mddev->new_level = mddev->level;
4613         mddev->new_chunk = mddev->chunk_size;
4614         mddev->new_layout = mddev->layout;
4615         mddev->delta_disks = 0;
4616
4617         return 0;
4618 }
4619
4620 static int update_size(mddev_t *mddev, sector_t num_sectors)
4621 {
4622         mdk_rdev_t * rdev;
4623         int rv;
4624         struct list_head *tmp;
4625         int fit = (num_sectors == 0);
4626
4627         if (mddev->pers->resize == NULL)
4628                 return -EINVAL;
4629         /* The "num_sectors" is the number of sectors of each device that
4630          * is used.  This can only make sense for arrays with redundancy.
4631          * linear and raid0 always use whatever space is available. We can only
4632          * consider changing this number if no resync or reconstruction is
4633          * happening, and if the new size is acceptable. It must fit before the
4634          * sb_start or, if that is <data_offset, it must fit before the size
4635          * of each device.  If num_sectors is zero, we find the largest size
4636          * that fits.
4637
4638          */
4639         if (mddev->sync_thread)
4640                 return -EBUSY;
4641         if (mddev->bitmap)
4642                 /* Sorry, cannot grow a bitmap yet, just remove it,
4643                  * grow, and re-add.
4644                  */
4645                 return -EBUSY;
4646         rdev_for_each(rdev, tmp, mddev) {
4647                 sector_t avail;
4648                 avail = rdev->size * 2;
4649
4650                 if (fit && (num_sectors == 0 || num_sectors > avail))
4651                         num_sectors = avail;
4652                 if (avail < num_sectors)
4653                         return -ENOSPC;
4654         }
4655         rv = mddev->pers->resize(mddev, num_sectors);
4656         if (!rv) {
4657                 struct block_device *bdev;
4658
4659                 bdev = bdget_disk(mddev->gendisk, 0);
4660                 if (bdev) {
4661                         mutex_lock(&bdev->bd_inode->i_mutex);
4662                         i_size_write(bdev->bd_inode,
4663                                      (loff_t)mddev->array_sectors << 9);
4664                         mutex_unlock(&bdev->bd_inode->i_mutex);
4665                         bdput(bdev);
4666                 }
4667         }
4668         return rv;
4669 }
4670
4671 static int update_raid_disks(mddev_t *mddev, int raid_disks)
4672 {
4673         int rv;
4674         /* change the number of raid disks */
4675         if (mddev->pers->check_reshape == NULL)
4676                 return -EINVAL;
4677         if (raid_disks <= 0 ||
4678             raid_disks >= mddev->max_disks)
4679                 return -EINVAL;
4680         if (mddev->sync_thread || mddev->reshape_position != MaxSector)
4681                 return -EBUSY;
4682         mddev->delta_disks = raid_disks - mddev->raid_disks;
4683
4684         rv = mddev->pers->check_reshape(mddev);
4685         return rv;
4686 }
4687
4688
4689 /*
4690  * update_array_info is used to change the configuration of an
4691  * on-line array.
4692  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
4693  * fields in the info are checked against the array.
4694  * Any differences that cannot be handled will cause an error.
4695  * Normally, only one change can be managed at a time.
4696  */
4697 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
4698 {
4699         int rv = 0;
4700         int cnt = 0;
4701         int state = 0;
4702
4703         /* calculate expected state,ignoring low bits */
4704         if (mddev->bitmap && mddev->bitmap_offset)
4705                 state |= (1 << MD_SB_BITMAP_PRESENT);
4706
4707         if (mddev->major_version != info->major_version ||
4708             mddev->minor_version != info->minor_version ||
4709 /*          mddev->patch_version != info->patch_version || */
4710             mddev->ctime         != info->ctime         ||
4711             mddev->level         != info->level         ||
4712 /*          mddev->layout        != info->layout        || */
4713             !mddev->persistent   != info->not_persistent||
4714             mddev->chunk_size    != info->chunk_size    ||
4715             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
4716             ((state^info->state) & 0xfffffe00)
4717                 )
4718                 return -EINVAL;
4719         /* Check there is only one change */
4720         if (info->size >= 0 && mddev->size != info->size) cnt++;
4721         if (mddev->raid_disks != info->raid_disks) cnt++;
4722         if (mddev->layout != info->layout) cnt++;
4723         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) cnt++;
4724         if (cnt == 0) return 0;
4725         if (cnt > 1) return -EINVAL;
4726
4727         if (mddev->layout != info->layout) {
4728                 /* Change layout
4729                  * we don't need to do anything at the md level, the
4730                  * personality will take care of it all.
4731                  */
4732                 if (mddev->pers->reconfig == NULL)
4733                         return -EINVAL;
4734                 else
4735                         return mddev->pers->reconfig(mddev, info->layout, -1);
4736         }
4737         if (info->size >= 0 && mddev->size != info->size)
4738                 rv = update_size(mddev, (sector_t)info->size * 2);
4739
4740         if (mddev->raid_disks    != info->raid_disks)
4741                 rv = update_raid_disks(mddev, info->raid_disks);
4742
4743         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
4744                 if (mddev->pers->quiesce == NULL)
4745                         return -EINVAL;
4746                 if (mddev->recovery || mddev->sync_thread)
4747                         return -EBUSY;
4748                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
4749                         /* add the bitmap */
4750                         if (mddev->bitmap)
4751                                 return -EEXIST;
4752                         if (mddev->default_bitmap_offset == 0)
4753                                 return -EINVAL;
4754                         mddev->bitmap_offset = mddev->default_bitmap_offset;
4755                         mddev->pers->quiesce(mddev, 1);
4756                         rv = bitmap_create(mddev);
4757                         if (rv)
4758                                 bitmap_destroy(mddev);
4759                         mddev->pers->quiesce(mddev, 0);
4760                 } else {
4761                         /* remove the bitmap */
4762                         if (!mddev->bitmap)
4763                                 return -ENOENT;
4764                         if (mddev->bitmap->file)
4765                                 return -EINVAL;
4766                         mddev->pers->quiesce(mddev, 1);
4767                         bitmap_destroy(mddev);
4768                         mddev->pers->quiesce(mddev, 0);
4769                         mddev->bitmap_offset = 0;
4770                 }
4771         }
4772         md_update_sb(mddev, 1);
4773         return rv;
4774 }
4775
4776 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
4777 {
4778         mdk_rdev_t *rdev;
4779
4780         if (mddev->pers == NULL)
4781                 return -ENODEV;
4782
4783         rdev = find_rdev(mddev, dev);
4784         if (!rdev)
4785                 return -ENODEV;
4786
4787         md_error(mddev, rdev);
4788         return 0;
4789 }
4790
4791 /*
4792  * We have a problem here : there is no easy way to give a CHS
4793  * virtual geometry. We currently pretend that we have a 2 heads
4794  * 4 sectors (with a BIG number of cylinders...). This drives
4795  * dosfs just mad... ;-)
4796  */
4797 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
4798 {
4799         mddev_t *mddev = bdev->bd_disk->private_data;
4800
4801         geo->heads = 2;
4802         geo->sectors = 4;
4803         geo->cylinders = get_capacity(mddev->gendisk) / 8;
4804         return 0;
4805 }
4806
4807 static int md_ioctl(struct inode *inode, struct file *file,
4808                         unsigned int cmd, unsigned long arg)
4809 {
4810         int err = 0;
4811         void __user *argp = (void __user *)arg;
4812         mddev_t *mddev = NULL;
4813
4814         if (!capable(CAP_SYS_ADMIN))
4815                 return -EACCES;
4816
4817         /*
4818          * Commands dealing with the RAID driver but not any
4819          * particular array:
4820          */
4821         switch (cmd)
4822         {
4823                 case RAID_VERSION:
4824                         err = get_version(argp);
4825                         goto done;
4826
4827                 case PRINT_RAID_DEBUG:
4828                         err = 0;
4829                         md_print_devices();
4830                         goto done;
4831
4832 #ifndef MODULE
4833                 case RAID_AUTORUN:
4834                         err = 0;
4835                         autostart_arrays(arg);
4836                         goto done;
4837 #endif
4838                 default:;
4839         }
4840
4841         /*
4842          * Commands creating/starting a new array:
4843          */
4844
4845         mddev = inode->i_bdev->bd_disk->private_data;
4846
4847         if (!mddev) {
4848                 BUG();
4849                 goto abort;
4850         }
4851
4852         err = mddev_lock(mddev);
4853         if (err) {
4854                 printk(KERN_INFO 
4855                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
4856                         err, cmd);
4857                 goto abort;
4858         }
4859
4860         switch (cmd)
4861         {
4862                 case SET_ARRAY_INFO:
4863                         {
4864                                 mdu_array_info_t info;
4865                                 if (!arg)
4866                                         memset(&info, 0, sizeof(info));
4867                                 else if (copy_from_user(&info, argp, sizeof(info))) {
4868                                         err = -EFAULT;
4869                                         goto abort_unlock;
4870                                 }
4871                                 if (mddev->pers) {
4872                                         err = update_array_info(mddev, &info);
4873                                         if (err) {
4874                                                 printk(KERN_WARNING "md: couldn't update"
4875                                                        " array info. %d\n", err);
4876                                                 goto abort_unlock;
4877                                         }
4878                                         goto done_unlock;
4879                                 }
4880                                 if (!list_empty(&mddev->disks)) {
4881                                         printk(KERN_WARNING
4882                                                "md: array %s already has disks!\n",
4883                                                mdname(mddev));
4884                                         err = -EBUSY;
4885                                         goto abort_unlock;
4886                                 }
4887                                 if (mddev->raid_disks) {
4888                                         printk(KERN_WARNING
4889                                                "md: array %s already initialised!\n",
4890                                                mdname(mddev));
4891                                         err = -EBUSY;
4892                                         goto abort_unlock;
4893                                 }
4894                                 err = set_array_info(mddev, &info);
4895                                 if (err) {
4896                                         printk(KERN_WARNING "md: couldn't set"
4897                                                " array info. %d\n", err);
4898                                         goto abort_unlock;
4899                                 }
4900                         }
4901                         goto done_unlock;
4902
4903                 default:;
4904         }
4905
4906         /*
4907          * Commands querying/configuring an existing array:
4908          */
4909         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
4910          * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
4911         if ((!mddev->raid_disks && !mddev->external)
4912             && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
4913             && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
4914             && cmd != GET_BITMAP_FILE) {
4915                 err = -ENODEV;
4916                 goto abort_unlock;
4917         }
4918
4919         /*
4920          * Commands even a read-only array can execute:
4921          */
4922         switch (cmd)
4923         {
4924                 case GET_ARRAY_INFO:
4925                         err = get_array_info(mddev, argp);
4926                         goto done_unlock;
4927
4928                 case GET_BITMAP_FILE:
4929                         err = get_bitmap_file(mddev, argp);
4930                         goto done_unlock;
4931
4932                 case GET_DISK_INFO:
4933                         err = get_disk_info(mddev, argp);
4934                         goto done_unlock;
4935
4936                 case RESTART_ARRAY_RW:
4937                         err = restart_array(mddev);
4938                         goto done_unlock;
4939
4940                 case STOP_ARRAY:
4941                         err = do_md_stop (mddev, 0, 1);
4942                         goto done_unlock;
4943
4944                 case STOP_ARRAY_RO:
4945                         err = do_md_stop (mddev, 1, 1);
4946                         goto done_unlock;
4947
4948         }
4949
4950         /*
4951          * The remaining ioctls are changing the state of the
4952          * superblock, so we do not allow them on read-only arrays.
4953          * However non-MD ioctls (e.g. get-size) will still come through
4954          * here and hit the 'default' below, so only disallow
4955          * 'md' ioctls, and switch to rw mode if started auto-readonly.
4956          */
4957         if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
4958                 if (mddev->ro == 2) {
4959                         mddev->ro = 0;
4960                         sysfs_notify(&mddev->kobj, NULL, "array_state");
4961                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4962                         md_wakeup_thread(mddev->thread);
4963                 } else {
4964                         err = -EROFS;
4965                         goto abort_unlock;
4966                 }
4967         }
4968
4969         switch (cmd)
4970         {
4971                 case ADD_NEW_DISK:
4972                 {
4973                         mdu_disk_info_t info;
4974                         if (copy_from_user(&info, argp, sizeof(info)))
4975                                 err = -EFAULT;
4976                         else
4977                                 err = add_new_disk(mddev, &info);
4978                         goto done_unlock;
4979                 }
4980
4981                 case HOT_REMOVE_DISK:
4982                         err = hot_remove_disk(mddev, new_decode_dev(arg));
4983                         goto done_unlock;
4984
4985                 case HOT_ADD_DISK:
4986                         err = hot_add_disk(mddev, new_decode_dev(arg));
4987                         goto done_unlock;
4988
4989                 case SET_DISK_FAULTY:
4990                         err = set_disk_faulty(mddev, new_decode_dev(arg));
4991                         goto done_unlock;
4992
4993                 case RUN_ARRAY:
4994                         err = do_md_run (mddev);
4995                         goto done_unlock;
4996
4997                 case SET_BITMAP_FILE:
4998                         err = set_bitmap_file(mddev, (int)arg);
4999                         goto done_unlock;
5000
5001                 default:
5002                         err = -EINVAL;
5003                         goto abort_unlock;
5004         }
5005
5006 done_unlock:
5007 abort_unlock:
5008         mddev_unlock(mddev);
5009
5010         return err;
5011 done:
5012         if (err)
5013                 MD_BUG();
5014 abort:
5015         return err;
5016 }
5017
5018 static int md_open(struct inode *inode, struct file *file)
5019 {
5020         /*
5021          * Succeed if we can lock the mddev, which confirms that
5022          * it isn't being stopped right now.
5023          */
5024         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
5025         int err;
5026
5027         if ((err = mutex_lock_interruptible_nested(&mddev->reconfig_mutex, 1)))
5028                 goto out;
5029
5030         err = 0;
5031         mddev_get(mddev);
5032         atomic_inc(&mddev->openers);
5033         mddev_unlock(mddev);
5034
5035         check_disk_change(inode->i_bdev);
5036  out:
5037         return err;
5038 }
5039
5040 static int md_release(struct inode *inode, struct file * file)
5041 {
5042         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
5043
5044         BUG_ON(!mddev);
5045         atomic_dec(&mddev->openers);
5046         mddev_put(mddev);
5047
5048         return 0;
5049 }
5050
5051 static int md_media_changed(struct gendisk *disk)
5052 {
5053         mddev_t *mddev = disk->private_data;
5054
5055         return mddev->changed;
5056 }
5057
5058 static int md_revalidate(struct gendisk *disk)
5059 {
5060         mddev_t *mddev = disk->private_data;
5061
5062         mddev->changed = 0;
5063         return 0;
5064 }
5065 static struct block_device_operations md_fops =
5066 {
5067         .owner          = THIS_MODULE,
5068         .open           = md_open,
5069         .release        = md_release,
5070         .ioctl          = md_ioctl,
5071         .getgeo         = md_getgeo,
5072         .media_changed  = md_media_changed,
5073         .revalidate_disk= md_revalidate,
5074 };
5075
5076 static int md_thread(void * arg)
5077 {
5078         mdk_thread_t *thread = arg;
5079
5080         /*
5081          * md_thread is a 'system-thread', it's priority should be very
5082          * high. We avoid resource deadlocks individually in each
5083          * raid personality. (RAID5 does preallocation) We also use RR and
5084          * the very same RT priority as kswapd, thus we will never get
5085          * into a priority inversion deadlock.
5086          *
5087          * we definitely have to have equal or higher priority than
5088          * bdflush, otherwise bdflush will deadlock if there are too
5089          * many dirty RAID5 blocks.
5090          */
5091
5092         allow_signal(SIGKILL);
5093         while (!kthread_should_stop()) {
5094
5095                 /* We need to wait INTERRUPTIBLE so that
5096                  * we don't add to the load-average.
5097                  * That means we need to be sure no signals are
5098                  * pending
5099                  */
5100                 if (signal_pending(current))
5101                         flush_signals(current);
5102
5103                 wait_event_interruptible_timeout
5104                         (thread->wqueue,
5105                          test_bit(THREAD_WAKEUP, &thread->flags)
5106                          || kthread_should_stop(),
5107                          thread->timeout);
5108
5109                 clear_bit(THREAD_WAKEUP, &thread->flags);
5110
5111                 thread->run(thread->mddev);
5112         }
5113
5114         return 0;
5115 }
5116
5117 void md_wakeup_thread(mdk_thread_t *thread)
5118 {
5119         if (thread) {
5120                 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
5121                 set_bit(THREAD_WAKEUP, &thread->flags);
5122                 wake_up(&thread->wqueue);
5123         }
5124 }
5125
5126 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
5127                                  const char *name)
5128 {
5129         mdk_thread_t *thread;
5130
5131         thread = kzalloc(sizeof(mdk_thread_t), GFP_KERNEL);
5132         if (!thread)
5133                 return NULL;
5134
5135         init_waitqueue_head(&thread->wqueue);
5136
5137         thread->run = run;
5138         thread->mddev = mddev;
5139         thread->timeout = MAX_SCHEDULE_TIMEOUT;
5140         thread->tsk = kthread_run(md_thread, thread, name, mdname(thread->mddev));
5141         if (IS_ERR(thread->tsk)) {
5142                 kfree(thread);
5143                 return NULL;
5144         }
5145         return thread;
5146 }
5147
5148 void md_unregister_thread(mdk_thread_t *thread)
5149 {
5150         dprintk("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
5151
5152         kthread_stop(thread->tsk);
5153         kfree(thread);
5154 }
5155
5156 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
5157 {
5158         if (!mddev) {
5159                 MD_BUG();
5160                 return;
5161         }
5162
5163         if (!rdev || test_bit(Faulty, &rdev->flags))
5164                 return;
5165
5166         if (mddev->external)
5167                 set_bit(Blocked, &rdev->flags);
5168 /*
5169         dprintk("md_error dev:%s, rdev:(%d:%d), (caller: %p,%p,%p,%p).\n",
5170                 mdname(mddev),
5171                 MAJOR(rdev->bdev->bd_dev), MINOR(rdev->bdev->bd_dev),
5172                 __builtin_return_address(0),__builtin_return_address(1),
5173                 __builtin_return_address(2),__builtin_return_address(3));
5174 */
5175         if (!mddev->pers)
5176                 return;
5177         if (!mddev->pers->error_handler)
5178                 return;
5179         mddev->pers->error_handler(mddev,rdev);
5180         if (mddev->degraded)
5181                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5182         set_bit(StateChanged, &rdev->flags);
5183         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5184         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5185         md_wakeup_thread(mddev->thread);
5186         md_new_event_inintr(mddev);
5187 }
5188
5189 /* seq_file implementation /proc/mdstat */
5190
5191 static void status_unused(struct seq_file *seq)
5192 {
5193         int i = 0;
5194         mdk_rdev_t *rdev;
5195         struct list_head *tmp;
5196
5197         seq_printf(seq, "unused devices: ");
5198
5199         rdev_for_each_list(rdev, tmp, pending_raid_disks) {
5200                 char b[BDEVNAME_SIZE];
5201                 i++;
5202                 seq_printf(seq, "%s ",
5203                               bdevname(rdev->bdev,b));
5204         }
5205         if (!i)
5206                 seq_printf(seq, "<none>");
5207
5208         seq_printf(seq, "\n");
5209 }
5210
5211
5212 static void status_resync(struct seq_file *seq, mddev_t * mddev)
5213 {
5214         sector_t max_blocks, resync, res;
5215         unsigned long dt, db, rt;
5216         int scale;
5217         unsigned int per_milli;
5218
5219         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active))/2;
5220
5221         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
5222                 max_blocks = mddev->resync_max_sectors >> 1;
5223         else
5224                 max_blocks = mddev->size;
5225
5226         /*
5227          * Should not happen.
5228          */
5229         if (!max_blocks) {
5230                 MD_BUG();
5231                 return;
5232         }
5233         /* Pick 'scale' such that (resync>>scale)*1000 will fit
5234          * in a sector_t, and (max_blocks>>scale) will fit in a
5235          * u32, as those are the requirements for sector_div.
5236          * Thus 'scale' must be at least 10
5237          */
5238         scale = 10;
5239         if (sizeof(sector_t) > sizeof(unsigned long)) {
5240                 while ( max_blocks/2 > (1ULL<<(scale+32)))
5241                         scale++;
5242         }
5243         res = (resync>>scale)*1000;
5244         sector_div(res, (u32)((max_blocks>>scale)+1));
5245
5246         per_milli = res;
5247         {
5248                 int i, x = per_milli/50, y = 20-x;
5249                 seq_printf(seq, "[");
5250                 for (i = 0; i < x; i++)
5251                         seq_printf(seq, "=");
5252                 seq_printf(seq, ">");
5253                 for (i = 0; i < y; i++)
5254                         seq_printf(seq, ".");
5255                 seq_printf(seq, "] ");
5256         }
5257         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
5258                    (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
5259                     "reshape" :
5260                     (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
5261                      "check" :
5262                      (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
5263                       "resync" : "recovery"))),
5264                    per_milli/10, per_milli % 10,
5265                    (unsigned long long) resync,
5266                    (unsigned long long) max_blocks);
5267
5268         /*
5269          * We do not want to overflow, so the order of operands and
5270          * the * 100 / 100 trick are important. We do a +1 to be
5271          * safe against division by zero. We only estimate anyway.
5272          *
5273          * dt: time from mark until now
5274          * db: blocks written from mark until now
5275          * rt: remaining time
5276          */
5277         dt = ((jiffies - mddev->resync_mark) / HZ);
5278         if (!dt) dt++;
5279         db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
5280                 - mddev->resync_mark_cnt;
5281         rt = (dt * ((unsigned long)(max_blocks-resync) / (db/2/100+1)))/100;
5282
5283         seq_printf(seq, " finish=%lu.%lumin", rt / 60, (rt % 60)/6);
5284
5285         seq_printf(seq, " speed=%ldK/sec", db/2/dt);
5286 }
5287
5288 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
5289 {
5290         struct list_head *tmp;
5291         loff_t l = *pos;
5292         mddev_t *mddev;
5293
5294         if (l >= 0x10000)
5295                 return NULL;
5296         if (!l--)
5297                 /* header */
5298                 return (void*)1;
5299
5300         spin_lock(&all_mddevs_lock);
5301         list_for_each(tmp,&all_mddevs)
5302                 if (!l--) {
5303                         mddev = list_entry(tmp, mddev_t, all_mddevs);
5304                         mddev_get(mddev);
5305                         spin_unlock(&all_mddevs_lock);
5306                         return mddev;
5307                 }
5308         spin_unlock(&all_mddevs_lock);
5309         if (!l--)
5310                 return (void*)2;/* tail */
5311         return NULL;
5312 }
5313
5314 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
5315 {
5316         struct list_head *tmp;
5317         mddev_t *next_mddev, *mddev = v;
5318         
5319         ++*pos;
5320         if (v == (void*)2)
5321                 return NULL;
5322
5323         spin_lock(&all_mddevs_lock);
5324         if (v == (void*)1)
5325                 tmp = all_mddevs.next;
5326         else
5327                 tmp = mddev->all_mddevs.next;
5328         if (tmp != &all_mddevs)
5329                 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
5330         else {
5331                 next_mddev = (void*)2;
5332                 *pos = 0x10000;
5333         }               
5334         spin_unlock(&all_mddevs_lock);
5335
5336         if (v != (void*)1)
5337                 mddev_put(mddev);
5338         return next_mddev;
5339
5340 }
5341
5342 static void md_seq_stop(struct seq_file *seq, void *v)
5343 {
5344         mddev_t *mddev = v;
5345
5346         if (mddev && v != (void*)1 && v != (void*)2)
5347                 mddev_put(mddev);
5348 }
5349
5350 struct mdstat_info {
5351         int event;
5352 };
5353
5354 static int md_seq_show(struct seq_file *seq, void *v)
5355 {
5356         mddev_t *mddev = v;
5357         sector_t size;
5358         struct list_head *tmp2;
5359         mdk_rdev_t *rdev;
5360         struct mdstat_info *mi = seq->private;
5361         struct bitmap *bitmap;
5362
5363         if (v == (void*)1) {
5364                 struct mdk_personality *pers;
5365                 seq_printf(seq, "Personalities : ");
5366                 spin_lock(&pers_lock);
5367                 list_for_each_entry(pers, &pers_list, list)
5368                         seq_printf(seq, "[%s] ", pers->name);
5369
5370                 spin_unlock(&pers_lock);
5371                 seq_printf(seq, "\n");
5372                 mi->event = atomic_read(&md_event_count);
5373                 return 0;
5374         }
5375         if (v == (void*)2) {
5376                 status_unused(seq);
5377                 return 0;
5378         }
5379
5380         if (mddev_lock(mddev) < 0)
5381                 return -EINTR;
5382
5383         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
5384                 seq_printf(seq, "%s : %sactive", mdname(mddev),
5385                                                 mddev->pers ? "" : "in");
5386                 if (mddev->pers) {
5387                         if (mddev->ro==1)
5388                                 seq_printf(seq, " (read-only)");
5389                         if (mddev->ro==2)
5390                                 seq_printf(seq, " (auto-read-only)");
5391                         seq_printf(seq, " %s", mddev->pers->name);
5392                 }
5393
5394                 size = 0;
5395                 rdev_for_each(rdev, tmp2, mddev) {
5396                         char b[BDEVNAME_SIZE];
5397                         seq_printf(seq, " %s[%d]",
5398                                 bdevname(rdev->bdev,b), rdev->desc_nr);
5399                         if (test_bit(WriteMostly, &rdev->flags))
5400                                 seq_printf(seq, "(W)");
5401                         if (test_bit(Faulty, &rdev->flags)) {
5402                                 seq_printf(seq, "(F)");
5403                                 continue;
5404                         } else if (rdev->raid_disk < 0)
5405                                 seq_printf(seq, "(S)"); /* spare */
5406                         size += rdev->size;
5407                 }
5408
5409                 if (!list_empty(&mddev->disks)) {
5410                         if (mddev->pers)
5411                                 seq_printf(seq, "\n      %llu blocks",
5412                                            (unsigned long long)
5413                                            mddev->array_sectors / 2);
5414                         else
5415                                 seq_printf(seq, "\n      %llu blocks",
5416                                            (unsigned long long)size);
5417                 }
5418                 if (mddev->persistent) {
5419                         if (mddev->major_version != 0 ||
5420                             mddev->minor_version != 90) {
5421                                 seq_printf(seq," super %d.%d",
5422                                            mddev->major_version,
5423                                            mddev->minor_version);
5424                         }
5425                 } else if (mddev->external)
5426                         seq_printf(seq, " super external:%s",
5427                                    mddev->metadata_type);
5428                 else
5429                         seq_printf(seq, " super non-persistent");
5430
5431                 if (mddev->pers) {
5432                         mddev->pers->status (seq, mddev);
5433                         seq_printf(seq, "\n      ");
5434                         if (mddev->pers->sync_request) {
5435                                 if (mddev->curr_resync > 2) {
5436                                         status_resync (seq, mddev);
5437                                         seq_printf(seq, "\n      ");
5438                                 } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
5439                                         seq_printf(seq, "\tresync=DELAYED\n      ");
5440                                 else if (mddev->recovery_cp < MaxSector)
5441                                         seq_printf(seq, "\tresync=PENDING\n      ");
5442                         }
5443                 } else
5444                         seq_printf(seq, "\n       ");
5445
5446                 if ((bitmap = mddev->bitmap)) {
5447                         unsigned long chunk_kb;
5448                         unsigned long flags;
5449                         spin_lock_irqsave(&bitmap->lock, flags);
5450                         chunk_kb = bitmap->chunksize >> 10;
5451                         seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
5452                                 "%lu%s chunk",
5453                                 bitmap->pages - bitmap->missing_pages,
5454                                 bitmap->pages,
5455                                 (bitmap->pages - bitmap->missing_pages)
5456                                         << (PAGE_SHIFT - 10),
5457                                 chunk_kb ? chunk_kb : bitmap->chunksize,
5458                                 chunk_kb ? "KB" : "B");
5459                         if (bitmap->file) {
5460                                 seq_printf(seq, ", file: ");
5461                                 seq_path(seq, &bitmap->file->f_path, " \t\n");
5462                         }
5463
5464                         seq_printf(seq, "\n");
5465                         spin_unlock_irqrestore(&bitmap->lock, flags);
5466                 }
5467
5468                 seq_printf(seq, "\n");
5469         }
5470         mddev_unlock(mddev);
5471         
5472         return 0;
5473 }
5474
5475 static struct seq_operations md_seq_ops = {
5476         .start  = md_seq_start,
5477         .next   = md_seq_next,
5478         .stop   = md_seq_stop,
5479         .show   = md_seq_show,
5480 };
5481
5482 static int md_seq_open(struct inode *inode, struct file *file)
5483 {
5484         int error;
5485         struct mdstat_info *mi = kmalloc(sizeof(*mi), GFP_KERNEL);
5486         if (mi == NULL)
5487                 return -ENOMEM;
5488
5489         error = seq_open(file, &md_seq_ops);
5490         if (error)
5491                 kfree(mi);
5492         else {
5493                 struct seq_file *p = file->private_data;
5494                 p->private = mi;
5495                 mi->event = atomic_read(&md_event_count);
5496         }
5497         return error;
5498 }
5499
5500 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
5501 {
5502         struct seq_file *m = filp->private_data;
5503         struct mdstat_info *mi = m->private;
5504         int mask;
5505
5506         poll_wait(filp, &md_event_waiters, wait);
5507
5508         /* always allow read */
5509         mask = POLLIN | POLLRDNORM;
5510
5511         if (mi->event != atomic_read(&md_event_count))
5512                 mask |= POLLERR | POLLPRI;
5513         return mask;
5514 }
5515
5516 static const struct file_operations md_seq_fops = {
5517         .owner          = THIS_MODULE,
5518         .open           = md_seq_open,
5519         .read           = seq_read,
5520         .llseek         = seq_lseek,
5521         .release        = seq_release_private,
5522         .poll           = mdstat_poll,
5523 };
5524
5525 int register_md_personality(struct mdk_personality *p)
5526 {
5527         spin_lock(&pers_lock);
5528         list_add_tail(&p->list, &pers_list);
5529         printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
5530         spin_unlock(&pers_lock);
5531         return 0;
5532 }
5533
5534 int unregister_md_personality(struct mdk_personality *p)
5535 {
5536         printk(KERN_INFO "md: %s personality unregistered\n", p->name);
5537         spin_lock(&pers_lock);
5538         list_del_init(&p->list);
5539         spin_unlock(&pers_lock);
5540         return 0;
5541 }
5542
5543 static int is_mddev_idle(mddev_t *mddev)
5544 {
5545         mdk_rdev_t * rdev;
5546         int idle;
5547         long curr_events;
5548
5549         idle = 1;
5550         rcu_read_lock();
5551         rdev_for_each_rcu(rdev, mddev) {
5552                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
5553                 curr_events = part_stat_read(&disk->part0, sectors[0]) +
5554                                 part_stat_read(&disk->part0, sectors[1]) -
5555                                 atomic_read(&disk->sync_io);
5556                 /* sync IO will cause sync_io to increase before the disk_stats
5557                  * as sync_io is counted when a request starts, and
5558                  * disk_stats is counted when it completes.
5559                  * So resync activity will cause curr_events to be smaller than
5560                  * when there was no such activity.
5561                  * non-sync IO will cause disk_stat to increase without
5562                  * increasing sync_io so curr_events will (eventually)
5563                  * be larger than it was before.  Once it becomes
5564                  * substantially larger, the test below will cause
5565                  * the array to appear non-idle, and resync will slow
5566                  * down.
5567                  * If there is a lot of outstanding resync activity when
5568                  * we set last_event to curr_events, then all that activity
5569                  * completing might cause the array to appear non-idle
5570                  * and resync will be slowed down even though there might
5571                  * not have been non-resync activity.  This will only
5572                  * happen once though.  'last_events' will soon reflect
5573                  * the state where there is little or no outstanding
5574                  * resync requests, and further resync activity will
5575                  * always make curr_events less than last_events.
5576                  *
5577                  */
5578                 if (curr_events - rdev->last_events > 4096) {
5579                         rdev->last_events = curr_events;
5580                         idle = 0;
5581                 }
5582         }
5583         rcu_read_unlock();
5584         return idle;
5585 }
5586
5587 void md_done_sync(mddev_t *mddev, int blocks, int ok)
5588 {
5589         /* another "blocks" (512byte) blocks have been synced */
5590         atomic_sub(blocks, &mddev->recovery_active);
5591         wake_up(&mddev->recovery_wait);
5592         if (!ok) {
5593                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5594                 md_wakeup_thread(mddev->thread);
5595                 // stop recovery, signal do_sync ....
5596         }
5597 }
5598
5599
5600 /* md_write_start(mddev, bi)
5601  * If we need to update some array metadata (e.g. 'active' flag
5602  * in superblock) before writing, schedule a superblock update
5603  * and wait for it to complete.
5604  */
5605 void md_write_start(mddev_t *mddev, struct bio *bi)
5606 {
5607         int did_change = 0;
5608         if (bio_data_dir(bi) != WRITE)
5609                 return;
5610
5611         BUG_ON(mddev->ro == 1);
5612         if (mddev->ro == 2) {
5613                 /* need to switch to read/write */
5614                 mddev->ro = 0;
5615                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5616                 md_wakeup_thread(mddev->thread);
5617                 md_wakeup_thread(mddev->sync_thread);
5618                 did_change = 1;
5619         }
5620         atomic_inc(&mddev->writes_pending);
5621         if (mddev->safemode == 1)
5622                 mddev->safemode = 0;
5623         if (mddev->in_sync) {
5624                 spin_lock_irq(&mddev->write_lock);
5625                 if (mddev->in_sync) {
5626                         mddev->in_sync = 0;
5627                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
5628                         md_wakeup_thread(mddev->thread);
5629                         did_change = 1;
5630                 }
5631                 spin_unlock_irq(&mddev->write_lock);
5632         }
5633         if (did_change)
5634                 sysfs_notify(&mddev->kobj, NULL, "array_state");
5635         wait_event(mddev->sb_wait,
5636                    !test_bit(MD_CHANGE_CLEAN, &mddev->flags) &&
5637                    !test_bit(MD_CHANGE_PENDING, &mddev->flags));
5638 }
5639
5640 void md_write_end(mddev_t *mddev)
5641 {
5642         if (atomic_dec_and_test(&mddev->writes_pending)) {
5643                 if (mddev->safemode == 2)
5644                         md_wakeup_thread(mddev->thread);
5645                 else if (mddev->safemode_delay)
5646                         mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
5647         }
5648 }
5649
5650 /* md_allow_write(mddev)
5651  * Calling this ensures that the array is marked 'active' so that writes
5652  * may proceed without blocking.  It is important to call this before
5653  * attempting a GFP_KERNEL allocation while holding the mddev lock.
5654  * Must be called with mddev_lock held.
5655  *
5656  * In the ->external case MD_CHANGE_CLEAN can not be cleared until mddev->lock
5657  * is dropped, so return -EAGAIN after notifying userspace.
5658  */
5659 int md_allow_write(mddev_t *mddev)
5660 {
5661         if (!mddev->pers)
5662                 return 0;
5663         if (mddev->ro)
5664                 return 0;
5665         if (!mddev->pers->sync_request)
5666                 return 0;
5667
5668         spin_lock_irq(&mddev->write_lock);
5669         if (mddev->in_sync) {
5670                 mddev->in_sync = 0;
5671                 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
5672                 if (mddev->safemode_delay &&
5673                     mddev->safemode == 0)
5674                         mddev->safemode = 1;
5675                 spin_unlock_irq(&mddev->write_lock);
5676                 md_update_sb(mddev, 0);
5677                 sysfs_notify(&mddev->kobj, NULL, "array_state");
5678         } else
5679                 spin_unlock_irq(&mddev->write_lock);
5680
5681         if (test_bit(MD_CHANGE_CLEAN, &mddev->flags))
5682                 return -EAGAIN;
5683         else
5684                 return 0;
5685 }
5686 EXPORT_SYMBOL_GPL(md_allow_write);
5687
5688 #define SYNC_MARKS      10
5689 #define SYNC_MARK_STEP  (3*HZ)
5690 void md_do_sync(mddev_t *mddev)
5691 {
5692         mddev_t *mddev2;
5693         unsigned int currspeed = 0,
5694                  window;
5695         sector_t max_sectors,j, io_sectors;
5696         unsigned long mark[SYNC_MARKS];
5697         sector_t mark_cnt[SYNC_MARKS];
5698         int last_mark,m;
5699         struct list_head *tmp;
5700         sector_t last_check;
5701         int skipped = 0;
5702         struct list_head *rtmp;
5703         mdk_rdev_t *rdev;
5704         char *desc;
5705
5706         /* just incase thread restarts... */
5707         if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
5708                 return;
5709         if (mddev->ro) /* never try to sync a read-only array */
5710                 return;
5711
5712         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5713                 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
5714                         desc = "data-check";
5715                 else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
5716                         desc = "requested-resync";
5717                 else
5718                         desc = "resync";
5719         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5720                 desc = "reshape";
5721         else
5722                 desc = "recovery";
5723
5724         /* we overload curr_resync somewhat here.
5725          * 0 == not engaged in resync at all
5726          * 2 == checking that there is no conflict with another sync
5727          * 1 == like 2, but have yielded to allow conflicting resync to
5728          *              commense
5729          * other == active in resync - this many blocks
5730          *
5731          * Before starting a resync we must have set curr_resync to
5732          * 2, and then checked that every "conflicting" array has curr_resync
5733          * less than ours.  When we find one that is the same or higher
5734          * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
5735          * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
5736          * This will mean we have to start checking from the beginning again.
5737          *
5738          */
5739
5740         do {
5741                 mddev->curr_resync = 2;
5742
5743         try_again:
5744                 if (kthread_should_stop()) {
5745                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5746                         goto skip;
5747                 }
5748                 for_each_mddev(mddev2, tmp) {
5749                         if (mddev2 == mddev)
5750                                 continue;
5751                         if (!mddev->parallel_resync
5752                         &&  mddev2->curr_resync
5753                         &&  match_mddev_units(mddev, mddev2)) {
5754                                 DEFINE_WAIT(wq);
5755                                 if (mddev < mddev2 && mddev->curr_resync == 2) {
5756                                         /* arbitrarily yield */
5757                                         mddev->curr_resync = 1;
5758                                         wake_up(&resync_wait);
5759                                 }
5760                                 if (mddev > mddev2 && mddev->curr_resync == 1)
5761                                         /* no need to wait here, we can wait the next
5762                                          * time 'round when curr_resync == 2
5763                                          */
5764                                         continue;
5765                                 /* We need to wait 'interruptible' so as not to
5766                                  * contribute to the load average, and not to
5767                                  * be caught by 'softlockup'
5768                                  */
5769                                 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
5770                                 if (!kthread_should_stop() &&
5771                                     mddev2->curr_resync >= mddev->curr_resync) {
5772                                         printk(KERN_INFO "md: delaying %s of %s"
5773                                                " until %s has finished (they"
5774                                                " share one or more physical units)\n",
5775                                                desc, mdname(mddev), mdname(mddev2));
5776                                         mddev_put(mddev2);
5777                                         if (signal_pending(current))
5778                                                 flush_signals(current);
5779                                         schedule();
5780                                         finish_wait(&resync_wait, &wq);
5781                                         goto try_again;
5782                                 }
5783                                 finish_wait(&resync_wait, &wq);
5784                         }
5785                 }
5786         } while (mddev->curr_resync < 2);
5787
5788         j = 0;
5789         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5790                 /* resync follows the size requested by the personality,
5791                  * which defaults to physical size, but can be virtual size
5792                  */
5793                 max_sectors = mddev->resync_max_sectors;
5794                 mddev->resync_mismatches = 0;
5795                 /* we don't use the checkpoint if there's a bitmap */
5796                 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
5797                         j = mddev->resync_min;
5798                 else if (!mddev->bitmap)
5799                         j = mddev->recovery_cp;
5800
5801         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5802                 max_sectors = mddev->size << 1;
5803         else {
5804                 /* recovery follows the physical size of devices */
5805                 max_sectors = mddev->size << 1;
5806                 j = MaxSector;
5807                 rdev_for_each(rdev, rtmp, mddev)
5808                         if (rdev->raid_disk >= 0 &&
5809                             !test_bit(Faulty, &rdev->flags) &&
5810                             !test_bit(In_sync, &rdev->flags) &&
5811                             rdev->recovery_offset < j)
5812                                 j = rdev->recovery_offset;
5813         }
5814
5815         printk(KERN_INFO "md: %s of RAID array %s\n", desc, mdname(mddev));
5816         printk(KERN_INFO "md: minimum _guaranteed_  speed:"
5817                 " %d KB/sec/disk.\n", speed_min(mddev));
5818         printk(KERN_INFO "md: using maximum available idle IO bandwidth "
5819                "(but not more than %d KB/sec) for %s.\n",
5820                speed_max(mddev), desc);
5821
5822         is_mddev_idle(mddev); /* this also initializes IO event counters */
5823
5824         io_sectors = 0;
5825         for (m = 0; m < SYNC_MARKS; m++) {
5826                 mark[m] = jiffies;
5827                 mark_cnt[m] = io_sectors;
5828         }
5829         last_mark = 0;
5830         mddev->resync_mark = mark[last_mark];
5831         mddev->resync_mark_cnt = mark_cnt[last_mark];
5832
5833         /*
5834          * Tune reconstruction:
5835          */
5836         window = 32*(PAGE_SIZE/512);
5837         printk(KERN_INFO "md: using %dk window, over a total of %llu blocks.\n",
5838                 window/2,(unsigned long long) max_sectors/2);
5839
5840         atomic_set(&mddev->recovery_active, 0);
5841         last_check = 0;
5842
5843         if (j>2) {
5844                 printk(KERN_INFO 
5845                        "md: resuming %s of %s from checkpoint.\n",
5846                        desc, mdname(mddev));
5847                 mddev->curr_resync = j;
5848         }
5849
5850         while (j < max_sectors) {
5851                 sector_t sectors;
5852
5853                 skipped = 0;
5854                 if (j >= mddev->resync_max) {
5855                         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5856                         wait_event(mddev->recovery_wait,
5857                                    mddev->resync_max > j
5858                                    || kthread_should_stop());
5859                 }
5860                 if (kthread_should_stop())
5861                         goto interrupted;
5862                 sectors = mddev->pers->sync_request(mddev, j, &skipped,
5863                                                   currspeed < speed_min(mddev));
5864                 if (sectors == 0) {
5865                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5866                         goto out;
5867                 }
5868
5869                 if (!skipped) { /* actual IO requested */
5870                         io_sectors += sectors;
5871                         atomic_add(sectors, &mddev->recovery_active);
5872                 }
5873
5874                 j += sectors;
5875                 if (j>1) mddev->curr_resync = j;
5876                 mddev->curr_mark_cnt = io_sectors;
5877                 if (last_check == 0)
5878                         /* this is the earliers that rebuilt will be
5879                          * visible in /proc/mdstat
5880                          */
5881                         md_new_event(mddev);
5882
5883                 if (last_check + window > io_sectors || j == max_sectors)
5884                         continue;
5885
5886                 last_check = io_sectors;
5887
5888                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5889                         break;
5890
5891         repeat:
5892                 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
5893                         /* step marks */
5894                         int next = (last_mark+1) % SYNC_MARKS;
5895
5896                         mddev->resync_mark = mark[next];
5897                         mddev->resync_mark_cnt = mark_cnt[next];
5898                         mark[next] = jiffies;
5899                         mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
5900                         last_mark = next;
5901                 }
5902
5903
5904                 if (kthread_should_stop())
5905                         goto interrupted;
5906
5907
5908                 /*
5909                  * this loop exits only if either when we are slower than
5910                  * the 'hard' speed limit, or the system was IO-idle for
5911                  * a jiffy.
5912                  * the system might be non-idle CPU-wise, but we only care
5913                  * about not overloading the IO subsystem. (things like an
5914                  * e2fsck being done on the RAID array should execute fast)
5915                  */
5916                 blk_unplug(mddev->queue);
5917                 cond_resched();
5918
5919                 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
5920                         /((jiffies-mddev->resync_mark)/HZ +1) +1;
5921
5922                 if (currspeed > speed_min(mddev)) {
5923                         if ((currspeed > speed_max(mddev)) ||
5924                                         !is_mddev_idle(mddev)) {
5925                                 msleep(500);
5926                                 goto repeat;
5927                         }
5928                 }
5929         }
5930         printk(KERN_INFO "md: %s: %s done.\n",mdname(mddev), desc);
5931         /*
5932          * this also signals 'finished resyncing' to md_stop
5933          */
5934  out:
5935         blk_unplug(mddev->queue);
5936
5937         wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
5938
5939         /* tell personality that we are finished */
5940         mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
5941
5942         if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
5943             mddev->curr_resync > 2) {
5944                 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5945                         if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
5946                                 if (mddev->curr_resync >= mddev->recovery_cp) {
5947                                         printk(KERN_INFO
5948                                                "md: checkpointing %s of %s.\n",
5949                                                desc, mdname(mddev));
5950                                         mddev->recovery_cp = mddev->curr_resync;
5951                                 }
5952                         } else
5953                                 mddev->recovery_cp = MaxSector;
5954                 } else {
5955                         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5956                                 mddev->curr_resync = MaxSector;
5957                         rdev_for_each(rdev, rtmp, mddev)
5958                                 if (rdev->raid_disk >= 0 &&
5959                                     !test_bit(Faulty, &rdev->flags) &&
5960                                     !test_bit(In_sync, &rdev->flags) &&
5961                                     rdev->recovery_offset < mddev->curr_resync)
5962                                         rdev->recovery_offset = mddev->curr_resync;
5963                 }
5964         }
5965         set_bit(MD_CHANGE_DEVS, &mddev->flags);
5966
5967  skip:
5968         mddev->curr_resync = 0;
5969         mddev->resync_min = 0;
5970         mddev->resync_max = MaxSector;
5971         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5972         wake_up(&resync_wait);
5973         set_bit(MD_RECOVERY_DONE, &mddev->recovery);
5974         md_wakeup_thread(mddev->thread);
5975         return;
5976
5977  interrupted:
5978         /*
5979          * got a signal, exit.
5980          */
5981         printk(KERN_INFO
5982                "md: md_do_sync() got signal ... exiting\n");
5983         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5984         goto out;
5985
5986 }
5987 EXPORT_SYMBOL_GPL(md_do_sync);
5988
5989
5990 static int remove_and_add_spares(mddev_t *mddev)
5991 {
5992         mdk_rdev_t *rdev;
5993         struct list_head *rtmp;
5994         int spares = 0;
5995
5996         rdev_for_each(rdev, rtmp, mddev)
5997                 if (rdev->raid_disk >= 0 &&
5998                     !test_bit(Blocked, &rdev->flags) &&
5999                     (test_bit(Faulty, &rdev->flags) ||
6000                      ! test_bit(In_sync, &rdev->flags)) &&
6001                     atomic_read(&rdev->nr_pending)==0) {
6002                         if (mddev->pers->hot_remove_disk(
6003                                     mddev, rdev->raid_disk)==0) {
6004                                 char nm[20];
6005                                 sprintf(nm,"rd%d", rdev->raid_disk);
6006                                 sysfs_remove_link(&mddev->kobj, nm);
6007                                 rdev->raid_disk = -1;
6008                         }
6009                 }
6010
6011         if (mddev->degraded && ! mddev->ro) {
6012                 rdev_for_each(rdev, rtmp, mddev) {
6013                         if (rdev->raid_disk >= 0 &&
6014                             !test_bit(In_sync, &rdev->flags) &&
6015                             !test_bit(Blocked, &rdev->flags))
6016                                 spares++;
6017                         if (rdev->raid_disk < 0
6018                             && !test_bit(Faulty, &rdev->flags)) {
6019                                 rdev->recovery_offset = 0;
6020                                 if (mddev->pers->
6021                                     hot_add_disk(mddev, rdev) == 0) {
6022                                         char nm[20];
6023                                         sprintf(nm, "rd%d", rdev->raid_disk);
6024                                         if (sysfs_create_link(&mddev->kobj,
6025                                                               &rdev->kobj, nm))
6026                                                 printk(KERN_WARNING
6027                                                        "md: cannot register "
6028                                                        "%s for %s\n",
6029                                                        nm, mdname(mddev));
6030                                         spares++;
6031                                         md_new_event(mddev);
6032                                 } else
6033                                         break;
6034                         }
6035                 }
6036         }
6037         return spares;
6038 }
6039 /*
6040  * This routine is regularly called by all per-raid-array threads to
6041  * deal with generic issues like resync and super-block update.
6042  * Raid personalities that don't have a thread (linear/raid0) do not
6043  * need this as they never do any recovery or update the superblock.
6044  *
6045  * It does not do any resync itself, but rather "forks" off other threads
6046  * to do that as needed.
6047  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
6048  * "->recovery" and create a thread at ->sync_thread.
6049  * When the thread finishes it sets MD_RECOVERY_DONE
6050  * and wakeups up this thread which will reap the thread and finish up.
6051  * This thread also removes any faulty devices (with nr_pending == 0).
6052  *
6053  * The overall approach is:
6054  *  1/ if the superblock needs updating, update it.
6055  *  2/ If a recovery thread is running, don't do anything else.
6056  *  3/ If recovery has finished, clean up, possibly marking spares active.
6057  *  4/ If there are any faulty devices, remove them.
6058  *  5/ If array is degraded, try to add spares devices
6059  *  6/ If array has spares or is not in-sync, start a resync thread.
6060  */
6061 void md_check_recovery(mddev_t *mddev)
6062 {
6063         mdk_rdev_t *rdev;
6064         struct list_head *rtmp;
6065
6066
6067         if (mddev->bitmap)
6068                 bitmap_daemon_work(mddev->bitmap);
6069
6070         if (test_and_clear_bit(MD_NOTIFY_ARRAY_STATE, &mddev->flags))
6071                 sysfs_notify(&mddev->kobj, NULL, "array_state");
6072
6073         if (mddev->ro)
6074                 return;
6075
6076         if (signal_pending(current)) {
6077                 if (mddev->pers->sync_request && !mddev->external) {
6078                         printk(KERN_INFO "md: %s in immediate safe mode\n",
6079                                mdname(mddev));
6080                         mddev->safemode = 2;
6081                 }
6082                 flush_signals(current);
6083         }
6084
6085         if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
6086                 return;
6087         if ( ! (
6088                 (mddev->flags && !mddev->external) ||
6089                 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
6090                 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
6091                 (mddev->external == 0 && mddev->safemode == 1) ||
6092                 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
6093                  && !mddev->in_sync && mddev->recovery_cp == MaxSector)
6094                 ))
6095                 return;
6096
6097         if (mddev_trylock(mddev)) {
6098                 int spares = 0;
6099
6100                 if (mddev->ro) {
6101                         /* Only thing we do on a ro array is remove
6102                          * failed devices.
6103                          */
6104                         remove_and_add_spares(mddev);
6105                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6106                         goto unlock;
6107                 }
6108
6109                 if (!mddev->external) {
6110                         int did_change = 0;
6111                         spin_lock_irq(&mddev->write_lock);
6112                         if (mddev->safemode &&
6113                             !atomic_read(&mddev->writes_pending) &&
6114                             !mddev->in_sync &&
6115                             mddev->recovery_cp == MaxSector) {
6116                                 mddev->in_sync = 1;
6117                                 did_change = 1;
6118                                 if (mddev->persistent)
6119                                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
6120                         }
6121                         if (mddev->safemode == 1)
6122                                 mddev->safemode = 0;
6123                         spin_unlock_irq(&mddev->write_lock);
6124                         if (did_change)
6125                                 sysfs_notify(&mddev->kobj, NULL, "array_state");
6126                 }
6127
6128                 if (mddev->flags)
6129                         md_update_sb(mddev, 0);
6130
6131                 rdev_for_each(rdev, rtmp, mddev)
6132                         if (test_and_clear_bit(StateChanged, &rdev->flags))
6133                                 sysfs_notify(&rdev->kobj, NULL, "state");
6134
6135
6136                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
6137                     !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
6138                         /* resync/recovery still happening */
6139                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6140                         goto unlock;
6141                 }
6142                 if (mddev->sync_thread) {
6143                         /* resync has finished, collect result */
6144                         md_unregister_thread(mddev->sync_thread);
6145                         mddev->sync_thread = NULL;
6146                         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
6147                             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
6148                                 /* success...*/
6149                                 /* activate any spares */
6150                                 if (mddev->pers->spare_active(mddev))
6151                                         sysfs_notify(&mddev->kobj, NULL,
6152                                                      "degraded");
6153                         }
6154                         md_update_sb(mddev, 1);
6155
6156                         /* if array is no-longer degraded, then any saved_raid_disk
6157                          * information must be scrapped
6158                          */
6159                         if (!mddev->degraded)
6160                                 rdev_for_each(rdev, rtmp, mddev)
6161                                         rdev->saved_raid_disk = -1;
6162
6163                         mddev->recovery = 0;
6164                         /* flag recovery needed just to double check */
6165                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6166                         sysfs_notify(&mddev->kobj, NULL, "sync_action");
6167                         md_new_event(mddev);
6168                         goto unlock;
6169                 }
6170                 /* Set RUNNING before clearing NEEDED to avoid
6171                  * any transients in the value of "sync_action".
6172                  */
6173                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6174                 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6175                 /* Clear some bits that don't mean anything, but
6176                  * might be left set
6177                  */
6178                 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
6179                 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
6180
6181                 if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
6182                         goto unlock;
6183                 /* no recovery is running.
6184                  * remove any failed drives, then
6185                  * add spares if possible.
6186                  * Spare are also removed and re-added, to allow
6187                  * the personality to fail the re-add.
6188                  */
6189
6190                 if (mddev->reshape_position != MaxSector) {
6191                         if (mddev->pers->check_reshape(mddev) != 0)
6192                                 /* Cannot proceed */
6193                                 goto unlock;
6194                         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
6195                         clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6196                 } else if ((spares = remove_and_add_spares(mddev))) {
6197                         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6198                         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
6199                         clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
6200                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6201                 } else if (mddev->recovery_cp < MaxSector) {
6202                         set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6203                         clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6204                 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
6205                         /* nothing to be done ... */
6206                         goto unlock;
6207
6208                 if (mddev->pers->sync_request) {
6209                         if (spares && mddev->bitmap && ! mddev->bitmap->file) {
6210                                 /* We are adding a device or devices to an array
6211                                  * which has the bitmap stored on all devices.
6212                                  * So make sure all bitmap pages get written
6213                                  */
6214                                 bitmap_write_all(mddev->bitmap);
6215                         }
6216                         mddev->sync_thread = md_register_thread(md_do_sync,
6217                                                                 mddev,
6218                                                                 "%s_resync");
6219                         if (!mddev->sync_thread) {
6220                                 printk(KERN_ERR "%s: could not start resync"
6221                                         " thread...\n", 
6222                                         mdname(mddev));
6223                                 /* leave the spares where they are, it shouldn't hurt */
6224                                 mddev->recovery = 0;
6225                         } else
6226                                 md_wakeup_thread(mddev->sync_thread);
6227                         sysfs_notify(&mddev->kobj, NULL, "sync_action");
6228                         md_new_event(mddev);
6229                 }
6230         unlock:
6231                 if (!mddev->sync_thread) {
6232                         clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6233                         if (test_and_clear_bit(MD_RECOVERY_RECOVER,
6234                                                &mddev->recovery))
6235                                 sysfs_notify(&mddev->kobj, NULL, "sync_action");
6236                 }
6237                 mddev_unlock(mddev);
6238         }
6239 }
6240
6241 void md_wait_for_blocked_rdev(mdk_rdev_t *rdev, mddev_t *mddev)
6242 {
6243         sysfs_notify(&rdev->kobj, NULL, "state");
6244         wait_event_timeout(rdev->blocked_wait,
6245                            !test_bit(Blocked, &rdev->flags),
6246                            msecs_to_jiffies(5000));
6247         rdev_dec_pending(rdev, mddev);
6248 }
6249 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
6250
6251 static int md_notify_reboot(struct notifier_block *this,
6252                             unsigned long code, void *x)
6253 {
6254         struct list_head *tmp;
6255         mddev_t *mddev;
6256
6257         if ((code == SYS_DOWN) || (code == SYS_HALT) || (code == SYS_POWER_OFF)) {
6258
6259                 printk(KERN_INFO "md: stopping all md devices.\n");
6260
6261                 for_each_mddev(mddev, tmp)
6262                         if (mddev_trylock(mddev)) {
6263                                 /* Force a switch to readonly even array
6264                                  * appears to still be in use.  Hence
6265                                  * the '100'.
6266                                  */
6267                                 do_md_stop (mddev, 1, 100);
6268                                 mddev_unlock(mddev);
6269                         }
6270                 /*
6271                  * certain more exotic SCSI devices are known to be
6272                  * volatile wrt too early system reboots. While the
6273                  * right place to handle this issue is the given
6274                  * driver, we do want to have a safe RAID driver ...
6275                  */
6276                 mdelay(1000*1);
6277         }
6278         return NOTIFY_DONE;
6279 }
6280
6281 static struct notifier_block md_notifier = {
6282         .notifier_call  = md_notify_reboot,
6283         .next           = NULL,
6284         .priority       = INT_MAX, /* before any real devices */
6285 };
6286
6287 static void md_geninit(void)
6288 {
6289         dprintk("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
6290
6291         proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
6292 }
6293
6294 static int __init md_init(void)
6295 {
6296         if (register_blkdev(MAJOR_NR, "md"))
6297                 return -1;
6298         if ((mdp_major=register_blkdev(0, "mdp"))<=0) {
6299                 unregister_blkdev(MAJOR_NR, "md");
6300                 return -1;
6301         }
6302         blk_register_region(MKDEV(MAJOR_NR, 0), 1UL<<MINORBITS, THIS_MODULE,
6303                             md_probe, NULL, NULL);
6304         blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
6305                             md_probe, NULL, NULL);
6306
6307         register_reboot_notifier(&md_notifier);
6308         raid_table_header = register_sysctl_table(raid_root_table);
6309
6310         md_geninit();
6311         return (0);
6312 }
6313
6314
6315 #ifndef MODULE
6316
6317 /*
6318  * Searches all registered partitions for autorun RAID arrays
6319  * at boot time.
6320  */
6321
6322 static LIST_HEAD(all_detected_devices);
6323 struct detected_devices_node {
6324         struct list_head list;
6325         dev_t dev;
6326 };
6327
6328 void md_autodetect_dev(dev_t dev)
6329 {
6330         struct detected_devices_node *node_detected_dev;
6331
6332         node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
6333         if (node_detected_dev) {
6334                 node_detected_dev->dev = dev;
6335                 list_add_tail(&node_detected_dev->list, &all_detected_devices);
6336         } else {
6337                 printk(KERN_CRIT "md: md_autodetect_dev: kzalloc failed"
6338                         ", skipping dev(%d,%d)\n", MAJOR(dev), MINOR(dev));
6339         }
6340 }
6341
6342
6343 static void autostart_arrays(int part)
6344 {
6345         mdk_rdev_t *rdev;
6346         struct detected_devices_node *node_detected_dev;
6347         dev_t dev;
6348         int i_scanned, i_passed;
6349
6350         i_scanned = 0;
6351         i_passed = 0;
6352
6353         printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
6354
6355         while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
6356                 i_scanned++;
6357                 node_detected_dev = list_entry(all_detected_devices.next,
6358                                         struct detected_devices_node, list);
6359                 list_del(&node_detected_dev->list);
6360                 dev = node_detected_dev->dev;
6361                 kfree(node_detected_dev);
6362                 rdev = md_import_device(dev,0, 90);
6363                 if (IS_ERR(rdev))
6364                         continue;
6365
6366                 if (test_bit(Faulty, &rdev->flags)) {
6367                         MD_BUG();
6368                         continue;
6369                 }
6370                 set_bit(AutoDetected, &rdev->flags);
6371                 list_add(&rdev->same_set, &pending_raid_disks);
6372                 i_passed++;
6373         }
6374
6375         printk(KERN_INFO "md: Scanned %d and added %d devices.\n",
6376                                                 i_scanned, i_passed);
6377
6378         autorun_devices(part);
6379 }
6380
6381 #endif /* !MODULE */
6382
6383 static __exit void md_exit(void)
6384 {
6385         mddev_t *mddev;
6386         struct list_head *tmp;
6387
6388         blk_unregister_region(MKDEV(MAJOR_NR,0), 1U << MINORBITS);
6389         blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
6390
6391         unregister_blkdev(MAJOR_NR,"md");
6392         unregister_blkdev(mdp_major, "mdp");
6393         unregister_reboot_notifier(&md_notifier);
6394         unregister_sysctl_table(raid_table_header);
6395         remove_proc_entry("mdstat", NULL);
6396         for_each_mddev(mddev, tmp) {
6397                 struct gendisk *disk = mddev->gendisk;
6398                 if (!disk)
6399                         continue;
6400                 export_array(mddev);
6401                 del_gendisk(disk);
6402                 put_disk(disk);
6403                 mddev->gendisk = NULL;
6404                 mddev_put(mddev);
6405         }
6406 }
6407
6408 subsys_initcall(md_init);
6409 module_exit(md_exit)
6410
6411 static int get_ro(char *buffer, struct kernel_param *kp)
6412 {
6413         return sprintf(buffer, "%d", start_readonly);
6414 }
6415 static int set_ro(const char *val, struct kernel_param *kp)
6416 {
6417         char *e;
6418         int num = simple_strtoul(val, &e, 10);
6419         if (*val && (*e == '\0' || *e == '\n')) {
6420                 start_readonly = num;
6421                 return 0;
6422         }
6423         return -EINVAL;
6424 }
6425
6426 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
6427 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
6428
6429
6430 EXPORT_SYMBOL(register_md_personality);
6431 EXPORT_SYMBOL(unregister_md_personality);
6432 EXPORT_SYMBOL(md_error);
6433 EXPORT_SYMBOL(md_done_sync);
6434 EXPORT_SYMBOL(md_write_start);
6435 EXPORT_SYMBOL(md_write_end);
6436 EXPORT_SYMBOL(md_register_thread);
6437 EXPORT_SYMBOL(md_unregister_thread);
6438 EXPORT_SYMBOL(md_wakeup_thread);
6439 EXPORT_SYMBOL(md_check_recovery);
6440 MODULE_LICENSE("GPL");
6441 MODULE_ALIAS("md");
6442 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);