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