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