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