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