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