ccbbf63727cc03fe06fb26bf03debcd9f8e97b6f
[sfrench/cifs-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
280         new->queue = blk_alloc_queue(GFP_KERNEL);
281         if (!new->queue) {
282                 kfree(new);
283                 return NULL;
284         }
285         set_bit(QUEUE_FLAG_CLUSTER, &new->queue->queue_flags);
286
287         blk_queue_make_request(new->queue, md_fail_request);
288
289         goto retry;
290 }
291
292 static inline int mddev_lock(mddev_t * mddev)
293 {
294         return mutex_lock_interruptible(&mddev->reconfig_mutex);
295 }
296
297 static inline int mddev_trylock(mddev_t * mddev)
298 {
299         return mutex_trylock(&mddev->reconfig_mutex);
300 }
301
302 static inline void mddev_unlock(mddev_t * mddev)
303 {
304         mutex_unlock(&mddev->reconfig_mutex);
305
306         md_wakeup_thread(mddev->thread);
307 }
308
309 static mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
310 {
311         mdk_rdev_t * rdev;
312         struct list_head *tmp;
313
314         rdev_for_each(rdev, tmp, mddev) {
315                 if (rdev->desc_nr == nr)
316                         return rdev;
317         }
318         return NULL;
319 }
320
321 static mdk_rdev_t * find_rdev(mddev_t * mddev, dev_t dev)
322 {
323         struct list_head *tmp;
324         mdk_rdev_t *rdev;
325
326         rdev_for_each(rdev, tmp, mddev) {
327                 if (rdev->bdev->bd_dev == dev)
328                         return rdev;
329         }
330         return NULL;
331 }
332
333 static struct mdk_personality *find_pers(int level, char *clevel)
334 {
335         struct mdk_personality *pers;
336         list_for_each_entry(pers, &pers_list, list) {
337                 if (level != LEVEL_NONE && pers->level == level)
338                         return pers;
339                 if (strcmp(pers->name, clevel)==0)
340                         return pers;
341         }
342         return NULL;
343 }
344
345 static inline sector_t calc_dev_sboffset(struct block_device *bdev)
346 {
347         sector_t size = bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
348         return MD_NEW_SIZE_BLOCKS(size);
349 }
350
351 static sector_t calc_dev_size(mdk_rdev_t *rdev, unsigned chunk_size)
352 {
353         sector_t size;
354
355         size = rdev->sb_offset;
356
357         if (chunk_size)
358                 size &= ~((sector_t)chunk_size/1024 - 1);
359         return size;
360 }
361
362 static int alloc_disk_sb(mdk_rdev_t * rdev)
363 {
364         if (rdev->sb_page)
365                 MD_BUG();
366
367         rdev->sb_page = alloc_page(GFP_KERNEL);
368         if (!rdev->sb_page) {
369                 printk(KERN_ALERT "md: out of memory.\n");
370                 return -EINVAL;
371         }
372
373         return 0;
374 }
375
376 static void free_disk_sb(mdk_rdev_t * rdev)
377 {
378         if (rdev->sb_page) {
379                 put_page(rdev->sb_page);
380                 rdev->sb_loaded = 0;
381                 rdev->sb_page = NULL;
382                 rdev->sb_offset = 0;
383                 rdev->size = 0;
384         }
385 }
386
387
388 static void super_written(struct bio *bio, int error)
389 {
390         mdk_rdev_t *rdev = bio->bi_private;
391         mddev_t *mddev = rdev->mddev;
392
393         if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
394                 printk("md: super_written gets error=%d, uptodate=%d\n",
395                        error, test_bit(BIO_UPTODATE, &bio->bi_flags));
396                 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
397                 md_error(mddev, rdev);
398         }
399
400         if (atomic_dec_and_test(&mddev->pending_writes))
401                 wake_up(&mddev->sb_wait);
402         bio_put(bio);
403 }
404
405 static void super_written_barrier(struct bio *bio, int error)
406 {
407         struct bio *bio2 = bio->bi_private;
408         mdk_rdev_t *rdev = bio2->bi_private;
409         mddev_t *mddev = rdev->mddev;
410
411         if (!test_bit(BIO_UPTODATE, &bio->bi_flags) &&
412             error == -EOPNOTSUPP) {
413                 unsigned long flags;
414                 /* barriers don't appear to be supported :-( */
415                 set_bit(BarriersNotsupp, &rdev->flags);
416                 mddev->barriers_work = 0;
417                 spin_lock_irqsave(&mddev->write_lock, flags);
418                 bio2->bi_next = mddev->biolist;
419                 mddev->biolist = bio2;
420                 spin_unlock_irqrestore(&mddev->write_lock, flags);
421                 wake_up(&mddev->sb_wait);
422                 bio_put(bio);
423         } else {
424                 bio_put(bio2);
425                 bio->bi_private = rdev;
426                 super_written(bio, error);
427         }
428 }
429
430 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
431                    sector_t sector, int size, struct page *page)
432 {
433         /* write first size bytes of page to sector of rdev
434          * Increment mddev->pending_writes before returning
435          * and decrement it on completion, waking up sb_wait
436          * if zero is reached.
437          * If an error occurred, call md_error
438          *
439          * As we might need to resubmit the request if BIO_RW_BARRIER
440          * causes ENOTSUPP, we allocate a spare bio...
441          */
442         struct bio *bio = bio_alloc(GFP_NOIO, 1);
443         int rw = (1<<BIO_RW) | (1<<BIO_RW_SYNC);
444
445         bio->bi_bdev = rdev->bdev;
446         bio->bi_sector = sector;
447         bio_add_page(bio, page, size, 0);
448         bio->bi_private = rdev;
449         bio->bi_end_io = super_written;
450         bio->bi_rw = rw;
451
452         atomic_inc(&mddev->pending_writes);
453         if (!test_bit(BarriersNotsupp, &rdev->flags)) {
454                 struct bio *rbio;
455                 rw |= (1<<BIO_RW_BARRIER);
456                 rbio = bio_clone(bio, GFP_NOIO);
457                 rbio->bi_private = bio;
458                 rbio->bi_end_io = super_written_barrier;
459                 submit_bio(rw, rbio);
460         } else
461                 submit_bio(rw, bio);
462 }
463
464 void md_super_wait(mddev_t *mddev)
465 {
466         /* wait for all superblock writes that were scheduled to complete.
467          * if any had to be retried (due to BARRIER problems), retry them
468          */
469         DEFINE_WAIT(wq);
470         for(;;) {
471                 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
472                 if (atomic_read(&mddev->pending_writes)==0)
473                         break;
474                 while (mddev->biolist) {
475                         struct bio *bio;
476                         spin_lock_irq(&mddev->write_lock);
477                         bio = mddev->biolist;
478                         mddev->biolist = bio->bi_next ;
479                         bio->bi_next = NULL;
480                         spin_unlock_irq(&mddev->write_lock);
481                         submit_bio(bio->bi_rw, bio);
482                 }
483                 schedule();
484         }
485         finish_wait(&mddev->sb_wait, &wq);
486 }
487
488 static void bi_complete(struct bio *bio, int error)
489 {
490         complete((struct completion*)bio->bi_private);
491 }
492
493 int sync_page_io(struct block_device *bdev, sector_t sector, int size,
494                    struct page *page, int rw)
495 {
496         struct bio *bio = bio_alloc(GFP_NOIO, 1);
497         struct completion event;
498         int ret;
499
500         rw |= (1 << BIO_RW_SYNC);
501
502         bio->bi_bdev = bdev;
503         bio->bi_sector = sector;
504         bio_add_page(bio, page, size, 0);
505         init_completion(&event);
506         bio->bi_private = &event;
507         bio->bi_end_io = bi_complete;
508         submit_bio(rw, bio);
509         wait_for_completion(&event);
510
511         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
512         bio_put(bio);
513         return ret;
514 }
515 EXPORT_SYMBOL_GPL(sync_page_io);
516
517 static int read_disk_sb(mdk_rdev_t * rdev, int size)
518 {
519         char b[BDEVNAME_SIZE];
520         if (!rdev->sb_page) {
521                 MD_BUG();
522                 return -EINVAL;
523         }
524         if (rdev->sb_loaded)
525                 return 0;
526
527
528         if (!sync_page_io(rdev->bdev, rdev->sb_offset<<1, size, rdev->sb_page, READ))
529                 goto fail;
530         rdev->sb_loaded = 1;
531         return 0;
532
533 fail:
534         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
535                 bdevname(rdev->bdev,b));
536         return -EINVAL;
537 }
538
539 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
540 {
541         if (    (sb1->set_uuid0 == sb2->set_uuid0) &&
542                 (sb1->set_uuid1 == sb2->set_uuid1) &&
543                 (sb1->set_uuid2 == sb2->set_uuid2) &&
544                 (sb1->set_uuid3 == sb2->set_uuid3))
545
546                 return 1;
547
548         return 0;
549 }
550
551
552 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
553 {
554         int ret;
555         mdp_super_t *tmp1, *tmp2;
556
557         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
558         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
559
560         if (!tmp1 || !tmp2) {
561                 ret = 0;
562                 printk(KERN_INFO "md.c: sb1 is not equal to sb2!\n");
563                 goto abort;
564         }
565
566         *tmp1 = *sb1;
567         *tmp2 = *sb2;
568
569         /*
570          * nr_disks is not constant
571          */
572         tmp1->nr_disks = 0;
573         tmp2->nr_disks = 0;
574
575         if (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4))
576                 ret = 0;
577         else
578                 ret = 1;
579
580 abort:
581         kfree(tmp1);
582         kfree(tmp2);
583         return ret;
584 }
585
586
587 static u32 md_csum_fold(u32 csum)
588 {
589         csum = (csum & 0xffff) + (csum >> 16);
590         return (csum & 0xffff) + (csum >> 16);
591 }
592
593 static unsigned int calc_sb_csum(mdp_super_t * sb)
594 {
595         u64 newcsum = 0;
596         u32 *sb32 = (u32*)sb;
597         int i;
598         unsigned int disk_csum, csum;
599
600         disk_csum = sb->sb_csum;
601         sb->sb_csum = 0;
602
603         for (i = 0; i < MD_SB_BYTES/4 ; i++)
604                 newcsum += sb32[i];
605         csum = (newcsum & 0xffffffff) + (newcsum>>32);
606
607
608 #ifdef CONFIG_ALPHA
609         /* This used to use csum_partial, which was wrong for several
610          * reasons including that different results are returned on
611          * different architectures.  It isn't critical that we get exactly
612          * the same return value as before (we always csum_fold before
613          * testing, and that removes any differences).  However as we
614          * know that csum_partial always returned a 16bit value on
615          * alphas, do a fold to maximise conformity to previous behaviour.
616          */
617         sb->sb_csum = md_csum_fold(disk_csum);
618 #else
619         sb->sb_csum = disk_csum;
620 #endif
621         return csum;
622 }
623
624
625 /*
626  * Handle superblock details.
627  * We want to be able to handle multiple superblock formats
628  * so we have a common interface to them all, and an array of
629  * different handlers.
630  * We rely on user-space to write the initial superblock, and support
631  * reading and updating of superblocks.
632  * Interface methods are:
633  *   int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
634  *      loads and validates a superblock on dev.
635  *      if refdev != NULL, compare superblocks on both devices
636  *    Return:
637  *      0 - dev has a superblock that is compatible with refdev
638  *      1 - dev has a superblock that is compatible and newer than refdev
639  *          so dev should be used as the refdev in future
640  *     -EINVAL superblock incompatible or invalid
641  *     -othererror e.g. -EIO
642  *
643  *   int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
644  *      Verify that dev is acceptable into mddev.
645  *       The first time, mddev->raid_disks will be 0, and data from
646  *       dev should be merged in.  Subsequent calls check that dev
647  *       is new enough.  Return 0 or -EINVAL
648  *
649  *   void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
650  *     Update the superblock for rdev with data in mddev
651  *     This does not write to disc.
652  *
653  */
654
655 struct super_type  {
656         char            *name;
657         struct module   *owner;
658         int             (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version);
659         int             (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
660         void            (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
661 };
662
663 /*
664  * load_super for 0.90.0 
665  */
666 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
667 {
668         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
669         mdp_super_t *sb;
670         int ret;
671         sector_t sb_offset;
672
673         /*
674          * Calculate the position of the superblock,
675          * it's at the end of the disk.
676          *
677          * It also happens to be a multiple of 4Kb.
678          */
679         sb_offset = calc_dev_sboffset(rdev->bdev);
680         rdev->sb_offset = sb_offset;
681
682         ret = read_disk_sb(rdev, MD_SB_BYTES);
683         if (ret) return ret;
684
685         ret = -EINVAL;
686
687         bdevname(rdev->bdev, b);
688         sb = (mdp_super_t*)page_address(rdev->sb_page);
689
690         if (sb->md_magic != MD_SB_MAGIC) {
691                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
692                        b);
693                 goto abort;
694         }
695
696         if (sb->major_version != 0 ||
697             sb->minor_version < 90 ||
698             sb->minor_version > 91) {
699                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
700                         sb->major_version, sb->minor_version,
701                         b);
702                 goto abort;
703         }
704
705         if (sb->raid_disks <= 0)
706                 goto abort;
707
708         if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
709                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
710                         b);
711                 goto abort;
712         }
713
714         rdev->preferred_minor = sb->md_minor;
715         rdev->data_offset = 0;
716         rdev->sb_size = MD_SB_BYTES;
717
718         if (sb->state & (1<<MD_SB_BITMAP_PRESENT)) {
719                 if (sb->level != 1 && sb->level != 4
720                     && sb->level != 5 && sb->level != 6
721                     && sb->level != 10) {
722                         /* FIXME use a better test */
723                         printk(KERN_WARNING
724                                "md: bitmaps not supported for this level.\n");
725                         goto abort;
726                 }
727         }
728
729         if (sb->level == LEVEL_MULTIPATH)
730                 rdev->desc_nr = -1;
731         else
732                 rdev->desc_nr = sb->this_disk.number;
733
734         if (refdev == 0)
735                 ret = 1;
736         else {
737                 __u64 ev1, ev2;
738                 mdp_super_t *refsb = (mdp_super_t*)page_address(refdev->sb_page);
739                 if (!uuid_equal(refsb, sb)) {
740                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
741                                 b, bdevname(refdev->bdev,b2));
742                         goto abort;
743                 }
744                 if (!sb_equal(refsb, sb)) {
745                         printk(KERN_WARNING "md: %s has same UUID"
746                                " but different superblock to %s\n",
747                                b, bdevname(refdev->bdev, b2));
748                         goto abort;
749                 }
750                 ev1 = md_event(sb);
751                 ev2 = md_event(refsb);
752                 if (ev1 > ev2)
753                         ret = 1;
754                 else 
755                         ret = 0;
756         }
757         rdev->size = calc_dev_size(rdev, sb->chunk_size);
758
759         if (rdev->size < sb->size && sb->level > 1)
760                 /* "this cannot possibly happen" ... */
761                 ret = -EINVAL;
762
763  abort:
764         return ret;
765 }
766
767 /*
768  * validate_super for 0.90.0
769  */
770 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
771 {
772         mdp_disk_t *desc;
773         mdp_super_t *sb = (mdp_super_t *)page_address(rdev->sb_page);
774         __u64 ev1 = md_event(sb);
775
776         rdev->raid_disk = -1;
777         clear_bit(Faulty, &rdev->flags);
778         clear_bit(In_sync, &rdev->flags);
779         clear_bit(WriteMostly, &rdev->flags);
780         clear_bit(BarriersNotsupp, &rdev->flags);
781
782         if (mddev->raid_disks == 0) {
783                 mddev->major_version = 0;
784                 mddev->minor_version = sb->minor_version;
785                 mddev->patch_version = sb->patch_version;
786                 mddev->external = 0;
787                 mddev->chunk_size = sb->chunk_size;
788                 mddev->ctime = sb->ctime;
789                 mddev->utime = sb->utime;
790                 mddev->level = sb->level;
791                 mddev->clevel[0] = 0;
792                 mddev->layout = sb->layout;
793                 mddev->raid_disks = sb->raid_disks;
794                 mddev->size = sb->size;
795                 mddev->events = ev1;
796                 mddev->bitmap_offset = 0;
797                 mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
798
799                 if (mddev->minor_version >= 91) {
800                         mddev->reshape_position = sb->reshape_position;
801                         mddev->delta_disks = sb->delta_disks;
802                         mddev->new_level = sb->new_level;
803                         mddev->new_layout = sb->new_layout;
804                         mddev->new_chunk = sb->new_chunk;
805                 } else {
806                         mddev->reshape_position = MaxSector;
807                         mddev->delta_disks = 0;
808                         mddev->new_level = mddev->level;
809                         mddev->new_layout = mddev->layout;
810                         mddev->new_chunk = mddev->chunk_size;
811                 }
812
813                 if (sb->state & (1<<MD_SB_CLEAN))
814                         mddev->recovery_cp = MaxSector;
815                 else {
816                         if (sb->events_hi == sb->cp_events_hi && 
817                                 sb->events_lo == sb->cp_events_lo) {
818                                 mddev->recovery_cp = sb->recovery_cp;
819                         } else
820                                 mddev->recovery_cp = 0;
821                 }
822
823                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
824                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
825                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
826                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
827
828                 mddev->max_disks = MD_SB_DISKS;
829
830                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
831                     mddev->bitmap_file == NULL)
832                         mddev->bitmap_offset = mddev->default_bitmap_offset;
833
834         } else if (mddev->pers == NULL) {
835                 /* Insist on good event counter while assembling */
836                 ++ev1;
837                 if (ev1 < mddev->events) 
838                         return -EINVAL;
839         } else if (mddev->bitmap) {
840                 /* if adding to array with a bitmap, then we can accept an
841                  * older device ... but not too old.
842                  */
843                 if (ev1 < mddev->bitmap->events_cleared)
844                         return 0;
845         } else {
846                 if (ev1 < mddev->events)
847                         /* just a hot-add of a new device, leave raid_disk at -1 */
848                         return 0;
849         }
850
851         if (mddev->level != LEVEL_MULTIPATH) {
852                 desc = sb->disks + rdev->desc_nr;
853
854                 if (desc->state & (1<<MD_DISK_FAULTY))
855                         set_bit(Faulty, &rdev->flags);
856                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
857                             desc->raid_disk < mddev->raid_disks */) {
858                         set_bit(In_sync, &rdev->flags);
859                         rdev->raid_disk = desc->raid_disk;
860                 }
861                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
862                         set_bit(WriteMostly, &rdev->flags);
863         } else /* MULTIPATH are always insync */
864                 set_bit(In_sync, &rdev->flags);
865         return 0;
866 }
867
868 /*
869  * sync_super for 0.90.0
870  */
871 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
872 {
873         mdp_super_t *sb;
874         struct list_head *tmp;
875         mdk_rdev_t *rdev2;
876         int next_spare = mddev->raid_disks;
877
878
879         /* make rdev->sb match mddev data..
880          *
881          * 1/ zero out disks
882          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
883          * 3/ any empty disks < next_spare become removed
884          *
885          * disks[0] gets initialised to REMOVED because
886          * we cannot be sure from other fields if it has
887          * been initialised or not.
888          */
889         int i;
890         int active=0, working=0,failed=0,spare=0,nr_disks=0;
891
892         rdev->sb_size = MD_SB_BYTES;
893
894         sb = (mdp_super_t*)page_address(rdev->sb_page);
895
896         memset(sb, 0, sizeof(*sb));
897
898         sb->md_magic = MD_SB_MAGIC;
899         sb->major_version = mddev->major_version;
900         sb->patch_version = mddev->patch_version;
901         sb->gvalid_words  = 0; /* ignored */
902         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
903         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
904         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
905         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
906
907         sb->ctime = mddev->ctime;
908         sb->level = mddev->level;
909         sb->size  = mddev->size;
910         sb->raid_disks = mddev->raid_disks;
911         sb->md_minor = mddev->md_minor;
912         sb->not_persistent = 0;
913         sb->utime = mddev->utime;
914         sb->state = 0;
915         sb->events_hi = (mddev->events>>32);
916         sb->events_lo = (u32)mddev->events;
917
918         if (mddev->reshape_position == MaxSector)
919                 sb->minor_version = 90;
920         else {
921                 sb->minor_version = 91;
922                 sb->reshape_position = mddev->reshape_position;
923                 sb->new_level = mddev->new_level;
924                 sb->delta_disks = mddev->delta_disks;
925                 sb->new_layout = mddev->new_layout;
926                 sb->new_chunk = mddev->new_chunk;
927         }
928         mddev->minor_version = sb->minor_version;
929         if (mddev->in_sync)
930         {
931                 sb->recovery_cp = mddev->recovery_cp;
932                 sb->cp_events_hi = (mddev->events>>32);
933                 sb->cp_events_lo = (u32)mddev->events;
934                 if (mddev->recovery_cp == MaxSector)
935                         sb->state = (1<< MD_SB_CLEAN);
936         } else
937                 sb->recovery_cp = 0;
938
939         sb->layout = mddev->layout;
940         sb->chunk_size = mddev->chunk_size;
941
942         if (mddev->bitmap && mddev->bitmap_file == NULL)
943                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
944
945         sb->disks[0].state = (1<<MD_DISK_REMOVED);
946         rdev_for_each(rdev2, tmp, mddev) {
947                 mdp_disk_t *d;
948                 int desc_nr;
949                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
950                     && !test_bit(Faulty, &rdev2->flags))
951                         desc_nr = rdev2->raid_disk;
952                 else
953                         desc_nr = next_spare++;
954                 rdev2->desc_nr = desc_nr;
955                 d = &sb->disks[rdev2->desc_nr];
956                 nr_disks++;
957                 d->number = rdev2->desc_nr;
958                 d->major = MAJOR(rdev2->bdev->bd_dev);
959                 d->minor = MINOR(rdev2->bdev->bd_dev);
960                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
961                     && !test_bit(Faulty, &rdev2->flags))
962                         d->raid_disk = rdev2->raid_disk;
963                 else
964                         d->raid_disk = rdev2->desc_nr; /* compatibility */
965                 if (test_bit(Faulty, &rdev2->flags))
966                         d->state = (1<<MD_DISK_FAULTY);
967                 else if (test_bit(In_sync, &rdev2->flags)) {
968                         d->state = (1<<MD_DISK_ACTIVE);
969                         d->state |= (1<<MD_DISK_SYNC);
970                         active++;
971                         working++;
972                 } else {
973                         d->state = 0;
974                         spare++;
975                         working++;
976                 }
977                 if (test_bit(WriteMostly, &rdev2->flags))
978                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
979         }
980         /* now set the "removed" and "faulty" bits on any missing devices */
981         for (i=0 ; i < mddev->raid_disks ; i++) {
982                 mdp_disk_t *d = &sb->disks[i];
983                 if (d->state == 0 && d->number == 0) {
984                         d->number = i;
985                         d->raid_disk = i;
986                         d->state = (1<<MD_DISK_REMOVED);
987                         d->state |= (1<<MD_DISK_FAULTY);
988                         failed++;
989                 }
990         }
991         sb->nr_disks = nr_disks;
992         sb->active_disks = active;
993         sb->working_disks = working;
994         sb->failed_disks = failed;
995         sb->spare_disks = spare;
996
997         sb->this_disk = sb->disks[rdev->desc_nr];
998         sb->sb_csum = calc_sb_csum(sb);
999 }
1000
1001 /*
1002  * version 1 superblock
1003  */
1004
1005 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1006 {
1007         __le32 disk_csum;
1008         u32 csum;
1009         unsigned long long newcsum;
1010         int size = 256 + le32_to_cpu(sb->max_dev)*2;
1011         __le32 *isuper = (__le32*)sb;
1012         int i;
1013
1014         disk_csum = sb->sb_csum;
1015         sb->sb_csum = 0;
1016         newcsum = 0;
1017         for (i=0; size>=4; size -= 4 )
1018                 newcsum += le32_to_cpu(*isuper++);
1019
1020         if (size == 2)
1021                 newcsum += le16_to_cpu(*(__le16*) isuper);
1022
1023         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1024         sb->sb_csum = disk_csum;
1025         return cpu_to_le32(csum);
1026 }
1027
1028 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
1029 {
1030         struct mdp_superblock_1 *sb;
1031         int ret;
1032         sector_t sb_offset;
1033         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1034         int bmask;
1035
1036         /*
1037          * Calculate the position of the superblock.
1038          * It is always aligned to a 4K boundary and
1039          * depeding on minor_version, it can be:
1040          * 0: At least 8K, but less than 12K, from end of device
1041          * 1: At start of device
1042          * 2: 4K from start of device.
1043          */
1044         switch(minor_version) {
1045         case 0:
1046                 sb_offset = rdev->bdev->bd_inode->i_size >> 9;
1047                 sb_offset -= 8*2;
1048                 sb_offset &= ~(sector_t)(4*2-1);
1049                 /* convert from sectors to K */
1050                 sb_offset /= 2;
1051                 break;
1052         case 1:
1053                 sb_offset = 0;
1054                 break;
1055         case 2:
1056                 sb_offset = 4;
1057                 break;
1058         default:
1059                 return -EINVAL;
1060         }
1061         rdev->sb_offset = sb_offset;
1062
1063         /* superblock is rarely larger than 1K, but it can be larger,
1064          * and it is safe to read 4k, so we do that
1065          */
1066         ret = read_disk_sb(rdev, 4096);
1067         if (ret) return ret;
1068
1069
1070         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1071
1072         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1073             sb->major_version != cpu_to_le32(1) ||
1074             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1075             le64_to_cpu(sb->super_offset) != (rdev->sb_offset<<1) ||
1076             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1077                 return -EINVAL;
1078
1079         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1080                 printk("md: invalid superblock checksum on %s\n",
1081                         bdevname(rdev->bdev,b));
1082                 return -EINVAL;
1083         }
1084         if (le64_to_cpu(sb->data_size) < 10) {
1085                 printk("md: data_size too small on %s\n",
1086                        bdevname(rdev->bdev,b));
1087                 return -EINVAL;
1088         }
1089         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET)) {
1090                 if (sb->level != cpu_to_le32(1) &&
1091                     sb->level != cpu_to_le32(4) &&
1092                     sb->level != cpu_to_le32(5) &&
1093                     sb->level != cpu_to_le32(6) &&
1094                     sb->level != cpu_to_le32(10)) {
1095                         printk(KERN_WARNING
1096                                "md: bitmaps not supported for this level.\n");
1097                         return -EINVAL;
1098                 }
1099         }
1100
1101         rdev->preferred_minor = 0xffff;
1102         rdev->data_offset = le64_to_cpu(sb->data_offset);
1103         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1104
1105         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1106         bmask = queue_hardsect_size(rdev->bdev->bd_disk->queue)-1;
1107         if (rdev->sb_size & bmask)
1108                 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1109
1110         if (minor_version
1111             && rdev->data_offset < sb_offset + (rdev->sb_size/512))
1112                 return -EINVAL;
1113
1114         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1115                 rdev->desc_nr = -1;
1116         else
1117                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1118
1119         if (refdev == 0)
1120                 ret = 1;
1121         else {
1122                 __u64 ev1, ev2;
1123                 struct mdp_superblock_1 *refsb = 
1124                         (struct mdp_superblock_1*)page_address(refdev->sb_page);
1125
1126                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1127                     sb->level != refsb->level ||
1128                     sb->layout != refsb->layout ||
1129                     sb->chunksize != refsb->chunksize) {
1130                         printk(KERN_WARNING "md: %s has strangely different"
1131                                 " superblock to %s\n",
1132                                 bdevname(rdev->bdev,b),
1133                                 bdevname(refdev->bdev,b2));
1134                         return -EINVAL;
1135                 }
1136                 ev1 = le64_to_cpu(sb->events);
1137                 ev2 = le64_to_cpu(refsb->events);
1138
1139                 if (ev1 > ev2)
1140                         ret = 1;
1141                 else
1142                         ret = 0;
1143         }
1144         if (minor_version)
1145                 rdev->size = ((rdev->bdev->bd_inode->i_size>>9) - le64_to_cpu(sb->data_offset)) / 2;
1146         else
1147                 rdev->size = rdev->sb_offset;
1148         if (rdev->size < le64_to_cpu(sb->data_size)/2)
1149                 return -EINVAL;
1150         rdev->size = le64_to_cpu(sb->data_size)/2;
1151         if (le32_to_cpu(sb->chunksize))
1152                 rdev->size &= ~((sector_t)le32_to_cpu(sb->chunksize)/2 - 1);
1153
1154         if (le64_to_cpu(sb->size) > rdev->size*2)
1155                 return -EINVAL;
1156         return ret;
1157 }
1158
1159 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1160 {
1161         struct mdp_superblock_1 *sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1162         __u64 ev1 = le64_to_cpu(sb->events);
1163
1164         rdev->raid_disk = -1;
1165         clear_bit(Faulty, &rdev->flags);
1166         clear_bit(In_sync, &rdev->flags);
1167         clear_bit(WriteMostly, &rdev->flags);
1168         clear_bit(BarriersNotsupp, &rdev->flags);
1169
1170         if (mddev->raid_disks == 0) {
1171                 mddev->major_version = 1;
1172                 mddev->patch_version = 0;
1173                 mddev->external = 0;
1174                 mddev->chunk_size = le32_to_cpu(sb->chunksize) << 9;
1175                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1176                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1177                 mddev->level = le32_to_cpu(sb->level);
1178                 mddev->clevel[0] = 0;
1179                 mddev->layout = le32_to_cpu(sb->layout);
1180                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1181                 mddev->size = le64_to_cpu(sb->size)/2;
1182                 mddev->events = ev1;
1183                 mddev->bitmap_offset = 0;
1184                 mddev->default_bitmap_offset = 1024 >> 9;
1185                 
1186                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1187                 memcpy(mddev->uuid, sb->set_uuid, 16);
1188
1189                 mddev->max_disks =  (4096-256)/2;
1190
1191                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1192                     mddev->bitmap_file == NULL )
1193                         mddev->bitmap_offset = (__s32)le32_to_cpu(sb->bitmap_offset);
1194
1195                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1196                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1197                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1198                         mddev->new_level = le32_to_cpu(sb->new_level);
1199                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1200                         mddev->new_chunk = le32_to_cpu(sb->new_chunk)<<9;
1201                 } else {
1202                         mddev->reshape_position = MaxSector;
1203                         mddev->delta_disks = 0;
1204                         mddev->new_level = mddev->level;
1205                         mddev->new_layout = mddev->layout;
1206                         mddev->new_chunk = mddev->chunk_size;
1207                 }
1208
1209         } else if (mddev->pers == NULL) {
1210                 /* Insist of good event counter while assembling */
1211                 ++ev1;
1212                 if (ev1 < mddev->events)
1213                         return -EINVAL;
1214         } else if (mddev->bitmap) {
1215                 /* If adding to array with a bitmap, then we can accept an
1216                  * older device, but not too old.
1217                  */
1218                 if (ev1 < mddev->bitmap->events_cleared)
1219                         return 0;
1220         } else {
1221                 if (ev1 < mddev->events)
1222                         /* just a hot-add of a new device, leave raid_disk at -1 */
1223                         return 0;
1224         }
1225         if (mddev->level != LEVEL_MULTIPATH) {
1226                 int role;
1227                 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1228                 switch(role) {
1229                 case 0xffff: /* spare */
1230                         break;
1231                 case 0xfffe: /* faulty */
1232                         set_bit(Faulty, &rdev->flags);
1233                         break;
1234                 default:
1235                         if ((le32_to_cpu(sb->feature_map) &
1236                              MD_FEATURE_RECOVERY_OFFSET))
1237                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1238                         else
1239                                 set_bit(In_sync, &rdev->flags);
1240                         rdev->raid_disk = role;
1241                         break;
1242                 }
1243                 if (sb->devflags & WriteMostly1)
1244                         set_bit(WriteMostly, &rdev->flags);
1245         } else /* MULTIPATH are always insync */
1246                 set_bit(In_sync, &rdev->flags);
1247
1248         return 0;
1249 }
1250
1251 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1252 {
1253         struct mdp_superblock_1 *sb;
1254         struct list_head *tmp;
1255         mdk_rdev_t *rdev2;
1256         int max_dev, i;
1257         /* make rdev->sb match mddev and rdev data. */
1258
1259         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1260
1261         sb->feature_map = 0;
1262         sb->pad0 = 0;
1263         sb->recovery_offset = cpu_to_le64(0);
1264         memset(sb->pad1, 0, sizeof(sb->pad1));
1265         memset(sb->pad2, 0, sizeof(sb->pad2));
1266         memset(sb->pad3, 0, sizeof(sb->pad3));
1267
1268         sb->utime = cpu_to_le64((__u64)mddev->utime);
1269         sb->events = cpu_to_le64(mddev->events);
1270         if (mddev->in_sync)
1271                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1272         else
1273                 sb->resync_offset = cpu_to_le64(0);
1274
1275         sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1276
1277         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1278         sb->size = cpu_to_le64(mddev->size<<1);
1279
1280         if (mddev->bitmap && mddev->bitmap_file == NULL) {
1281                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_offset);
1282                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1283         }
1284
1285         if (rdev->raid_disk >= 0 &&
1286             !test_bit(In_sync, &rdev->flags) &&
1287             rdev->recovery_offset > 0) {
1288                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1289                 sb->recovery_offset = cpu_to_le64(rdev->recovery_offset);
1290         }
1291
1292         if (mddev->reshape_position != MaxSector) {
1293                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1294                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1295                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1296                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1297                 sb->new_level = cpu_to_le32(mddev->new_level);
1298                 sb->new_chunk = cpu_to_le32(mddev->new_chunk>>9);
1299         }
1300
1301         max_dev = 0;
1302         rdev_for_each(rdev2, tmp, mddev)
1303                 if (rdev2->desc_nr+1 > max_dev)
1304                         max_dev = rdev2->desc_nr+1;
1305
1306         if (max_dev > le32_to_cpu(sb->max_dev))
1307                 sb->max_dev = cpu_to_le32(max_dev);
1308         for (i=0; i<max_dev;i++)
1309                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1310         
1311         rdev_for_each(rdev2, tmp, mddev) {
1312                 i = rdev2->desc_nr;
1313                 if (test_bit(Faulty, &rdev2->flags))
1314                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1315                 else if (test_bit(In_sync, &rdev2->flags))
1316                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1317                 else if (rdev2->raid_disk >= 0 && rdev2->recovery_offset > 0)
1318                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1319                 else
1320                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1321         }
1322
1323         sb->sb_csum = calc_sb_1_csum(sb);
1324 }
1325
1326
1327 static struct super_type super_types[] = {
1328         [0] = {
1329                 .name   = "0.90.0",
1330                 .owner  = THIS_MODULE,
1331                 .load_super     = super_90_load,
1332                 .validate_super = super_90_validate,
1333                 .sync_super     = super_90_sync,
1334         },
1335         [1] = {
1336                 .name   = "md-1",
1337                 .owner  = THIS_MODULE,
1338                 .load_super     = super_1_load,
1339                 .validate_super = super_1_validate,
1340                 .sync_super     = super_1_sync,
1341         },
1342 };
1343
1344 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1345 {
1346         struct list_head *tmp, *tmp2;
1347         mdk_rdev_t *rdev, *rdev2;
1348
1349         rdev_for_each(rdev, tmp, mddev1)
1350                 rdev_for_each(rdev2, tmp2, mddev2)
1351                         if (rdev->bdev->bd_contains ==
1352                             rdev2->bdev->bd_contains)
1353                                 return 1;
1354
1355         return 0;
1356 }
1357
1358 static LIST_HEAD(pending_raid_disks);
1359
1360 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1361 {
1362         char b[BDEVNAME_SIZE];
1363         struct kobject *ko;
1364         char *s;
1365         int err;
1366
1367         if (rdev->mddev) {
1368                 MD_BUG();
1369                 return -EINVAL;
1370         }
1371         /* make sure rdev->size exceeds mddev->size */
1372         if (rdev->size && (mddev->size == 0 || rdev->size < mddev->size)) {
1373                 if (mddev->pers) {
1374                         /* Cannot change size, so fail
1375                          * If mddev->level <= 0, then we don't care
1376                          * about aligning sizes (e.g. linear)
1377                          */
1378                         if (mddev->level > 0)
1379                                 return -ENOSPC;
1380                 } else
1381                         mddev->size = rdev->size;
1382         }
1383
1384         /* Verify rdev->desc_nr is unique.
1385          * If it is -1, assign a free number, else
1386          * check number is not in use
1387          */
1388         if (rdev->desc_nr < 0) {
1389                 int choice = 0;
1390                 if (mddev->pers) choice = mddev->raid_disks;
1391                 while (find_rdev_nr(mddev, choice))
1392                         choice++;
1393                 rdev->desc_nr = choice;
1394         } else {
1395                 if (find_rdev_nr(mddev, rdev->desc_nr))
1396                         return -EBUSY;
1397         }
1398         bdevname(rdev->bdev,b);
1399         while ( (s=strchr(b, '/')) != NULL)
1400                 *s = '!';
1401
1402         rdev->mddev = mddev;
1403         printk(KERN_INFO "md: bind<%s>\n", b);
1404
1405         if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
1406                 goto fail;
1407
1408         if (rdev->bdev->bd_part)
1409                 ko = &rdev->bdev->bd_part->dev.kobj;
1410         else
1411                 ko = &rdev->bdev->bd_disk->dev.kobj;
1412         if ((err = sysfs_create_link(&rdev->kobj, ko, "block"))) {
1413                 kobject_del(&rdev->kobj);
1414                 goto fail;
1415         }
1416         list_add(&rdev->same_set, &mddev->disks);
1417         bd_claim_by_disk(rdev->bdev, rdev->bdev->bd_holder, mddev->gendisk);
1418         return 0;
1419
1420  fail:
1421         printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
1422                b, mdname(mddev));
1423         return err;
1424 }
1425
1426 static void md_delayed_delete(struct work_struct *ws)
1427 {
1428         mdk_rdev_t *rdev = container_of(ws, mdk_rdev_t, del_work);
1429         kobject_del(&rdev->kobj);
1430         kobject_put(&rdev->kobj);
1431 }
1432
1433 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
1434 {
1435         char b[BDEVNAME_SIZE];
1436         if (!rdev->mddev) {
1437                 MD_BUG();
1438                 return;
1439         }
1440         bd_release_from_disk(rdev->bdev, rdev->mddev->gendisk);
1441         list_del_init(&rdev->same_set);
1442         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
1443         rdev->mddev = NULL;
1444         sysfs_remove_link(&rdev->kobj, "block");
1445
1446         /* We need to delay this, otherwise we can deadlock when
1447          * writing to 'remove' to "dev/state"
1448          */
1449         INIT_WORK(&rdev->del_work, md_delayed_delete);
1450         kobject_get(&rdev->kobj);
1451         schedule_work(&rdev->del_work);
1452 }
1453
1454 /*
1455  * prevent the device from being mounted, repartitioned or
1456  * otherwise reused by a RAID array (or any other kernel
1457  * subsystem), by bd_claiming the device.
1458  */
1459 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev, int shared)
1460 {
1461         int err = 0;
1462         struct block_device *bdev;
1463         char b[BDEVNAME_SIZE];
1464
1465         bdev = open_by_devnum(dev, FMODE_READ|FMODE_WRITE);
1466         if (IS_ERR(bdev)) {
1467                 printk(KERN_ERR "md: could not open %s.\n",
1468                         __bdevname(dev, b));
1469                 return PTR_ERR(bdev);
1470         }
1471         err = bd_claim(bdev, shared ? (mdk_rdev_t *)lock_rdev : rdev);
1472         if (err) {
1473                 printk(KERN_ERR "md: could not bd_claim %s.\n",
1474                         bdevname(bdev, b));
1475                 blkdev_put(bdev);
1476                 return err;
1477         }
1478         if (!shared)
1479                 set_bit(AllReserved, &rdev->flags);
1480         rdev->bdev = bdev;
1481         return err;
1482 }
1483
1484 static void unlock_rdev(mdk_rdev_t *rdev)
1485 {
1486         struct block_device *bdev = rdev->bdev;
1487         rdev->bdev = NULL;
1488         if (!bdev)
1489                 MD_BUG();
1490         bd_release(bdev);
1491         blkdev_put(bdev);
1492 }
1493
1494 void md_autodetect_dev(dev_t dev);
1495
1496 static void export_rdev(mdk_rdev_t * rdev)
1497 {
1498         char b[BDEVNAME_SIZE];
1499         printk(KERN_INFO "md: export_rdev(%s)\n",
1500                 bdevname(rdev->bdev,b));
1501         if (rdev->mddev)
1502                 MD_BUG();
1503         free_disk_sb(rdev);
1504         list_del_init(&rdev->same_set);
1505 #ifndef MODULE
1506         if (test_bit(AutoDetected, &rdev->flags))
1507                 md_autodetect_dev(rdev->bdev->bd_dev);
1508 #endif
1509         unlock_rdev(rdev);
1510         kobject_put(&rdev->kobj);
1511 }
1512
1513 static void kick_rdev_from_array(mdk_rdev_t * rdev)
1514 {
1515         unbind_rdev_from_array(rdev);
1516         export_rdev(rdev);
1517 }
1518
1519 static void export_array(mddev_t *mddev)
1520 {
1521         struct list_head *tmp;
1522         mdk_rdev_t *rdev;
1523
1524         rdev_for_each(rdev, tmp, mddev) {
1525                 if (!rdev->mddev) {
1526                         MD_BUG();
1527                         continue;
1528                 }
1529                 kick_rdev_from_array(rdev);
1530         }
1531         if (!list_empty(&mddev->disks))
1532                 MD_BUG();
1533         mddev->raid_disks = 0;
1534         mddev->major_version = 0;
1535 }
1536
1537 static void print_desc(mdp_disk_t *desc)
1538 {
1539         printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
1540                 desc->major,desc->minor,desc->raid_disk,desc->state);
1541 }
1542
1543 static void print_sb(mdp_super_t *sb)
1544 {
1545         int i;
1546
1547         printk(KERN_INFO 
1548                 "md:  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
1549                 sb->major_version, sb->minor_version, sb->patch_version,
1550                 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
1551                 sb->ctime);
1552         printk(KERN_INFO "md:     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
1553                 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
1554                 sb->md_minor, sb->layout, sb->chunk_size);
1555         printk(KERN_INFO "md:     UT:%08x ST:%d AD:%d WD:%d"
1556                 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
1557                 sb->utime, sb->state, sb->active_disks, sb->working_disks,
1558                 sb->failed_disks, sb->spare_disks,
1559                 sb->sb_csum, (unsigned long)sb->events_lo);
1560
1561         printk(KERN_INFO);
1562         for (i = 0; i < MD_SB_DISKS; i++) {
1563                 mdp_disk_t *desc;
1564
1565                 desc = sb->disks + i;
1566                 if (desc->number || desc->major || desc->minor ||
1567                     desc->raid_disk || (desc->state && (desc->state != 4))) {
1568                         printk("     D %2d: ", i);
1569                         print_desc(desc);
1570                 }
1571         }
1572         printk(KERN_INFO "md:     THIS: ");
1573         print_desc(&sb->this_disk);
1574
1575 }
1576
1577 static void print_rdev(mdk_rdev_t *rdev)
1578 {
1579         char b[BDEVNAME_SIZE];
1580         printk(KERN_INFO "md: rdev %s, SZ:%08llu F:%d S:%d DN:%u\n",
1581                 bdevname(rdev->bdev,b), (unsigned long long)rdev->size,
1582                 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
1583                 rdev->desc_nr);
1584         if (rdev->sb_loaded) {
1585                 printk(KERN_INFO "md: rdev superblock:\n");
1586                 print_sb((mdp_super_t*)page_address(rdev->sb_page));
1587         } else
1588                 printk(KERN_INFO "md: no rdev superblock!\n");
1589 }
1590
1591 static void md_print_devices(void)
1592 {
1593         struct list_head *tmp, *tmp2;
1594         mdk_rdev_t *rdev;
1595         mddev_t *mddev;
1596         char b[BDEVNAME_SIZE];
1597
1598         printk("\n");
1599         printk("md:     **********************************\n");
1600         printk("md:     * <COMPLETE RAID STATE PRINTOUT> *\n");
1601         printk("md:     **********************************\n");
1602         for_each_mddev(mddev, tmp) {
1603
1604                 if (mddev->bitmap)
1605                         bitmap_print_sb(mddev->bitmap);
1606                 else
1607                         printk("%s: ", mdname(mddev));
1608                 rdev_for_each(rdev, tmp2, mddev)
1609                         printk("<%s>", bdevname(rdev->bdev,b));
1610                 printk("\n");
1611
1612                 rdev_for_each(rdev, tmp2, mddev)
1613                         print_rdev(rdev);
1614         }
1615         printk("md:     **********************************\n");
1616         printk("\n");
1617 }
1618
1619
1620 static void sync_sbs(mddev_t * mddev, int nospares)
1621 {
1622         /* Update each superblock (in-memory image), but
1623          * if we are allowed to, skip spares which already
1624          * have the right event counter, or have one earlier
1625          * (which would mean they aren't being marked as dirty
1626          * with the rest of the array)
1627          */
1628         mdk_rdev_t *rdev;
1629         struct list_head *tmp;
1630
1631         rdev_for_each(rdev, tmp, mddev) {
1632                 if (rdev->sb_events == mddev->events ||
1633                     (nospares &&
1634                      rdev->raid_disk < 0 &&
1635                      (rdev->sb_events&1)==0 &&
1636                      rdev->sb_events+1 == mddev->events)) {
1637                         /* Don't update this superblock */
1638                         rdev->sb_loaded = 2;
1639                 } else {
1640                         super_types[mddev->major_version].
1641                                 sync_super(mddev, rdev);
1642                         rdev->sb_loaded = 1;
1643                 }
1644         }
1645 }
1646
1647 static void md_update_sb(mddev_t * mddev, int force_change)
1648 {
1649         struct list_head *tmp;
1650         mdk_rdev_t *rdev;
1651         int sync_req;
1652         int nospares = 0;
1653
1654 repeat:
1655         spin_lock_irq(&mddev->write_lock);
1656
1657         set_bit(MD_CHANGE_PENDING, &mddev->flags);
1658         if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
1659                 force_change = 1;
1660         if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
1661                 /* just a clean<-> dirty transition, possibly leave spares alone,
1662                  * though if events isn't the right even/odd, we will have to do
1663                  * spares after all
1664                  */
1665                 nospares = 1;
1666         if (force_change)
1667                 nospares = 0;
1668         if (mddev->degraded)
1669                 /* If the array is degraded, then skipping spares is both
1670                  * dangerous and fairly pointless.
1671                  * Dangerous because a device that was removed from the array
1672                  * might have a event_count that still looks up-to-date,
1673                  * so it can be re-added without a resync.
1674                  * Pointless because if there are any spares to skip,
1675                  * then a recovery will happen and soon that array won't
1676                  * be degraded any more and the spare can go back to sleep then.
1677                  */
1678                 nospares = 0;
1679
1680         sync_req = mddev->in_sync;
1681         mddev->utime = get_seconds();
1682
1683         /* If this is just a dirty<->clean transition, and the array is clean
1684          * and 'events' is odd, we can roll back to the previous clean state */
1685         if (nospares
1686             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
1687             && (mddev->events & 1)
1688             && mddev->events != 1)
1689                 mddev->events--;
1690         else {
1691                 /* otherwise we have to go forward and ... */
1692                 mddev->events ++;
1693                 if (!mddev->in_sync || mddev->recovery_cp != MaxSector) { /* not clean */
1694                         /* .. if the array isn't clean, insist on an odd 'events' */
1695                         if ((mddev->events&1)==0) {
1696                                 mddev->events++;
1697                                 nospares = 0;
1698                         }
1699                 } else {
1700                         /* otherwise insist on an even 'events' (for clean states) */
1701                         if ((mddev->events&1)) {
1702                                 mddev->events++;
1703                                 nospares = 0;
1704                         }
1705                 }
1706         }
1707
1708         if (!mddev->events) {
1709                 /*
1710                  * oops, this 64-bit counter should never wrap.
1711                  * Either we are in around ~1 trillion A.C., assuming
1712                  * 1 reboot per second, or we have a bug:
1713                  */
1714                 MD_BUG();
1715                 mddev->events --;
1716         }
1717
1718         /*
1719          * do not write anything to disk if using
1720          * nonpersistent superblocks
1721          */
1722         if (!mddev->persistent) {
1723                 if (!mddev->external)
1724                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
1725
1726                 spin_unlock_irq(&mddev->write_lock);
1727                 wake_up(&mddev->sb_wait);
1728                 return;
1729         }
1730         sync_sbs(mddev, nospares);
1731         spin_unlock_irq(&mddev->write_lock);
1732
1733         dprintk(KERN_INFO 
1734                 "md: updating %s RAID superblock on device (in sync %d)\n",
1735                 mdname(mddev),mddev->in_sync);
1736
1737         bitmap_update_sb(mddev->bitmap);
1738         rdev_for_each(rdev, tmp, mddev) {
1739                 char b[BDEVNAME_SIZE];
1740                 dprintk(KERN_INFO "md: ");
1741                 if (rdev->sb_loaded != 1)
1742                         continue; /* no noise on spare devices */
1743                 if (test_bit(Faulty, &rdev->flags))
1744                         dprintk("(skipping faulty ");
1745
1746                 dprintk("%s ", bdevname(rdev->bdev,b));
1747                 if (!test_bit(Faulty, &rdev->flags)) {
1748                         md_super_write(mddev,rdev,
1749                                        rdev->sb_offset<<1, rdev->sb_size,
1750                                        rdev->sb_page);
1751                         dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
1752                                 bdevname(rdev->bdev,b),
1753                                 (unsigned long long)rdev->sb_offset);
1754                         rdev->sb_events = mddev->events;
1755
1756                 } else
1757                         dprintk(")\n");
1758                 if (mddev->level == LEVEL_MULTIPATH)
1759                         /* only need to write one superblock... */
1760                         break;
1761         }
1762         md_super_wait(mddev);
1763         /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
1764
1765         spin_lock_irq(&mddev->write_lock);
1766         if (mddev->in_sync != sync_req ||
1767             test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
1768                 /* have to write it out again */
1769                 spin_unlock_irq(&mddev->write_lock);
1770                 goto repeat;
1771         }
1772         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
1773         spin_unlock_irq(&mddev->write_lock);
1774         wake_up(&mddev->sb_wait);
1775
1776 }
1777
1778 /* words written to sysfs files may, or my not, be \n terminated.
1779  * We want to accept with case. For this we use cmd_match.
1780  */
1781 static int cmd_match(const char *cmd, const char *str)
1782 {
1783         /* See if cmd, written into a sysfs file, matches
1784          * str.  They must either be the same, or cmd can
1785          * have a trailing newline
1786          */
1787         while (*cmd && *str && *cmd == *str) {
1788                 cmd++;
1789                 str++;
1790         }
1791         if (*cmd == '\n')
1792                 cmd++;
1793         if (*str || *cmd)
1794                 return 0;
1795         return 1;
1796 }
1797
1798 struct rdev_sysfs_entry {
1799         struct attribute attr;
1800         ssize_t (*show)(mdk_rdev_t *, char *);
1801         ssize_t (*store)(mdk_rdev_t *, const char *, size_t);
1802 };
1803
1804 static ssize_t
1805 state_show(mdk_rdev_t *rdev, char *page)
1806 {
1807         char *sep = "";
1808         size_t len = 0;
1809
1810         if (test_bit(Faulty, &rdev->flags)) {
1811                 len+= sprintf(page+len, "%sfaulty",sep);
1812                 sep = ",";
1813         }
1814         if (test_bit(In_sync, &rdev->flags)) {
1815                 len += sprintf(page+len, "%sin_sync",sep);
1816                 sep = ",";
1817         }
1818         if (test_bit(WriteMostly, &rdev->flags)) {
1819                 len += sprintf(page+len, "%swrite_mostly",sep);
1820                 sep = ",";
1821         }
1822         if (!test_bit(Faulty, &rdev->flags) &&
1823             !test_bit(In_sync, &rdev->flags)) {
1824                 len += sprintf(page+len, "%sspare", sep);
1825                 sep = ",";
1826         }
1827         return len+sprintf(page+len, "\n");
1828 }
1829
1830 static ssize_t
1831 state_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1832 {
1833         /* can write
1834          *  faulty  - simulates and error
1835          *  remove  - disconnects the device
1836          *  writemostly - sets write_mostly
1837          *  -writemostly - clears write_mostly
1838          */
1839         int err = -EINVAL;
1840         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
1841                 md_error(rdev->mddev, rdev);
1842                 err = 0;
1843         } else if (cmd_match(buf, "remove")) {
1844                 if (rdev->raid_disk >= 0)
1845                         err = -EBUSY;
1846                 else {
1847                         mddev_t *mddev = rdev->mddev;
1848                         kick_rdev_from_array(rdev);
1849                         if (mddev->pers)
1850                                 md_update_sb(mddev, 1);
1851                         md_new_event(mddev);
1852                         err = 0;
1853                 }
1854         } else if (cmd_match(buf, "writemostly")) {
1855                 set_bit(WriteMostly, &rdev->flags);
1856                 err = 0;
1857         } else if (cmd_match(buf, "-writemostly")) {
1858                 clear_bit(WriteMostly, &rdev->flags);
1859                 err = 0;
1860         }
1861         return err ? err : len;
1862 }
1863 static struct rdev_sysfs_entry rdev_state =
1864 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
1865
1866 static ssize_t
1867 super_show(mdk_rdev_t *rdev, char *page)
1868 {
1869         if (rdev->sb_loaded && rdev->sb_size) {
1870                 memcpy(page, page_address(rdev->sb_page), rdev->sb_size);
1871                 return rdev->sb_size;
1872         } else
1873                 return 0;
1874 }
1875 static struct rdev_sysfs_entry rdev_super = __ATTR_RO(super);
1876
1877 static ssize_t
1878 errors_show(mdk_rdev_t *rdev, char *page)
1879 {
1880         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
1881 }
1882
1883 static ssize_t
1884 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1885 {
1886         char *e;
1887         unsigned long n = simple_strtoul(buf, &e, 10);
1888         if (*buf && (*e == 0 || *e == '\n')) {
1889                 atomic_set(&rdev->corrected_errors, n);
1890                 return len;
1891         }
1892         return -EINVAL;
1893 }
1894 static struct rdev_sysfs_entry rdev_errors =
1895 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
1896
1897 static ssize_t
1898 slot_show(mdk_rdev_t *rdev, char *page)
1899 {
1900         if (rdev->raid_disk < 0)
1901                 return sprintf(page, "none\n");
1902         else
1903                 return sprintf(page, "%d\n", rdev->raid_disk);
1904 }
1905
1906 static ssize_t
1907 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1908 {
1909         char *e;
1910         int err;
1911         char nm[20];
1912         int slot = simple_strtoul(buf, &e, 10);
1913         if (strncmp(buf, "none", 4)==0)
1914                 slot = -1;
1915         else if (e==buf || (*e && *e!= '\n'))
1916                 return -EINVAL;
1917         if (rdev->mddev->pers) {
1918                 /* Setting 'slot' on an active array requires also
1919                  * updating the 'rd%d' link, and communicating
1920                  * with the personality with ->hot_*_disk.
1921                  * For now we only support removing
1922                  * failed/spare devices.  This normally happens automatically,
1923                  * but not when the metadata is externally managed.
1924                  */
1925                 if (slot != -1)
1926                         return -EBUSY;
1927                 if (rdev->raid_disk == -1)
1928                         return -EEXIST;
1929                 /* personality does all needed checks */
1930                 if (rdev->mddev->pers->hot_add_disk == NULL)
1931                         return -EINVAL;
1932                 err = rdev->mddev->pers->
1933                         hot_remove_disk(rdev->mddev, rdev->raid_disk);
1934                 if (err)
1935                         return err;
1936                 sprintf(nm, "rd%d", rdev->raid_disk);
1937                 sysfs_remove_link(&rdev->mddev->kobj, nm);
1938                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
1939                 md_wakeup_thread(rdev->mddev->thread);
1940         } else {
1941                 if (slot >= rdev->mddev->raid_disks)
1942                         return -ENOSPC;
1943                 rdev->raid_disk = slot;
1944                 /* assume it is working */
1945                 clear_bit(Faulty, &rdev->flags);
1946                 clear_bit(WriteMostly, &rdev->flags);
1947                 set_bit(In_sync, &rdev->flags);
1948         }
1949         return len;
1950 }
1951
1952
1953 static struct rdev_sysfs_entry rdev_slot =
1954 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
1955
1956 static ssize_t
1957 offset_show(mdk_rdev_t *rdev, char *page)
1958 {
1959         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
1960 }
1961
1962 static ssize_t
1963 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1964 {
1965         char *e;
1966         unsigned long long offset = simple_strtoull(buf, &e, 10);
1967         if (e==buf || (*e && *e != '\n'))
1968                 return -EINVAL;
1969         if (rdev->mddev->pers)
1970                 return -EBUSY;
1971         if (rdev->size && rdev->mddev->external)
1972                 /* Must set offset before size, so overlap checks
1973                  * can be sane */
1974                 return -EBUSY;
1975         rdev->data_offset = offset;
1976         return len;
1977 }
1978
1979 static struct rdev_sysfs_entry rdev_offset =
1980 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
1981
1982 static ssize_t
1983 rdev_size_show(mdk_rdev_t *rdev, char *page)
1984 {
1985         return sprintf(page, "%llu\n", (unsigned long long)rdev->size);
1986 }
1987
1988 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
1989 {
1990         /* check if two start/length pairs overlap */
1991         if (s1+l1 <= s2)
1992                 return 0;
1993         if (s2+l2 <= s1)
1994                 return 0;
1995         return 1;
1996 }
1997
1998 static ssize_t
1999 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2000 {
2001         char *e;
2002         unsigned long long size = simple_strtoull(buf, &e, 10);
2003         unsigned long long oldsize = rdev->size;
2004         mddev_t *my_mddev = rdev->mddev;
2005
2006         if (e==buf || (*e && *e != '\n'))
2007                 return -EINVAL;
2008         if (my_mddev->pers)
2009                 return -EBUSY;
2010         rdev->size = size;
2011         if (size > oldsize && rdev->mddev->external) {
2012                 /* need to check that all other rdevs with the same ->bdev
2013                  * do not overlap.  We need to unlock the mddev to avoid
2014                  * a deadlock.  We have already changed rdev->size, and if
2015                  * we have to change it back, we will have the lock again.
2016                  */
2017                 mddev_t *mddev;
2018                 int overlap = 0;
2019                 struct list_head *tmp, *tmp2;
2020
2021                 mddev_unlock(my_mddev);
2022                 for_each_mddev(mddev, tmp) {
2023                         mdk_rdev_t *rdev2;
2024
2025                         mddev_lock(mddev);
2026                         rdev_for_each(rdev2, tmp2, mddev)
2027                                 if (test_bit(AllReserved, &rdev2->flags) ||
2028                                     (rdev->bdev == rdev2->bdev &&
2029                                      rdev != rdev2 &&
2030                                      overlaps(rdev->data_offset, rdev->size,
2031                                             rdev2->data_offset, rdev2->size))) {
2032                                         overlap = 1;
2033                                         break;
2034                                 }
2035                         mddev_unlock(mddev);
2036                         if (overlap) {
2037                                 mddev_put(mddev);
2038                                 break;
2039                         }
2040                 }
2041                 mddev_lock(my_mddev);
2042                 if (overlap) {
2043                         /* Someone else could have slipped in a size
2044                          * change here, but doing so is just silly.
2045                          * We put oldsize back because we *know* it is
2046                          * safe, and trust userspace not to race with
2047                          * itself
2048                          */
2049                         rdev->size = oldsize;
2050                         return -EBUSY;
2051                 }
2052         }
2053         if (size < my_mddev->size || my_mddev->size == 0)
2054                 my_mddev->size = size;
2055         return len;
2056 }
2057
2058 static struct rdev_sysfs_entry rdev_size =
2059 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2060
2061 static struct attribute *rdev_default_attrs[] = {
2062         &rdev_state.attr,
2063         &rdev_super.attr,
2064         &rdev_errors.attr,
2065         &rdev_slot.attr,
2066         &rdev_offset.attr,
2067         &rdev_size.attr,
2068         NULL,
2069 };
2070 static ssize_t
2071 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2072 {
2073         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2074         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2075         mddev_t *mddev = rdev->mddev;
2076         ssize_t rv;
2077
2078         if (!entry->show)
2079                 return -EIO;
2080
2081         rv = mddev ? mddev_lock(mddev) : -EBUSY;
2082         if (!rv) {
2083                 if (rdev->mddev == NULL)
2084                         rv = -EBUSY;
2085                 else
2086                         rv = entry->show(rdev, page);
2087                 mddev_unlock(mddev);
2088         }
2089         return rv;
2090 }
2091
2092 static ssize_t
2093 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
2094               const char *page, size_t length)
2095 {
2096         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2097         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2098         ssize_t rv;
2099         mddev_t *mddev = rdev->mddev;
2100
2101         if (!entry->store)
2102                 return -EIO;
2103         if (!capable(CAP_SYS_ADMIN))
2104                 return -EACCES;
2105         rv = mddev ? mddev_lock(mddev): -EBUSY;
2106         if (!rv) {
2107                 if (rdev->mddev == NULL)
2108                         rv = -EBUSY;
2109                 else
2110                         rv = entry->store(rdev, page, length);
2111                 mddev_unlock(rdev->mddev);
2112         }
2113         return rv;
2114 }
2115
2116 static void rdev_free(struct kobject *ko)
2117 {
2118         mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
2119         kfree(rdev);
2120 }
2121 static struct sysfs_ops rdev_sysfs_ops = {
2122         .show           = rdev_attr_show,
2123         .store          = rdev_attr_store,
2124 };
2125 static struct kobj_type rdev_ktype = {
2126         .release        = rdev_free,
2127         .sysfs_ops      = &rdev_sysfs_ops,
2128         .default_attrs  = rdev_default_attrs,
2129 };
2130
2131 /*
2132  * Import a device. If 'super_format' >= 0, then sanity check the superblock
2133  *
2134  * mark the device faulty if:
2135  *
2136  *   - the device is nonexistent (zero size)
2137  *   - the device has no valid superblock
2138  *
2139  * a faulty rdev _never_ has rdev->sb set.
2140  */
2141 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
2142 {
2143         char b[BDEVNAME_SIZE];
2144         int err;
2145         mdk_rdev_t *rdev;
2146         sector_t size;
2147
2148         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
2149         if (!rdev) {
2150                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
2151                 return ERR_PTR(-ENOMEM);
2152         }
2153
2154         if ((err = alloc_disk_sb(rdev)))
2155                 goto abort_free;
2156
2157         err = lock_rdev(rdev, newdev, super_format == -2);
2158         if (err)
2159                 goto abort_free;
2160
2161         kobject_init(&rdev->kobj, &rdev_ktype);
2162
2163         rdev->desc_nr = -1;
2164         rdev->saved_raid_disk = -1;
2165         rdev->raid_disk = -1;
2166         rdev->flags = 0;
2167         rdev->data_offset = 0;
2168         rdev->sb_events = 0;
2169         atomic_set(&rdev->nr_pending, 0);
2170         atomic_set(&rdev->read_errors, 0);
2171         atomic_set(&rdev->corrected_errors, 0);
2172
2173         size = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
2174         if (!size) {
2175                 printk(KERN_WARNING 
2176                         "md: %s has zero or unknown size, marking faulty!\n",
2177                         bdevname(rdev->bdev,b));
2178                 err = -EINVAL;
2179                 goto abort_free;
2180         }
2181
2182         if (super_format >= 0) {
2183                 err = super_types[super_format].
2184                         load_super(rdev, NULL, super_minor);
2185                 if (err == -EINVAL) {
2186                         printk(KERN_WARNING
2187                                 "md: %s does not have a valid v%d.%d "
2188                                "superblock, not importing!\n",
2189                                 bdevname(rdev->bdev,b),
2190                                super_format, super_minor);
2191                         goto abort_free;
2192                 }
2193                 if (err < 0) {
2194                         printk(KERN_WARNING 
2195                                 "md: could not read %s's sb, not importing!\n",
2196                                 bdevname(rdev->bdev,b));
2197                         goto abort_free;
2198                 }
2199         }
2200         INIT_LIST_HEAD(&rdev->same_set);
2201
2202         return rdev;
2203
2204 abort_free:
2205         if (rdev->sb_page) {
2206                 if (rdev->bdev)
2207                         unlock_rdev(rdev);
2208                 free_disk_sb(rdev);
2209         }
2210         kfree(rdev);
2211         return ERR_PTR(err);
2212 }
2213
2214 /*
2215  * Check a full RAID array for plausibility
2216  */
2217
2218
2219 static void analyze_sbs(mddev_t * mddev)
2220 {
2221         int i;
2222         struct list_head *tmp;
2223         mdk_rdev_t *rdev, *freshest;
2224         char b[BDEVNAME_SIZE];
2225
2226         freshest = NULL;
2227         rdev_for_each(rdev, tmp, mddev)
2228                 switch (super_types[mddev->major_version].
2229                         load_super(rdev, freshest, mddev->minor_version)) {
2230                 case 1:
2231                         freshest = rdev;
2232                         break;
2233                 case 0:
2234                         break;
2235                 default:
2236                         printk( KERN_ERR \
2237                                 "md: fatal superblock inconsistency in %s"
2238                                 " -- removing from array\n", 
2239                                 bdevname(rdev->bdev,b));
2240                         kick_rdev_from_array(rdev);
2241                 }
2242
2243
2244         super_types[mddev->major_version].
2245                 validate_super(mddev, freshest);
2246
2247         i = 0;
2248         rdev_for_each(rdev, tmp, mddev) {
2249                 if (rdev != freshest)
2250                         if (super_types[mddev->major_version].
2251                             validate_super(mddev, rdev)) {
2252                                 printk(KERN_WARNING "md: kicking non-fresh %s"
2253                                         " from array!\n",
2254                                         bdevname(rdev->bdev,b));
2255                                 kick_rdev_from_array(rdev);
2256                                 continue;
2257                         }
2258                 if (mddev->level == LEVEL_MULTIPATH) {
2259                         rdev->desc_nr = i++;
2260                         rdev->raid_disk = rdev->desc_nr;
2261                         set_bit(In_sync, &rdev->flags);
2262                 } else if (rdev->raid_disk >= mddev->raid_disks) {
2263                         rdev->raid_disk = -1;
2264                         clear_bit(In_sync, &rdev->flags);
2265                 }
2266         }
2267
2268
2269
2270         if (mddev->recovery_cp != MaxSector &&
2271             mddev->level >= 1)
2272                 printk(KERN_ERR "md: %s: raid array is not clean"
2273                        " -- starting background reconstruction\n",
2274                        mdname(mddev));
2275
2276 }
2277
2278 static ssize_t
2279 safe_delay_show(mddev_t *mddev, char *page)
2280 {
2281         int msec = (mddev->safemode_delay*1000)/HZ;
2282         return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
2283 }
2284 static ssize_t
2285 safe_delay_store(mddev_t *mddev, const char *cbuf, size_t len)
2286 {
2287         int scale=1;
2288         int dot=0;
2289         int i;
2290         unsigned long msec;
2291         char buf[30];
2292         char *e;
2293         /* remove a period, and count digits after it */
2294         if (len >= sizeof(buf))
2295                 return -EINVAL;
2296         strlcpy(buf, cbuf, len);
2297         buf[len] = 0;
2298         for (i=0; i<len; i++) {
2299                 if (dot) {
2300                         if (isdigit(buf[i])) {
2301                                 buf[i-1] = buf[i];
2302                                 scale *= 10;
2303                         }
2304                         buf[i] = 0;
2305                 } else if (buf[i] == '.') {
2306                         dot=1;
2307                         buf[i] = 0;
2308                 }
2309         }
2310         msec = simple_strtoul(buf, &e, 10);
2311         if (e == buf || (*e && *e != '\n'))
2312                 return -EINVAL;
2313         msec = (msec * 1000) / scale;
2314         if (msec == 0)
2315                 mddev->safemode_delay = 0;
2316         else {
2317                 mddev->safemode_delay = (msec*HZ)/1000;
2318                 if (mddev->safemode_delay == 0)
2319                         mddev->safemode_delay = 1;
2320         }
2321         return len;
2322 }
2323 static struct md_sysfs_entry md_safe_delay =
2324 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
2325
2326 static ssize_t
2327 level_show(mddev_t *mddev, char *page)
2328 {
2329         struct mdk_personality *p = mddev->pers;
2330         if (p)
2331                 return sprintf(page, "%s\n", p->name);
2332         else if (mddev->clevel[0])
2333                 return sprintf(page, "%s\n", mddev->clevel);
2334         else if (mddev->level != LEVEL_NONE)
2335                 return sprintf(page, "%d\n", mddev->level);
2336         else
2337                 return 0;
2338 }
2339
2340 static ssize_t
2341 level_store(mddev_t *mddev, const char *buf, size_t len)
2342 {
2343         ssize_t rv = len;
2344         if (mddev->pers)
2345                 return -EBUSY;
2346         if (len == 0)
2347                 return 0;
2348         if (len >= sizeof(mddev->clevel))
2349                 return -ENOSPC;
2350         strncpy(mddev->clevel, buf, len);
2351         if (mddev->clevel[len-1] == '\n')
2352                 len--;
2353         mddev->clevel[len] = 0;
2354         mddev->level = LEVEL_NONE;
2355         return rv;
2356 }
2357
2358 static struct md_sysfs_entry md_level =
2359 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
2360
2361
2362 static ssize_t
2363 layout_show(mddev_t *mddev, char *page)
2364 {
2365         /* just a number, not meaningful for all levels */
2366         if (mddev->reshape_position != MaxSector &&
2367             mddev->layout != mddev->new_layout)
2368                 return sprintf(page, "%d (%d)\n",
2369                                mddev->new_layout, mddev->layout);
2370         return sprintf(page, "%d\n", mddev->layout);
2371 }
2372
2373 static ssize_t
2374 layout_store(mddev_t *mddev, const char *buf, size_t len)
2375 {
2376         char *e;
2377         unsigned long n = simple_strtoul(buf, &e, 10);
2378
2379         if (!*buf || (*e && *e != '\n'))
2380                 return -EINVAL;
2381
2382         if (mddev->pers)
2383                 return -EBUSY;
2384         if (mddev->reshape_position != MaxSector)
2385                 mddev->new_layout = n;
2386         else
2387                 mddev->layout = n;
2388         return len;
2389 }
2390 static struct md_sysfs_entry md_layout =
2391 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
2392
2393
2394 static ssize_t
2395 raid_disks_show(mddev_t *mddev, char *page)
2396 {
2397         if (mddev->raid_disks == 0)
2398                 return 0;
2399         if (mddev->reshape_position != MaxSector &&
2400             mddev->delta_disks != 0)
2401                 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
2402                                mddev->raid_disks - mddev->delta_disks);
2403         return sprintf(page, "%d\n", mddev->raid_disks);
2404 }
2405
2406 static int update_raid_disks(mddev_t *mddev, int raid_disks);
2407
2408 static ssize_t
2409 raid_disks_store(mddev_t *mddev, const char *buf, size_t len)
2410 {
2411         char *e;
2412         int rv = 0;
2413         unsigned long n = simple_strtoul(buf, &e, 10);
2414
2415         if (!*buf || (*e && *e != '\n'))
2416                 return -EINVAL;
2417
2418         if (mddev->pers)
2419                 rv = update_raid_disks(mddev, n);
2420         else if (mddev->reshape_position != MaxSector) {
2421                 int olddisks = mddev->raid_disks - mddev->delta_disks;
2422                 mddev->delta_disks = n - olddisks;
2423                 mddev->raid_disks = n;
2424         } else
2425                 mddev->raid_disks = n;
2426         return rv ? rv : len;
2427 }
2428 static struct md_sysfs_entry md_raid_disks =
2429 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
2430
2431 static ssize_t
2432 chunk_size_show(mddev_t *mddev, char *page)
2433 {
2434         if (mddev->reshape_position != MaxSector &&
2435             mddev->chunk_size != mddev->new_chunk)
2436                 return sprintf(page, "%d (%d)\n", mddev->new_chunk,
2437                                mddev->chunk_size);
2438         return sprintf(page, "%d\n", mddev->chunk_size);
2439 }
2440
2441 static ssize_t
2442 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
2443 {
2444         /* can only set chunk_size if array is not yet active */
2445         char *e;
2446         unsigned long n = simple_strtoul(buf, &e, 10);
2447
2448         if (!*buf || (*e && *e != '\n'))
2449                 return -EINVAL;
2450
2451         if (mddev->pers)
2452                 return -EBUSY;
2453         else if (mddev->reshape_position != MaxSector)
2454                 mddev->new_chunk = n;
2455         else
2456                 mddev->chunk_size = n;
2457         return len;
2458 }
2459 static struct md_sysfs_entry md_chunk_size =
2460 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
2461
2462 static ssize_t
2463 resync_start_show(mddev_t *mddev, char *page)
2464 {
2465         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
2466 }
2467
2468 static ssize_t
2469 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
2470 {
2471         /* can only set chunk_size if array is not yet active */
2472         char *e;
2473         unsigned long long n = simple_strtoull(buf, &e, 10);
2474
2475         if (mddev->pers)
2476                 return -EBUSY;
2477         if (!*buf || (*e && *e != '\n'))
2478                 return -EINVAL;
2479
2480         mddev->recovery_cp = n;
2481         return len;
2482 }
2483 static struct md_sysfs_entry md_resync_start =
2484 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
2485
2486 /*
2487  * The array state can be:
2488  *
2489  * clear
2490  *     No devices, no size, no level
2491  *     Equivalent to STOP_ARRAY ioctl
2492  * inactive
2493  *     May have some settings, but array is not active
2494  *        all IO results in error
2495  *     When written, doesn't tear down array, but just stops it
2496  * suspended (not supported yet)
2497  *     All IO requests will block. The array can be reconfigured.
2498  *     Writing this, if accepted, will block until array is quiessent
2499  * readonly
2500  *     no resync can happen.  no superblocks get written.
2501  *     write requests fail
2502  * read-auto
2503  *     like readonly, but behaves like 'clean' on a write request.
2504  *
2505  * clean - no pending writes, but otherwise active.
2506  *     When written to inactive array, starts without resync
2507  *     If a write request arrives then
2508  *       if metadata is known, mark 'dirty' and switch to 'active'.
2509  *       if not known, block and switch to write-pending
2510  *     If written to an active array that has pending writes, then fails.
2511  * active
2512  *     fully active: IO and resync can be happening.
2513  *     When written to inactive array, starts with resync
2514  *
2515  * write-pending
2516  *     clean, but writes are blocked waiting for 'active' to be written.
2517  *
2518  * active-idle
2519  *     like active, but no writes have been seen for a while (100msec).
2520  *
2521  */
2522 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
2523                    write_pending, active_idle, bad_word};
2524 static char *array_states[] = {
2525         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
2526         "write-pending", "active-idle", NULL };
2527
2528 static int match_word(const char *word, char **list)
2529 {
2530         int n;
2531         for (n=0; list[n]; n++)
2532                 if (cmd_match(word, list[n]))
2533                         break;
2534         return n;
2535 }
2536
2537 static ssize_t
2538 array_state_show(mddev_t *mddev, char *page)
2539 {
2540         enum array_state st = inactive;
2541
2542         if (mddev->pers)
2543                 switch(mddev->ro) {
2544                 case 1:
2545                         st = readonly;
2546                         break;
2547                 case 2:
2548                         st = read_auto;
2549                         break;
2550                 case 0:
2551                         if (mddev->in_sync)
2552                                 st = clean;
2553                         else if (test_bit(MD_CHANGE_CLEAN, &mddev->flags))
2554                                 st = write_pending;
2555                         else if (mddev->safemode)
2556                                 st = active_idle;
2557                         else
2558                                 st = active;
2559                 }
2560         else {
2561                 if (list_empty(&mddev->disks) &&
2562                     mddev->raid_disks == 0 &&
2563                     mddev->size == 0)
2564                         st = clear;
2565                 else
2566                         st = inactive;
2567         }
2568         return sprintf(page, "%s\n", array_states[st]);
2569 }
2570
2571 static int do_md_stop(mddev_t * mddev, int ro);
2572 static int do_md_run(mddev_t * mddev);
2573 static int restart_array(mddev_t *mddev);
2574
2575 static ssize_t
2576 array_state_store(mddev_t *mddev, const char *buf, size_t len)
2577 {
2578         int err = -EINVAL;
2579         enum array_state st = match_word(buf, array_states);
2580         switch(st) {
2581         case bad_word:
2582                 break;
2583         case clear:
2584                 /* stopping an active array */
2585                 if (atomic_read(&mddev->active) > 1)
2586                         return -EBUSY;
2587                 err = do_md_stop(mddev, 0);
2588                 break;
2589         case inactive:
2590                 /* stopping an active array */
2591                 if (mddev->pers) {
2592                         if (atomic_read(&mddev->active) > 1)
2593                                 return -EBUSY;
2594                         err = do_md_stop(mddev, 2);
2595                 } else
2596                         err = 0; /* already inactive */
2597                 break;
2598         case suspended:
2599                 break; /* not supported yet */
2600         case readonly:
2601                 if (mddev->pers)
2602                         err = do_md_stop(mddev, 1);
2603                 else {
2604                         mddev->ro = 1;
2605                         err = do_md_run(mddev);
2606                 }
2607                 break;
2608         case read_auto:
2609                 /* stopping an active array */
2610                 if (mddev->pers) {
2611                         err = do_md_stop(mddev, 1);
2612                         if (err == 0)
2613                                 mddev->ro = 2; /* FIXME mark devices writable */
2614                 } else {
2615                         mddev->ro = 2;
2616                         err = do_md_run(mddev);
2617                 }
2618                 break;
2619         case clean:
2620                 if (mddev->pers) {
2621                         restart_array(mddev);
2622                         spin_lock_irq(&mddev->write_lock);
2623                         if (atomic_read(&mddev->writes_pending) == 0) {
2624                                 if (mddev->in_sync == 0) {
2625                                         mddev->in_sync = 1;
2626                                         if (mddev->persistent)
2627                                                 set_bit(MD_CHANGE_CLEAN,
2628                                                         &mddev->flags);
2629                                 }
2630                                 err = 0;
2631                         } else
2632                                 err = -EBUSY;
2633                         spin_unlock_irq(&mddev->write_lock);
2634                 } else {
2635                         mddev->ro = 0;
2636                         mddev->recovery_cp = MaxSector;
2637                         err = do_md_run(mddev);
2638                 }
2639                 break;
2640         case active:
2641                 if (mddev->pers) {
2642                         restart_array(mddev);
2643                         if (mddev->external)
2644                                 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2645                         wake_up(&mddev->sb_wait);
2646                         err = 0;
2647                 } else {
2648                         mddev->ro = 0;
2649                         err = do_md_run(mddev);
2650                 }
2651                 break;
2652         case write_pending:
2653         case active_idle:
2654                 /* these cannot be set */
2655                 break;
2656         }
2657         if (err)
2658                 return err;
2659         else
2660                 return len;
2661 }
2662 static struct md_sysfs_entry md_array_state =
2663 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
2664
2665 static ssize_t
2666 null_show(mddev_t *mddev, char *page)
2667 {
2668         return -EINVAL;
2669 }
2670
2671 static ssize_t
2672 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
2673 {
2674         /* buf must be %d:%d\n? giving major and minor numbers */
2675         /* The new device is added to the array.
2676          * If the array has a persistent superblock, we read the
2677          * superblock to initialise info and check validity.
2678          * Otherwise, only checking done is that in bind_rdev_to_array,
2679          * which mainly checks size.
2680          */
2681         char *e;
2682         int major = simple_strtoul(buf, &e, 10);
2683         int minor;
2684         dev_t dev;
2685         mdk_rdev_t *rdev;
2686         int err;
2687
2688         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
2689                 return -EINVAL;
2690         minor = simple_strtoul(e+1, &e, 10);
2691         if (*e && *e != '\n')
2692                 return -EINVAL;
2693         dev = MKDEV(major, minor);
2694         if (major != MAJOR(dev) ||
2695             minor != MINOR(dev))
2696                 return -EOVERFLOW;
2697
2698
2699         if (mddev->persistent) {
2700                 rdev = md_import_device(dev, mddev->major_version,
2701                                         mddev->minor_version);
2702                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
2703                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
2704                                                        mdk_rdev_t, same_set);
2705                         err = super_types[mddev->major_version]
2706                                 .load_super(rdev, rdev0, mddev->minor_version);
2707                         if (err < 0)
2708                                 goto out;
2709                 }
2710         } else if (mddev->external)
2711                 rdev = md_import_device(dev, -2, -1);
2712         else
2713                 rdev = md_import_device(dev, -1, -1);
2714
2715         if (IS_ERR(rdev))
2716                 return PTR_ERR(rdev);
2717         err = bind_rdev_to_array(rdev, mddev);
2718  out:
2719         if (err)
2720                 export_rdev(rdev);
2721         return err ? err : len;
2722 }
2723
2724 static struct md_sysfs_entry md_new_device =
2725 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
2726
2727 static ssize_t
2728 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
2729 {
2730         char *end;
2731         unsigned long chunk, end_chunk;
2732
2733         if (!mddev->bitmap)
2734                 goto out;
2735         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
2736         while (*buf) {
2737                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
2738                 if (buf == end) break;
2739                 if (*end == '-') { /* range */
2740                         buf = end + 1;
2741                         end_chunk = simple_strtoul(buf, &end, 0);
2742                         if (buf == end) break;
2743                 }
2744                 if (*end && !isspace(*end)) break;
2745                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
2746                 buf = end;
2747                 while (isspace(*buf)) buf++;
2748         }
2749         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
2750 out:
2751         return len;
2752 }
2753
2754 static struct md_sysfs_entry md_bitmap =
2755 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
2756
2757 static ssize_t
2758 size_show(mddev_t *mddev, char *page)
2759 {
2760         return sprintf(page, "%llu\n", (unsigned long long)mddev->size);
2761 }
2762
2763 static int update_size(mddev_t *mddev, unsigned long size);
2764
2765 static ssize_t
2766 size_store(mddev_t *mddev, const char *buf, size_t len)
2767 {
2768         /* If array is inactive, we can reduce the component size, but
2769          * not increase it (except from 0).
2770          * If array is active, we can try an on-line resize
2771          */
2772         char *e;
2773         int err = 0;
2774         unsigned long long size = simple_strtoull(buf, &e, 10);
2775         if (!*buf || *buf == '\n' ||
2776             (*e && *e != '\n'))
2777                 return -EINVAL;
2778
2779         if (mddev->pers) {
2780                 err = update_size(mddev, size);
2781                 md_update_sb(mddev, 1);
2782         } else {
2783                 if (mddev->size == 0 ||
2784                     mddev->size > size)
2785                         mddev->size = size;
2786                 else
2787                         err = -ENOSPC;
2788         }
2789         return err ? err : len;
2790 }
2791
2792 static struct md_sysfs_entry md_size =
2793 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
2794
2795
2796 /* Metdata version.
2797  * This is one of
2798  *   'none' for arrays with no metadata (good luck...)
2799  *   'external' for arrays with externally managed metadata,
2800  * or N.M for internally known formats
2801  */
2802 static ssize_t
2803 metadata_show(mddev_t *mddev, char *page)
2804 {
2805         if (mddev->persistent)
2806                 return sprintf(page, "%d.%d\n",
2807                                mddev->major_version, mddev->minor_version);
2808         else if (mddev->external)
2809                 return sprintf(page, "external:%s\n", mddev->metadata_type);
2810         else
2811                 return sprintf(page, "none\n");
2812 }
2813
2814 static ssize_t
2815 metadata_store(mddev_t *mddev, const char *buf, size_t len)
2816 {
2817         int major, minor;
2818         char *e;
2819         if (!list_empty(&mddev->disks))
2820                 return -EBUSY;
2821
2822         if (cmd_match(buf, "none")) {
2823                 mddev->persistent = 0;
2824                 mddev->external = 0;
2825                 mddev->major_version = 0;
2826                 mddev->minor_version = 90;
2827                 return len;
2828         }
2829         if (strncmp(buf, "external:", 9) == 0) {
2830                 size_t namelen = len-9;
2831                 if (namelen >= sizeof(mddev->metadata_type))
2832                         namelen = sizeof(mddev->metadata_type)-1;
2833                 strncpy(mddev->metadata_type, buf+9, namelen);
2834                 mddev->metadata_type[namelen] = 0;
2835                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
2836                         mddev->metadata_type[--namelen] = 0;
2837                 mddev->persistent = 0;
2838                 mddev->external = 1;
2839                 mddev->major_version = 0;
2840                 mddev->minor_version = 90;
2841                 return len;
2842         }
2843         major = simple_strtoul(buf, &e, 10);
2844         if (e==buf || *e != '.')
2845                 return -EINVAL;
2846         buf = e+1;
2847         minor = simple_strtoul(buf, &e, 10);
2848         if (e==buf || (*e && *e != '\n') )
2849                 return -EINVAL;
2850         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
2851                 return -ENOENT;
2852         mddev->major_version = major;
2853         mddev->minor_version = minor;
2854         mddev->persistent = 1;
2855         mddev->external = 0;
2856         return len;
2857 }
2858
2859 static struct md_sysfs_entry md_metadata =
2860 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
2861
2862 static ssize_t
2863 action_show(mddev_t *mddev, char *page)
2864 {
2865         char *type = "idle";
2866         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2867             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
2868                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2869                         type = "reshape";
2870                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2871                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2872                                 type = "resync";
2873                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2874                                 type = "check";
2875                         else
2876                                 type = "repair";
2877                 } else
2878                         type = "recover";
2879         }
2880         return sprintf(page, "%s\n", type);
2881 }
2882
2883 static ssize_t
2884 action_store(mddev_t *mddev, const char *page, size_t len)
2885 {
2886         if (!mddev->pers || !mddev->pers->sync_request)
2887                 return -EINVAL;
2888
2889         if (cmd_match(page, "idle")) {
2890                 if (mddev->sync_thread) {
2891                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2892                         md_unregister_thread(mddev->sync_thread);
2893                         mddev->sync_thread = NULL;
2894                         mddev->recovery = 0;
2895                 }
2896         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2897                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
2898                 return -EBUSY;
2899         else if (cmd_match(page, "resync") || cmd_match(page, "recover"))
2900                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2901         else if (cmd_match(page, "reshape")) {
2902                 int err;
2903                 if (mddev->pers->start_reshape == NULL)
2904                         return -EINVAL;
2905                 err = mddev->pers->start_reshape(mddev);
2906                 if (err)
2907                         return err;
2908         } else {
2909                 if (cmd_match(page, "check"))
2910                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
2911                 else if (!cmd_match(page, "repair"))
2912                         return -EINVAL;
2913                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
2914                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
2915         }
2916         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2917         md_wakeup_thread(mddev->thread);
2918         return len;
2919 }
2920
2921 static ssize_t
2922 mismatch_cnt_show(mddev_t *mddev, char *page)
2923 {
2924         return sprintf(page, "%llu\n",
2925                        (unsigned long long) mddev->resync_mismatches);
2926 }
2927
2928 static struct md_sysfs_entry md_scan_mode =
2929 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
2930
2931
2932 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
2933
2934 static ssize_t
2935 sync_min_show(mddev_t *mddev, char *page)
2936 {
2937         return sprintf(page, "%d (%s)\n", speed_min(mddev),
2938                        mddev->sync_speed_min ? "local": "system");
2939 }
2940
2941 static ssize_t
2942 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
2943 {
2944         int min;
2945         char *e;
2946         if (strncmp(buf, "system", 6)==0) {
2947                 mddev->sync_speed_min = 0;
2948                 return len;
2949         }
2950         min = simple_strtoul(buf, &e, 10);
2951         if (buf == e || (*e && *e != '\n') || min <= 0)
2952                 return -EINVAL;
2953         mddev->sync_speed_min = min;
2954         return len;
2955 }
2956
2957 static struct md_sysfs_entry md_sync_min =
2958 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
2959
2960 static ssize_t
2961 sync_max_show(mddev_t *mddev, char *page)
2962 {
2963         return sprintf(page, "%d (%s)\n", speed_max(mddev),
2964                        mddev->sync_speed_max ? "local": "system");
2965 }
2966
2967 static ssize_t
2968 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
2969 {
2970         int max;
2971         char *e;
2972         if (strncmp(buf, "system", 6)==0) {
2973                 mddev->sync_speed_max = 0;
2974                 return len;
2975         }
2976         max = simple_strtoul(buf, &e, 10);
2977         if (buf == e || (*e && *e != '\n') || max <= 0)
2978                 return -EINVAL;
2979         mddev->sync_speed_max = max;
2980         return len;
2981 }
2982
2983 static struct md_sysfs_entry md_sync_max =
2984 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
2985
2986 static ssize_t
2987 degraded_show(mddev_t *mddev, char *page)
2988 {
2989         return sprintf(page, "%d\n", mddev->degraded);
2990 }
2991 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
2992
2993 static ssize_t
2994 sync_speed_show(mddev_t *mddev, char *page)
2995 {
2996         unsigned long resync, dt, db;
2997         resync = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active));
2998         dt = ((jiffies - mddev->resync_mark) / HZ);
2999         if (!dt) dt++;
3000         db = resync - (mddev->resync_mark_cnt);
3001         return sprintf(page, "%ld\n", db/dt/2); /* K/sec */
3002 }
3003
3004 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
3005
3006 static ssize_t
3007 sync_completed_show(mddev_t *mddev, char *page)
3008 {
3009         unsigned long max_blocks, resync;
3010
3011         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
3012                 max_blocks = mddev->resync_max_sectors;
3013         else
3014                 max_blocks = mddev->size << 1;
3015
3016         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
3017         return sprintf(page, "%lu / %lu\n", resync, max_blocks);
3018 }
3019
3020 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
3021
3022 static ssize_t
3023 max_sync_show(mddev_t *mddev, char *page)
3024 {
3025         if (mddev->resync_max == MaxSector)
3026                 return sprintf(page, "max\n");
3027         else
3028                 return sprintf(page, "%llu\n",
3029                                (unsigned long long)mddev->resync_max);
3030 }
3031 static ssize_t
3032 max_sync_store(mddev_t *mddev, const char *buf, size_t len)
3033 {
3034         if (strncmp(buf, "max", 3) == 0)
3035                 mddev->resync_max = MaxSector;
3036         else {
3037                 char *ep;
3038                 unsigned long long max = simple_strtoull(buf, &ep, 10);
3039                 if (ep == buf || (*ep != 0 && *ep != '\n'))
3040                         return -EINVAL;
3041                 if (max < mddev->resync_max &&
3042                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3043                         return -EBUSY;
3044
3045                 /* Must be a multiple of chunk_size */
3046                 if (mddev->chunk_size) {
3047                         if (max & (sector_t)((mddev->chunk_size>>9)-1))
3048                                 return -EINVAL;
3049                 }
3050                 mddev->resync_max = max;
3051         }
3052         wake_up(&mddev->recovery_wait);
3053         return len;
3054 }
3055
3056 static struct md_sysfs_entry md_max_sync =
3057 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
3058
3059 static ssize_t
3060 suspend_lo_show(mddev_t *mddev, char *page)
3061 {
3062         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
3063 }
3064
3065 static ssize_t
3066 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
3067 {
3068         char *e;
3069         unsigned long long new = simple_strtoull(buf, &e, 10);
3070
3071         if (mddev->pers->quiesce == NULL)
3072                 return -EINVAL;
3073         if (buf == e || (*e && *e != '\n'))
3074                 return -EINVAL;
3075         if (new >= mddev->suspend_hi ||
3076             (new > mddev->suspend_lo && new < mddev->suspend_hi)) {
3077                 mddev->suspend_lo = new;
3078                 mddev->pers->quiesce(mddev, 2);
3079                 return len;
3080         } else
3081                 return -EINVAL;
3082 }
3083 static struct md_sysfs_entry md_suspend_lo =
3084 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
3085
3086
3087 static ssize_t
3088 suspend_hi_show(mddev_t *mddev, char *page)
3089 {
3090         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
3091 }
3092
3093 static ssize_t
3094 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
3095 {
3096         char *e;
3097         unsigned long long new = simple_strtoull(buf, &e, 10);
3098
3099         if (mddev->pers->quiesce == NULL)
3100                 return -EINVAL;
3101         if (buf == e || (*e && *e != '\n'))
3102                 return -EINVAL;
3103         if ((new <= mddev->suspend_lo && mddev->suspend_lo >= mddev->suspend_hi) ||
3104             (new > mddev->suspend_lo && new > mddev->suspend_hi)) {
3105                 mddev->suspend_hi = new;
3106                 mddev->pers->quiesce(mddev, 1);
3107                 mddev->pers->quiesce(mddev, 0);
3108                 return len;
3109         } else
3110                 return -EINVAL;
3111 }
3112 static struct md_sysfs_entry md_suspend_hi =
3113 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
3114
3115 static ssize_t
3116 reshape_position_show(mddev_t *mddev, char *page)
3117 {
3118         if (mddev->reshape_position != MaxSector)
3119                 return sprintf(page, "%llu\n",
3120                                (unsigned long long)mddev->reshape_position);
3121         strcpy(page, "none\n");
3122         return 5;
3123 }
3124
3125 static ssize_t
3126 reshape_position_store(mddev_t *mddev, const char *buf, size_t len)
3127 {
3128         char *e;
3129         unsigned long long new = simple_strtoull(buf, &e, 10);
3130         if (mddev->pers)
3131                 return -EBUSY;
3132         if (buf == e || (*e && *e != '\n'))
3133                 return -EINVAL;
3134         mddev->reshape_position = new;
3135         mddev->delta_disks = 0;
3136         mddev->new_level = mddev->level;
3137         mddev->new_layout = mddev->layout;
3138         mddev->new_chunk = mddev->chunk_size;
3139         return len;
3140 }
3141
3142 static struct md_sysfs_entry md_reshape_position =
3143 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
3144        reshape_position_store);
3145
3146
3147 static struct attribute *md_default_attrs[] = {
3148         &md_level.attr,
3149         &md_layout.attr,
3150         &md_raid_disks.attr,
3151         &md_chunk_size.attr,
3152         &md_size.attr,
3153         &md_resync_start.attr,
3154         &md_metadata.attr,
3155         &md_new_device.attr,
3156         &md_safe_delay.attr,
3157         &md_array_state.attr,
3158         &md_reshape_position.attr,
3159         NULL,
3160 };
3161
3162 static struct attribute *md_redundancy_attrs[] = {
3163         &md_scan_mode.attr,
3164         &md_mismatches.attr,
3165         &md_sync_min.attr,
3166         &md_sync_max.attr,
3167         &md_sync_speed.attr,
3168         &md_sync_completed.attr,
3169         &md_max_sync.attr,
3170         &md_suspend_lo.attr,
3171         &md_suspend_hi.attr,
3172         &md_bitmap.attr,
3173         &md_degraded.attr,
3174         NULL,
3175 };
3176 static struct attribute_group md_redundancy_group = {
3177         .name = NULL,
3178         .attrs = md_redundancy_attrs,
3179 };
3180
3181
3182 static ssize_t
3183 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3184 {
3185         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3186         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3187         ssize_t rv;
3188
3189         if (!entry->show)
3190                 return -EIO;
3191         rv = mddev_lock(mddev);
3192         if (!rv) {
3193                 rv = entry->show(mddev, page);
3194                 mddev_unlock(mddev);
3195         }
3196         return rv;
3197 }
3198
3199 static ssize_t
3200 md_attr_store(struct kobject *kobj, struct attribute *attr,
3201               const char *page, size_t length)
3202 {
3203         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3204         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3205         ssize_t rv;
3206
3207         if (!entry->store)
3208                 return -EIO;
3209         if (!capable(CAP_SYS_ADMIN))
3210                 return -EACCES;
3211         rv = mddev_lock(mddev);
3212         if (!rv) {
3213                 rv = entry->store(mddev, page, length);
3214                 mddev_unlock(mddev);
3215         }
3216         return rv;
3217 }
3218
3219 static void md_free(struct kobject *ko)
3220 {
3221         mddev_t *mddev = container_of(ko, mddev_t, kobj);
3222         kfree(mddev);
3223 }
3224
3225 static struct sysfs_ops md_sysfs_ops = {
3226         .show   = md_attr_show,
3227         .store  = md_attr_store,
3228 };
3229 static struct kobj_type md_ktype = {
3230         .release        = md_free,
3231         .sysfs_ops      = &md_sysfs_ops,
3232         .default_attrs  = md_default_attrs,
3233 };
3234
3235 int mdp_major = 0;
3236
3237 static struct kobject *md_probe(dev_t dev, int *part, void *data)
3238 {
3239         static DEFINE_MUTEX(disks_mutex);
3240         mddev_t *mddev = mddev_find(dev);
3241         struct gendisk *disk;
3242         int partitioned = (MAJOR(dev) != MD_MAJOR);
3243         int shift = partitioned ? MdpMinorShift : 0;
3244         int unit = MINOR(dev) >> shift;
3245         int error;
3246
3247         if (!mddev)
3248                 return NULL;
3249
3250         mutex_lock(&disks_mutex);
3251         if (mddev->gendisk) {
3252                 mutex_unlock(&disks_mutex);
3253                 mddev_put(mddev);
3254                 return NULL;
3255         }
3256         disk = alloc_disk(1 << shift);
3257         if (!disk) {
3258                 mutex_unlock(&disks_mutex);
3259                 mddev_put(mddev);
3260                 return NULL;
3261         }
3262         disk->major = MAJOR(dev);
3263         disk->first_minor = unit << shift;
3264         if (partitioned)
3265                 sprintf(disk->disk_name, "md_d%d", unit);
3266         else
3267                 sprintf(disk->disk_name, "md%d", unit);
3268         disk->fops = &md_fops;
3269         disk->private_data = mddev;
3270         disk->queue = mddev->queue;
3271         add_disk(disk);
3272         mddev->gendisk = disk;
3273         mutex_unlock(&disks_mutex);
3274         error = kobject_init_and_add(&mddev->kobj, &md_ktype, &disk->dev.kobj,
3275                                      "%s", "md");
3276         if (error)
3277                 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
3278                        disk->disk_name);
3279         else
3280                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
3281         return NULL;
3282 }
3283
3284 static void md_safemode_timeout(unsigned long data)
3285 {
3286         mddev_t *mddev = (mddev_t *) data;
3287
3288         mddev->safemode = 1;
3289         md_wakeup_thread(mddev->thread);
3290 }
3291
3292 static int start_dirty_degraded;
3293
3294 static int do_md_run(mddev_t * mddev)
3295 {
3296         int err;
3297         int chunk_size;
3298         struct list_head *tmp;
3299         mdk_rdev_t *rdev;
3300         struct gendisk *disk;
3301         struct mdk_personality *pers;
3302         char b[BDEVNAME_SIZE];
3303
3304         if (list_empty(&mddev->disks))
3305                 /* cannot run an array with no devices.. */
3306                 return -EINVAL;
3307
3308         if (mddev->pers)
3309                 return -EBUSY;
3310
3311         /*
3312          * Analyze all RAID superblock(s)
3313          */
3314         if (!mddev->raid_disks) {
3315                 if (!mddev->persistent)
3316                         return -EINVAL;
3317                 analyze_sbs(mddev);
3318         }
3319
3320         chunk_size = mddev->chunk_size;
3321
3322         if (chunk_size) {
3323                 if (chunk_size > MAX_CHUNK_SIZE) {
3324                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
3325                                 chunk_size, MAX_CHUNK_SIZE);
3326                         return -EINVAL;
3327                 }
3328                 /*
3329                  * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
3330                  */
3331                 if ( (1 << ffz(~chunk_size)) != chunk_size) {
3332                         printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
3333                         return -EINVAL;
3334                 }
3335                 if (chunk_size < PAGE_SIZE) {
3336                         printk(KERN_ERR "too small chunk_size: %d < %ld\n",
3337                                 chunk_size, PAGE_SIZE);
3338                         return -EINVAL;
3339                 }
3340
3341                 /* devices must have minimum size of one chunk */
3342                 rdev_for_each(rdev, tmp, mddev) {
3343                         if (test_bit(Faulty, &rdev->flags))
3344                                 continue;
3345                         if (rdev->size < chunk_size / 1024) {
3346                                 printk(KERN_WARNING
3347                                         "md: Dev %s smaller than chunk_size:"
3348                                         " %lluk < %dk\n",
3349                                         bdevname(rdev->bdev,b),
3350                                         (unsigned long long)rdev->size,
3351                                         chunk_size / 1024);
3352                                 return -EINVAL;
3353                         }
3354                 }
3355         }
3356
3357 #ifdef CONFIG_KMOD
3358         if (mddev->level != LEVEL_NONE)
3359                 request_module("md-level-%d", mddev->level);
3360         else if (mddev->clevel[0])
3361                 request_module("md-%s", mddev->clevel);
3362 #endif
3363
3364         /*
3365          * Drop all container device buffers, from now on
3366          * the only valid external interface is through the md
3367          * device.
3368          */
3369         rdev_for_each(rdev, tmp, mddev) {
3370                 if (test_bit(Faulty, &rdev->flags))
3371                         continue;
3372                 sync_blockdev(rdev->bdev);
3373                 invalidate_bdev(rdev->bdev);
3374
3375                 /* perform some consistency tests on the device.
3376                  * We don't want the data to overlap the metadata,
3377                  * Internal Bitmap issues has handled elsewhere.
3378                  */
3379                 if (rdev->data_offset < rdev->sb_offset) {
3380                         if (mddev->size &&
3381                             rdev->data_offset + mddev->size*2
3382                             > rdev->sb_offset*2) {
3383                                 printk("md: %s: data overlaps metadata\n",
3384                                        mdname(mddev));
3385                                 return -EINVAL;
3386                         }
3387                 } else {
3388                         if (rdev->sb_offset*2 + rdev->sb_size/512
3389                             > rdev->data_offset) {
3390                                 printk("md: %s: metadata overlaps data\n",
3391                                        mdname(mddev));
3392                                 return -EINVAL;
3393                         }
3394                 }
3395         }
3396
3397         md_probe(mddev->unit, NULL, NULL);
3398         disk = mddev->gendisk;
3399         if (!disk)
3400                 return -ENOMEM;
3401
3402         spin_lock(&pers_lock);
3403         pers = find_pers(mddev->level, mddev->clevel);
3404         if (!pers || !try_module_get(pers->owner)) {
3405                 spin_unlock(&pers_lock);
3406                 if (mddev->level != LEVEL_NONE)
3407                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
3408                                mddev->level);
3409                 else
3410                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
3411                                mddev->clevel);
3412                 return -EINVAL;
3413         }
3414         mddev->pers = pers;
3415         spin_unlock(&pers_lock);
3416         mddev->level = pers->level;
3417         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3418
3419         if (mddev->reshape_position != MaxSector &&
3420             pers->start_reshape == NULL) {
3421                 /* This personality cannot handle reshaping... */
3422                 mddev->pers = NULL;
3423                 module_put(pers->owner);
3424                 return -EINVAL;
3425         }
3426
3427         if (pers->sync_request) {
3428                 /* Warn if this is a potentially silly
3429                  * configuration.
3430                  */
3431                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
3432                 mdk_rdev_t *rdev2;
3433                 struct list_head *tmp2;
3434                 int warned = 0;
3435                 rdev_for_each(rdev, tmp, mddev) {
3436                         rdev_for_each(rdev2, tmp2, mddev) {
3437                                 if (rdev < rdev2 &&
3438                                     rdev->bdev->bd_contains ==
3439                                     rdev2->bdev->bd_contains) {
3440                                         printk(KERN_WARNING
3441                                                "%s: WARNING: %s appears to be"
3442                                                " on the same physical disk as"
3443                                                " %s.\n",
3444                                                mdname(mddev),
3445                                                bdevname(rdev->bdev,b),
3446                                                bdevname(rdev2->bdev,b2));
3447                                         warned = 1;
3448                                 }
3449                         }
3450                 }
3451                 if (warned)
3452                         printk(KERN_WARNING
3453                                "True protection against single-disk"
3454                                " failure might be compromised.\n");
3455         }
3456
3457         mddev->recovery = 0;
3458         mddev->resync_max_sectors = mddev->size << 1; /* may be over-ridden by personality */
3459         mddev->barriers_work = 1;
3460         mddev->ok_start_degraded = start_dirty_degraded;
3461
3462         if (start_readonly)
3463                 mddev->ro = 2; /* read-only, but switch on first write */
3464
3465         err = mddev->pers->run(mddev);
3466         if (!err && mddev->pers->sync_request) {
3467                 err = bitmap_create(mddev);
3468                 if (err) {
3469                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
3470                                mdname(mddev), err);
3471                         mddev->pers->stop(mddev);
3472                 }
3473         }
3474         if (err) {
3475                 printk(KERN_ERR "md: pers->run() failed ...\n");
3476                 module_put(mddev->pers->owner);
3477                 mddev->pers = NULL;
3478                 bitmap_destroy(mddev);
3479                 return err;
3480         }
3481         if (mddev->pers->sync_request) {
3482                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3483                         printk(KERN_WARNING
3484                                "md: cannot register extra attributes for %s\n",
3485                                mdname(mddev));
3486         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
3487                 mddev->ro = 0;
3488
3489         atomic_set(&mddev->writes_pending,0);
3490         mddev->safemode = 0;
3491         mddev->safemode_timer.function = md_safemode_timeout;
3492         mddev->safemode_timer.data = (unsigned long) mddev;
3493         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
3494         mddev->in_sync = 1;
3495
3496         rdev_for_each(rdev, tmp, mddev)
3497                 if (rdev->raid_disk >= 0) {
3498                         char nm[20];
3499                         sprintf(nm, "rd%d", rdev->raid_disk);
3500                         if (sysfs_create_link(&mddev->kobj, &rdev->kobj, nm))
3501                                 printk("md: cannot register %s for %s\n",
3502                                        nm, mdname(mddev));
3503                 }
3504         
3505         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3506         
3507         if (mddev->flags)
3508                 md_update_sb(mddev, 0);
3509
3510         set_capacity(disk, mddev->array_size<<1);
3511
3512         /* If we call blk_queue_make_request here, it will
3513          * re-initialise max_sectors etc which may have been
3514          * refined inside -> run.  So just set the bits we need to set.
3515          * Most initialisation happended when we called
3516          * blk_queue_make_request(..., md_fail_request)
3517          * earlier.
3518          */
3519         mddev->queue->queuedata = mddev;
3520         mddev->queue->make_request_fn = mddev->pers->make_request;
3521
3522         /* If there is a partially-recovered drive we need to
3523          * start recovery here.  If we leave it to md_check_recovery,
3524          * it will remove the drives and not do the right thing
3525          */
3526         if (mddev->degraded && !mddev->sync_thread) {
3527                 struct list_head *rtmp;
3528                 int spares = 0;
3529                 rdev_for_each(rdev, rtmp, mddev)
3530                         if (rdev->raid_disk >= 0 &&
3531                             !test_bit(In_sync, &rdev->flags) &&
3532                             !test_bit(Faulty, &rdev->flags))
3533                                 /* complete an interrupted recovery */
3534                                 spares++;
3535                 if (spares && mddev->pers->sync_request) {
3536                         mddev->recovery = 0;
3537                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3538                         mddev->sync_thread = md_register_thread(md_do_sync,
3539                                                                 mddev,
3540                                                                 "%s_resync");
3541                         if (!mddev->sync_thread) {
3542                                 printk(KERN_ERR "%s: could not start resync"
3543                                        " thread...\n",
3544                                        mdname(mddev));
3545                                 /* leave the spares where they are, it shouldn't hurt */
3546                                 mddev->recovery = 0;
3547                         }
3548                 }
3549         }
3550         md_wakeup_thread(mddev->thread);
3551         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
3552
3553         mddev->changed = 1;
3554         md_new_event(mddev);
3555         kobject_uevent(&mddev->gendisk->dev.kobj, KOBJ_CHANGE);
3556         return 0;
3557 }
3558
3559 static int restart_array(mddev_t *mddev)
3560 {
3561         struct gendisk *disk = mddev->gendisk;
3562         int err;
3563
3564         /*
3565          * Complain if it has no devices
3566          */
3567         err = -ENXIO;
3568         if (list_empty(&mddev->disks))
3569                 goto out;
3570
3571         if (mddev->pers) {
3572                 err = -EBUSY;
3573                 if (!mddev->ro)
3574                         goto out;
3575
3576                 mddev->safemode = 0;
3577                 mddev->ro = 0;
3578                 set_disk_ro(disk, 0);
3579
3580                 printk(KERN_INFO "md: %s switched to read-write mode.\n",
3581                         mdname(mddev));
3582                 /*
3583                  * Kick recovery or resync if necessary
3584                  */
3585                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3586                 md_wakeup_thread(mddev->thread);
3587                 md_wakeup_thread(mddev->sync_thread);
3588                 err = 0;
3589         } else
3590                 err = -EINVAL;
3591
3592 out:
3593         return err;
3594 }
3595
3596 /* similar to deny_write_access, but accounts for our holding a reference
3597  * to the file ourselves */
3598 static int deny_bitmap_write_access(struct file * file)
3599 {
3600         struct inode *inode = file->f_mapping->host;
3601
3602         spin_lock(&inode->i_lock);
3603         if (atomic_read(&inode->i_writecount) > 1) {
3604                 spin_unlock(&inode->i_lock);
3605                 return -ETXTBSY;
3606         }
3607         atomic_set(&inode->i_writecount, -1);
3608         spin_unlock(&inode->i_lock);
3609
3610         return 0;
3611 }
3612
3613 static void restore_bitmap_write_access(struct file *file)
3614 {
3615         struct inode *inode = file->f_mapping->host;
3616
3617         spin_lock(&inode->i_lock);
3618         atomic_set(&inode->i_writecount, 1);
3619         spin_unlock(&inode->i_lock);
3620 }
3621
3622 /* mode:
3623  *   0 - completely stop and dis-assemble array
3624  *   1 - switch to readonly
3625  *   2 - stop but do not disassemble array
3626  */
3627 static int do_md_stop(mddev_t * mddev, int mode)
3628 {
3629         int err = 0;
3630         struct gendisk *disk = mddev->gendisk;
3631
3632         if (mddev->pers) {
3633                 if (atomic_read(&mddev->active)>2) {
3634                         printk("md: %s still in use.\n",mdname(mddev));
3635                         return -EBUSY;
3636                 }
3637
3638                 if (mddev->sync_thread) {
3639                         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3640                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3641                         md_unregister_thread(mddev->sync_thread);
3642                         mddev->sync_thread = NULL;
3643                 }
3644
3645                 del_timer_sync(&mddev->safemode_timer);
3646
3647                 invalidate_partition(disk, 0);
3648
3649                 switch(mode) {
3650                 case 1: /* readonly */
3651                         err  = -ENXIO;
3652                         if (mddev->ro==1)
3653                                 goto out;
3654                         mddev->ro = 1;
3655                         break;
3656                 case 0: /* disassemble */
3657                 case 2: /* stop */
3658                         bitmap_flush(mddev);
3659                         md_super_wait(mddev);
3660                         if (mddev->ro)
3661                                 set_disk_ro(disk, 0);
3662                         blk_queue_make_request(mddev->queue, md_fail_request);
3663                         mddev->pers->stop(mddev);
3664                         mddev->queue->merge_bvec_fn = NULL;
3665                         mddev->queue->unplug_fn = NULL;
3666                         mddev->queue->backing_dev_info.congested_fn = NULL;
3667                         if (mddev->pers->sync_request)
3668                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
3669
3670                         module_put(mddev->pers->owner);
3671                         mddev->pers = NULL;
3672
3673                         set_capacity(disk, 0);
3674                         mddev->changed = 1;
3675
3676                         if (mddev->ro)
3677                                 mddev->ro = 0;
3678                 }
3679                 if (!mddev->in_sync || mddev->flags) {
3680                         /* mark array as shutdown cleanly */
3681                         mddev->in_sync = 1;
3682                         md_update_sb(mddev, 1);
3683                 }
3684                 if (mode == 1)
3685                         set_disk_ro(disk, 1);
3686                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3687         }
3688
3689         /*
3690          * Free resources if final stop
3691          */
3692         if (mode == 0) {
3693                 mdk_rdev_t *rdev;
3694                 struct list_head *tmp;
3695
3696                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
3697
3698                 bitmap_destroy(mddev);
3699                 if (mddev->bitmap_file) {
3700                         restore_bitmap_write_access(mddev->bitmap_file);
3701                         fput(mddev->bitmap_file);
3702                         mddev->bitmap_file = NULL;
3703                 }
3704                 mddev->bitmap_offset = 0;
3705
3706                 rdev_for_each(rdev, tmp, mddev)
3707                         if (rdev->raid_disk >= 0) {
3708                                 char nm[20];
3709                                 sprintf(nm, "rd%d", rdev->raid_disk);
3710                                 sysfs_remove_link(&mddev->kobj, nm);
3711                         }
3712
3713                 /* make sure all md_delayed_delete calls have finished */
3714                 flush_scheduled_work();
3715
3716                 export_array(mddev);
3717
3718                 mddev->array_size = 0;
3719                 mddev->size = 0;
3720                 mddev->raid_disks = 0;
3721                 mddev->recovery_cp = 0;
3722                 mddev->resync_max = MaxSector;
3723                 mddev->reshape_position = MaxSector;
3724                 mddev->external = 0;
3725                 mddev->persistent = 0;
3726
3727         } else if (mddev->pers)
3728                 printk(KERN_INFO "md: %s switched to read-only mode.\n",
3729                         mdname(mddev));
3730         err = 0;
3731         md_new_event(mddev);
3732 out:
3733         return err;
3734 }
3735
3736 #ifndef MODULE
3737 static void autorun_array(mddev_t *mddev)
3738 {
3739         mdk_rdev_t *rdev;
3740         struct list_head *tmp;
3741         int err;
3742
3743         if (list_empty(&mddev->disks))
3744                 return;
3745
3746         printk(KERN_INFO "md: running: ");
3747
3748         rdev_for_each(rdev, tmp, mddev) {
3749                 char b[BDEVNAME_SIZE];
3750                 printk("<%s>", bdevname(rdev->bdev,b));
3751         }
3752         printk("\n");
3753
3754         err = do_md_run (mddev);
3755         if (err) {
3756                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
3757                 do_md_stop (mddev, 0);
3758         }
3759 }
3760
3761 /*
3762  * lets try to run arrays based on all disks that have arrived
3763  * until now. (those are in pending_raid_disks)
3764  *
3765  * the method: pick the first pending disk, collect all disks with
3766  * the same UUID, remove all from the pending list and put them into
3767  * the 'same_array' list. Then order this list based on superblock
3768  * update time (freshest comes first), kick out 'old' disks and
3769  * compare superblocks. If everything's fine then run it.
3770  *
3771  * If "unit" is allocated, then bump its reference count
3772  */
3773 static void autorun_devices(int part)
3774 {
3775         struct list_head *tmp;
3776         mdk_rdev_t *rdev0, *rdev;
3777         mddev_t *mddev;
3778         char b[BDEVNAME_SIZE];
3779
3780         printk(KERN_INFO "md: autorun ...\n");
3781         while (!list_empty(&pending_raid_disks)) {
3782                 int unit;
3783                 dev_t dev;
3784                 LIST_HEAD(candidates);
3785                 rdev0 = list_entry(pending_raid_disks.next,
3786                                          mdk_rdev_t, same_set);
3787
3788                 printk(KERN_INFO "md: considering %s ...\n",
3789                         bdevname(rdev0->bdev,b));
3790                 INIT_LIST_HEAD(&candidates);
3791                 rdev_for_each_list(rdev, tmp, pending_raid_disks)
3792                         if (super_90_load(rdev, rdev0, 0) >= 0) {
3793                                 printk(KERN_INFO "md:  adding %s ...\n",
3794                                         bdevname(rdev->bdev,b));
3795                                 list_move(&rdev->same_set, &candidates);
3796                         }
3797                 /*
3798                  * now we have a set of devices, with all of them having
3799                  * mostly sane superblocks. It's time to allocate the
3800                  * mddev.
3801                  */
3802                 if (part) {
3803                         dev = MKDEV(mdp_major,
3804                                     rdev0->preferred_minor << MdpMinorShift);
3805                         unit = MINOR(dev) >> MdpMinorShift;
3806                 } else {
3807                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
3808                         unit = MINOR(dev);
3809                 }
3810             &n