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