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