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