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