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