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