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