md: remove the 'super' sysfs attribute from devices in an 'md' array
[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 errors_show(mdk_rdev_t *rdev, char *page)
1868 {
1869         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
1870 }
1871
1872 static ssize_t
1873 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1874 {
1875         char *e;
1876         unsigned long n = simple_strtoul(buf, &e, 10);
1877         if (*buf && (*e == 0 || *e == '\n')) {
1878                 atomic_set(&rdev->corrected_errors, n);
1879                 return len;
1880         }
1881         return -EINVAL;
1882 }
1883 static struct rdev_sysfs_entry rdev_errors =
1884 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
1885
1886 static ssize_t
1887 slot_show(mdk_rdev_t *rdev, char *page)
1888 {
1889         if (rdev->raid_disk < 0)
1890                 return sprintf(page, "none\n");
1891         else
1892                 return sprintf(page, "%d\n", rdev->raid_disk);
1893 }
1894
1895 static ssize_t
1896 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1897 {
1898         char *e;
1899         int err;
1900         char nm[20];
1901         int slot = simple_strtoul(buf, &e, 10);
1902         if (strncmp(buf, "none", 4)==0)
1903                 slot = -1;
1904         else if (e==buf || (*e && *e!= '\n'))
1905                 return -EINVAL;
1906         if (rdev->mddev->pers) {
1907                 /* Setting 'slot' on an active array requires also
1908                  * updating the 'rd%d' link, and communicating
1909                  * with the personality with ->hot_*_disk.
1910                  * For now we only support removing
1911                  * failed/spare devices.  This normally happens automatically,
1912                  * but not when the metadata is externally managed.
1913                  */
1914                 if (slot != -1)
1915                         return -EBUSY;
1916                 if (rdev->raid_disk == -1)
1917                         return -EEXIST;
1918                 /* personality does all needed checks */
1919                 if (rdev->mddev->pers->hot_add_disk == NULL)
1920                         return -EINVAL;
1921                 err = rdev->mddev->pers->
1922                         hot_remove_disk(rdev->mddev, rdev->raid_disk);
1923                 if (err)
1924                         return err;
1925                 sprintf(nm, "rd%d", rdev->raid_disk);
1926                 sysfs_remove_link(&rdev->mddev->kobj, nm);
1927                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
1928                 md_wakeup_thread(rdev->mddev->thread);
1929         } else {
1930                 if (slot >= rdev->mddev->raid_disks)
1931                         return -ENOSPC;
1932                 rdev->raid_disk = slot;
1933                 /* assume it is working */
1934                 clear_bit(Faulty, &rdev->flags);
1935                 clear_bit(WriteMostly, &rdev->flags);
1936                 set_bit(In_sync, &rdev->flags);
1937         }
1938         return len;
1939 }
1940
1941
1942 static struct rdev_sysfs_entry rdev_slot =
1943 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
1944
1945 static ssize_t
1946 offset_show(mdk_rdev_t *rdev, char *page)
1947 {
1948         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
1949 }
1950
1951 static ssize_t
1952 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1953 {
1954         char *e;
1955         unsigned long long offset = simple_strtoull(buf, &e, 10);
1956         if (e==buf || (*e && *e != '\n'))
1957                 return -EINVAL;
1958         if (rdev->mddev->pers)
1959                 return -EBUSY;
1960         if (rdev->size && rdev->mddev->external)
1961                 /* Must set offset before size, so overlap checks
1962                  * can be sane */
1963                 return -EBUSY;
1964         rdev->data_offset = offset;
1965         return len;
1966 }
1967
1968 static struct rdev_sysfs_entry rdev_offset =
1969 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
1970
1971 static ssize_t
1972 rdev_size_show(mdk_rdev_t *rdev, char *page)
1973 {
1974         return sprintf(page, "%llu\n", (unsigned long long)rdev->size);
1975 }
1976
1977 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
1978 {
1979         /* check if two start/length pairs overlap */
1980         if (s1+l1 <= s2)
1981                 return 0;
1982         if (s2+l2 <= s1)
1983                 return 0;
1984         return 1;
1985 }
1986
1987 static ssize_t
1988 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1989 {
1990         char *e;
1991         unsigned long long size = simple_strtoull(buf, &e, 10);
1992         unsigned long long oldsize = rdev->size;
1993         mddev_t *my_mddev = rdev->mddev;
1994
1995         if (e==buf || (*e && *e != '\n'))
1996                 return -EINVAL;
1997         if (my_mddev->pers)
1998                 return -EBUSY;
1999         rdev->size = size;
2000         if (size > oldsize && rdev->mddev->external) {
2001                 /* need to check that all other rdevs with the same ->bdev
2002                  * do not overlap.  We need to unlock the mddev to avoid
2003                  * a deadlock.  We have already changed rdev->size, and if
2004                  * we have to change it back, we will have the lock again.
2005                  */
2006                 mddev_t *mddev;
2007                 int overlap = 0;
2008                 struct list_head *tmp, *tmp2;
2009
2010                 mddev_unlock(my_mddev);
2011                 for_each_mddev(mddev, tmp) {
2012                         mdk_rdev_t *rdev2;
2013
2014                         mddev_lock(mddev);
2015                         rdev_for_each(rdev2, tmp2, mddev)
2016                                 if (test_bit(AllReserved, &rdev2->flags) ||
2017                                     (rdev->bdev == rdev2->bdev &&
2018                                      rdev != rdev2 &&
2019                                      overlaps(rdev->data_offset, rdev->size,
2020                                             rdev2->data_offset, rdev2->size))) {
2021                                         overlap = 1;
2022                                         break;
2023                                 }
2024                         mddev_unlock(mddev);
2025                         if (overlap) {
2026                                 mddev_put(mddev);
2027                                 break;
2028                         }
2029                 }
2030                 mddev_lock(my_mddev);
2031                 if (overlap) {
2032                         /* Someone else could have slipped in a size
2033                          * change here, but doing so is just silly.
2034                          * We put oldsize back because we *know* it is
2035                          * safe, and trust userspace not to race with
2036                          * itself
2037                          */
2038                         rdev->size = oldsize;
2039                         return -EBUSY;
2040                 }
2041         }
2042         if (size < my_mddev->size || my_mddev->size == 0)
2043                 my_mddev->size = size;
2044         return len;
2045 }
2046
2047 static struct rdev_sysfs_entry rdev_size =
2048 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2049
2050 static struct attribute *rdev_default_attrs[] = {
2051         &rdev_state.attr,
2052         &rdev_errors.attr,
2053         &rdev_slot.attr,
2054         &rdev_offset.attr,
2055         &rdev_size.attr,
2056         NULL,
2057 };
2058 static ssize_t
2059 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2060 {
2061         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2062         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2063         mddev_t *mddev = rdev->mddev;
2064         ssize_t rv;
2065
2066         if (!entry->show)
2067                 return -EIO;
2068
2069         rv = mddev ? mddev_lock(mddev) : -EBUSY;
2070         if (!rv) {
2071                 if (rdev->mddev == NULL)
2072                         rv = -EBUSY;
2073                 else
2074                         rv = entry->show(rdev, page);
2075                 mddev_unlock(mddev);
2076         }
2077         return rv;
2078 }
2079
2080 static ssize_t
2081 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
2082               const char *page, size_t length)
2083 {
2084         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2085         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2086         ssize_t rv;
2087         mddev_t *mddev = rdev->mddev;
2088
2089         if (!entry->store)
2090                 return -EIO;
2091         if (!capable(CAP_SYS_ADMIN))
2092                 return -EACCES;
2093         rv = mddev ? mddev_lock(mddev): -EBUSY;
2094         if (!rv) {
2095                 if (rdev->mddev == NULL)
2096                         rv = -EBUSY;
2097                 else
2098                         rv = entry->store(rdev, page, length);
2099                 mddev_unlock(rdev->mddev);
2100         }
2101         return rv;
2102 }
2103
2104 static void rdev_free(struct kobject *ko)
2105 {
2106         mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
2107         kfree(rdev);
2108 }
2109 static struct sysfs_ops rdev_sysfs_ops = {
2110         .show           = rdev_attr_show,
2111         .store          = rdev_attr_store,
2112 };
2113 static struct kobj_type rdev_ktype = {
2114         .release        = rdev_free,
2115         .sysfs_ops      = &rdev_sysfs_ops,
2116         .default_attrs  = rdev_default_attrs,
2117 };
2118
2119 /*
2120  * Import a device. If 'super_format' >= 0, then sanity check the superblock
2121  *
2122  * mark the device faulty if:
2123  *
2124  *   - the device is nonexistent (zero size)
2125  *   - the device has no valid superblock
2126  *
2127  * a faulty rdev _never_ has rdev->sb set.
2128  */
2129 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
2130 {
2131         char b[BDEVNAME_SIZE];
2132         int err;
2133         mdk_rdev_t *rdev;
2134         sector_t size;
2135
2136         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
2137         if (!rdev) {
2138                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
2139                 return ERR_PTR(-ENOMEM);
2140         }
2141
2142         if ((err = alloc_disk_sb(rdev)))
2143                 goto abort_free;
2144
2145         err = lock_rdev(rdev, newdev, super_format == -2);
2146         if (err)
2147                 goto abort_free;
2148
2149         kobject_init(&rdev->kobj, &rdev_ktype);
2150
2151         rdev->desc_nr = -1;
2152         rdev->saved_raid_disk = -1;
2153         rdev->raid_disk = -1;
2154         rdev->flags = 0;
2155         rdev->data_offset = 0;
2156         rdev->sb_events = 0;
2157         atomic_set(&rdev->nr_pending, 0);
2158         atomic_set(&rdev->read_errors, 0);
2159         atomic_set(&rdev->corrected_errors, 0);
2160
2161         size = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
2162         if (!size) {
2163                 printk(KERN_WARNING 
2164                         "md: %s has zero or unknown size, marking faulty!\n",
2165                         bdevname(rdev->bdev,b));
2166                 err = -EINVAL;
2167                 goto abort_free;
2168         }
2169
2170         if (super_format >= 0) {
2171                 err = super_types[super_format].
2172                         load_super(rdev, NULL, super_minor);
2173                 if (err == -EINVAL) {
2174                         printk(KERN_WARNING
2175                                 "md: %s does not have a valid v%d.%d "
2176                                "superblock, not importing!\n",
2177                                 bdevname(rdev->bdev,b),
2178                                super_format, super_minor);
2179                         goto abort_free;
2180                 }
2181                 if (err < 0) {
2182                         printk(KERN_WARNING 
2183                                 "md: could not read %s's sb, not importing!\n",
2184                                 bdevname(rdev->bdev,b));
2185                         goto abort_free;
2186                 }
2187         }
2188         INIT_LIST_HEAD(&rdev->same_set);
2189
2190         return rdev;
2191
2192 abort_free:
2193         if (rdev->sb_page) {
2194                 if (rdev->bdev)
2195                         unlock_rdev(rdev);
2196                 free_disk_sb(rdev);
2197         }
2198         kfree(rdev);
2199         return ERR_PTR(err);
2200 }
2201
2202 /*
2203  * Check a full RAID array for plausibility
2204  */
2205
2206
2207 static void analyze_sbs(mddev_t * mddev)
2208 {
2209         int i;
2210         struct list_head *tmp;
2211         mdk_rdev_t *rdev, *freshest;
2212         char b[BDEVNAME_SIZE];
2213
2214         freshest = NULL;
2215         rdev_for_each(rdev, tmp, mddev)
2216                 switch (super_types[mddev->major_version].
2217                         load_super(rdev, freshest, mddev->minor_version)) {
2218                 case 1:
2219                         freshest = rdev;
2220                         break;
2221                 case 0:
2222                         break;
2223                 default:
2224                         printk( KERN_ERR \
2225                                 "md: fatal superblock inconsistency in %s"
2226                                 " -- removing from array\n", 
2227                                 bdevname(rdev->bdev,b));
2228                         kick_rdev_from_array(rdev);
2229                 }
2230
2231
2232         super_types[mddev->major_version].
2233                 validate_super(mddev, freshest);
2234
2235         i = 0;
2236         rdev_for_each(rdev, tmp, mddev) {
2237                 if (rdev != freshest)
2238                         if (super_types[mddev->major_version].
2239                             validate_super(mddev, rdev)) {
2240                                 printk(KERN_WARNING "md: kicking non-fresh %s"
2241                                         " from array!\n",
2242                                         bdevname(rdev->bdev,b));
2243                                 kick_rdev_from_array(rdev);
2244                                 continue;
2245                         }
2246                 if (mddev->level == LEVEL_MULTIPATH) {
2247                         rdev->desc_nr = i++;
2248                         rdev->raid_disk = rdev->desc_nr;
2249                         set_bit(In_sync, &rdev->flags);
2250                 } else if (rdev->raid_disk >= mddev->raid_disks) {
2251                         rdev->raid_disk = -1;
2252                         clear_bit(In_sync, &rdev->flags);
2253                 }
2254         }
2255
2256
2257
2258         if (mddev->recovery_cp != MaxSector &&
2259             mddev->level >= 1)
2260                 printk(KERN_ERR "md: %s: raid array is not clean"
2261                        " -- starting background reconstruction\n",
2262                        mdname(mddev));
2263
2264 }
2265
2266 static ssize_t
2267 safe_delay_show(mddev_t *mddev, char *page)
2268 {
2269         int msec = (mddev->safemode_delay*1000)/HZ;
2270         return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
2271 }
2272 static ssize_t
2273 safe_delay_store(mddev_t *mddev, const char *cbuf, size_t len)
2274 {
2275         int scale=1;
2276         int dot=0;
2277         int i;
2278         unsigned long msec;
2279         char buf[30];
2280         char *e;
2281         /* remove a period, and count digits after it */
2282         if (len >= sizeof(buf))
2283                 return -EINVAL;
2284         strlcpy(buf, cbuf, len);
2285         buf[len] = 0;
2286         for (i=0; i<len; i++) {
2287                 if (dot) {
2288                         if (isdigit(buf[i])) {
2289                                 buf[i-1] = buf[i];
2290                                 scale *= 10;
2291                         }
2292                         buf[i] = 0;
2293                 } else if (buf[i] == '.') {
2294                         dot=1;
2295                         buf[i] = 0;
2296                 }
2297         }
2298         msec = simple_strtoul(buf, &e, 10);
2299         if (e == buf || (*e && *e != '\n'))
2300                 return -EINVAL;
2301         msec = (msec * 1000) / scale;
2302         if (msec == 0)
2303                 mddev->safemode_delay = 0;
2304         else {
2305                 mddev->safemode_delay = (msec*HZ)/1000;
2306                 if (mddev->safemode_delay == 0)
2307                         mddev->safemode_delay = 1;
2308         }
2309         return len;
2310 }
2311 static struct md_sysfs_entry md_safe_delay =
2312 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
2313
2314 static ssize_t
2315 level_show(mddev_t *mddev, char *page)
2316 {
2317         struct mdk_personality *p = mddev->pers;
2318         if (p)
2319                 return sprintf(page, "%s\n", p->name);
2320         else if (mddev->clevel[0])
2321                 return sprintf(page, "%s\n", mddev->clevel);
2322         else if (mddev->level != LEVEL_NONE)
2323                 return sprintf(page, "%d\n", mddev->level);
2324         else
2325                 return 0;
2326 }
2327
2328 static ssize_t
2329 level_store(mddev_t *mddev, const char *buf, size_t len)
2330 {
2331         ssize_t rv = len;
2332         if (mddev->pers)
2333                 return -EBUSY;
2334         if (len == 0)
2335                 return 0;
2336         if (len >= sizeof(mddev->clevel))
2337                 return -ENOSPC;
2338         strncpy(mddev->clevel, buf, len);
2339         if (mddev->clevel[len-1] == '\n')
2340                 len--;
2341         mddev->clevel[len] = 0;
2342         mddev->level = LEVEL_NONE;
2343         return rv;
2344 }
2345
2346 static struct md_sysfs_entry md_level =
2347 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
2348
2349
2350 static ssize_t
2351 layout_show(mddev_t *mddev, char *page)
2352 {
2353         /* just a number, not meaningful for all levels */
2354         if (mddev->reshape_position != MaxSector &&
2355             mddev->layout != mddev->new_layout)
2356                 return sprintf(page, "%d (%d)\n",
2357                                mddev->new_layout, mddev->layout);
2358         return sprintf(page, "%d\n", mddev->layout);
2359 }
2360
2361 static ssize_t
2362 layout_store(mddev_t *mddev, const char *buf, size_t len)
2363 {
2364         char *e;
2365         unsigned long n = simple_strtoul(buf, &e, 10);
2366
2367         if (!*buf || (*e && *e != '\n'))
2368                 return -EINVAL;
2369
2370         if (mddev->pers)
2371                 return -EBUSY;
2372         if (mddev->reshape_position != MaxSector)
2373                 mddev->new_layout = n;
2374         else
2375                 mddev->layout = n;
2376         return len;
2377 }
2378 static struct md_sysfs_entry md_layout =
2379 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
2380
2381
2382 static ssize_t
2383 raid_disks_show(mddev_t *mddev, char *page)
2384 {
2385         if (mddev->raid_disks == 0)
2386                 return 0;
2387         if (mddev->reshape_position != MaxSector &&
2388             mddev->delta_disks != 0)
2389                 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
2390                                mddev->raid_disks - mddev->delta_disks);
2391         return sprintf(page, "%d\n", mddev->raid_disks);
2392 }
2393
2394 static int update_raid_disks(mddev_t *mddev, int raid_disks);
2395
2396 static ssize_t
2397 raid_disks_store(mddev_t *mddev, const char *buf, size_t len)
2398 {
2399         char *e;
2400         int rv = 0;
2401         unsigned long n = simple_strtoul(buf, &e, 10);
2402
2403         if (!*buf || (*e && *e != '\n'))
2404                 return -EINVAL;
2405
2406         if (mddev->pers)
2407                 rv = update_raid_disks(mddev, n);
2408         else if (mddev->reshape_position != MaxSector) {
2409                 int olddisks = mddev->raid_disks - mddev->delta_disks;
2410                 mddev->delta_disks = n - olddisks;
2411                 mddev->raid_disks = n;
2412         } else
2413                 mddev->raid_disks = n;
2414         return rv ? rv : len;
2415 }
2416 static struct md_sysfs_entry md_raid_disks =
2417 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
2418
2419 static ssize_t
2420 chunk_size_show(mddev_t *mddev, char *page)
2421 {
2422         if (mddev->reshape_position != MaxSector &&
2423             mddev->chunk_size != mddev->new_chunk)
2424                 return sprintf(page, "%d (%d)\n", mddev->new_chunk,
2425                                mddev->chunk_size);
2426         return sprintf(page, "%d\n", mddev->chunk_size);
2427 }
2428
2429 static ssize_t
2430 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
2431 {
2432         /* can only set chunk_size if array is not yet active */
2433         char *e;
2434         unsigned long n = simple_strtoul(buf, &e, 10);
2435
2436         if (!*buf || (*e && *e != '\n'))
2437                 return -EINVAL;
2438
2439         if (mddev->pers)
2440                 return -EBUSY;
2441         else if (mddev->reshape_position != MaxSector)
2442                 mddev->new_chunk = n;
2443         else
2444                 mddev->chunk_size = n;
2445         return len;
2446 }
2447 static struct md_sysfs_entry md_chunk_size =
2448 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
2449
2450 static ssize_t
2451 resync_start_show(mddev_t *mddev, char *page)
2452 {
2453         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
2454 }
2455
2456 static ssize_t
2457 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
2458 {
2459         /* can only set chunk_size if array is not yet active */
2460         char *e;
2461         unsigned long long n = simple_strtoull(buf, &e, 10);
2462
2463         if (mddev->pers)
2464                 return -EBUSY;
2465         if (!*buf || (*e && *e != '\n'))
2466                 return -EINVAL;
2467
2468         mddev->recovery_cp = n;
2469         return len;
2470 }
2471 static struct md_sysfs_entry md_resync_start =
2472 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
2473
2474 /*
2475  * The array state can be:
2476  *
2477  * clear
2478  *     No devices, no size, no level
2479  *     Equivalent to STOP_ARRAY ioctl
2480  * inactive
2481  *     May have some settings, but array is not active
2482  *        all IO results in error
2483  *     When written, doesn't tear down array, but just stops it
2484  * suspended (not supported yet)
2485  *     All IO requests will block. The array can be reconfigured.
2486  *     Writing this, if accepted, will block until array is quiessent
2487  * readonly
2488  *     no resync can happen.  no superblocks get written.
2489  *     write requests fail
2490  * read-auto
2491  *     like readonly, but behaves like 'clean' on a write request.
2492  *
2493  * clean - no pending writes, but otherwise active.
2494  *     When written to inactive array, starts without resync
2495  *     If a write request arrives then
2496  *       if metadata is known, mark 'dirty' and switch to 'active'.
2497  *       if not known, block and switch to write-pending
2498  *     If written to an active array that has pending writes, then fails.
2499  * active
2500  *     fully active: IO and resync can be happening.
2501  *     When written to inactive array, starts with resync
2502  *
2503  * write-pending
2504  *     clean, but writes are blocked waiting for 'active' to be written.
2505  *
2506  * active-idle
2507  *     like active, but no writes have been seen for a while (100msec).
2508  *
2509  */
2510 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
2511                    write_pending, active_idle, bad_word};
2512 static char *array_states[] = {
2513         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
2514         "write-pending", "active-idle", NULL };
2515
2516 static int match_word(const char *word, char **list)
2517 {
2518         int n;
2519         for (n=0; list[n]; n++)
2520                 if (cmd_match(word, list[n]))
2521                         break;
2522         return n;
2523 }
2524
2525 static ssize_t
2526 array_state_show(mddev_t *mddev, char *page)
2527 {
2528         enum array_state st = inactive;
2529
2530         if (mddev->pers)
2531                 switch(mddev->ro) {
2532                 case 1:
2533                         st = readonly;
2534                         break;
2535                 case 2:
2536                         st = read_auto;
2537                         break;
2538                 case 0:
2539                         if (mddev->in_sync)
2540                                 st = clean;
2541                         else if (test_bit(MD_CHANGE_CLEAN, &mddev->flags))
2542                                 st = write_pending;
2543                         else if (mddev->safemode)
2544                                 st = active_idle;
2545                         else
2546                                 st = active;
2547                 }
2548         else {
2549                 if (list_empty(&mddev->disks) &&
2550                     mddev->raid_disks == 0 &&
2551                     mddev->size == 0)
2552                         st = clear;
2553                 else
2554                         st = inactive;
2555         }
2556         return sprintf(page, "%s\n", array_states[st]);
2557 }
2558
2559 static int do_md_stop(mddev_t * mddev, int ro);
2560 static int do_md_run(mddev_t * mddev);
2561 static int restart_array(mddev_t *mddev);
2562
2563 static ssize_t
2564 array_state_store(mddev_t *mddev, const char *buf, size_t len)
2565 {
2566         int err = -EINVAL;
2567         enum array_state st = match_word(buf, array_states);
2568         switch(st) {
2569         case bad_word:
2570                 break;
2571         case clear:
2572                 /* stopping an active array */
2573                 if (atomic_read(&mddev->active) > 1)
2574                         return -EBUSY;
2575                 err = do_md_stop(mddev, 0);
2576                 break;
2577         case inactive:
2578                 /* stopping an active array */
2579                 if (mddev->pers) {
2580                         if (atomic_read(&mddev->active) > 1)
2581                                 return -EBUSY;
2582                         err = do_md_stop(mddev, 2);
2583                 } else
2584                         err = 0; /* already inactive */
2585                 break;
2586         case suspended:
2587                 break; /* not supported yet */
2588         case readonly:
2589                 if (mddev->pers)
2590                         err = do_md_stop(mddev, 1);
2591                 else {
2592                         mddev->ro = 1;
2593                         err = do_md_run(mddev);
2594                 }
2595                 break;
2596         case read_auto:
2597                 /* stopping an active array */
2598                 if (mddev->pers) {
2599                         err = do_md_stop(mddev, 1);
2600                         if (err == 0)
2601                                 mddev->ro = 2; /* FIXME mark devices writable */
2602                 } else {
2603                         mddev->ro = 2;
2604                         err = do_md_run(mddev);
2605                 }
2606                 break;
2607         case clean:
2608                 if (mddev->pers) {
2609                         restart_array(mddev);
2610                         spin_lock_irq(&mddev->write_lock);
2611                         if (atomic_read(&mddev->writes_pending) == 0) {
2612                                 if (mddev->in_sync == 0) {
2613                                         mddev->in_sync = 1;
2614                                         if (mddev->persistent)
2615                                                 set_bit(MD_CHANGE_CLEAN,
2616                                                         &mddev->flags);
2617                                 }
2618                                 err = 0;
2619                         } else
2620                                 err = -EBUSY;
2621                         spin_unlock_irq(&mddev->write_lock);
2622                 } else {
2623                         mddev->ro = 0;
2624                         mddev->recovery_cp = MaxSector;
2625                         err = do_md_run(mddev);
2626                 }
2627                 break;
2628         case active:
2629                 if (mddev->pers) {
2630                         restart_array(mddev);
2631                         if (mddev->external)
2632                                 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2633                         wake_up(&mddev->sb_wait);
2634                         err = 0;
2635                 } else {
2636                         mddev->ro = 0;
2637                         err = do_md_run(mddev);
2638                 }
2639                 break;
2640         case write_pending:
2641         case active_idle:
2642                 /* these cannot be set */
2643                 break;
2644         }
2645         if (err)
2646                 return err;
2647         else
2648                 return len;
2649 }
2650 static struct md_sysfs_entry md_array_state =
2651 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
2652
2653 static ssize_t
2654 null_show(mddev_t *mddev, char *page)
2655 {
2656         return -EINVAL;
2657 }
2658
2659 static ssize_t
2660 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
2661 {
2662         /* buf must be %d:%d\n? giving major and minor numbers */
2663         /* The new device is added to the array.
2664          * If the array has a persistent superblock, we read the
2665          * superblock to initialise info and check validity.
2666          * Otherwise, only checking done is that in bind_rdev_to_array,
2667          * which mainly checks size.
2668          */
2669         char *e;
2670         int major = simple_strtoul(buf, &e, 10);
2671         int minor;
2672         dev_t dev;
2673         mdk_rdev_t *rdev;
2674         int err;
2675
2676         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
2677                 return -EINVAL;
2678         minor = simple_strtoul(e+1, &e, 10);
2679         if (*e && *e != '\n')
2680                 return -EINVAL;
2681         dev = MKDEV(major, minor);
2682         if (major != MAJOR(dev) ||
2683             minor != MINOR(dev))
2684                 return -EOVERFLOW;
2685
2686
2687         if (mddev->persistent) {
2688                 rdev = md_import_device(dev, mddev->major_version,
2689                                         mddev->minor_version);
2690                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
2691                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
2692                                                        mdk_rdev_t, same_set);
2693                         err = super_types[mddev->major_version]
2694                                 .load_super(rdev, rdev0, mddev->minor_version);
2695                         if (err < 0)
2696                                 goto out;
2697                 }
2698         } else if (mddev->external)
2699                 rdev = md_import_device(dev, -2, -1);
2700         else
2701                 rdev = md_import_device(dev, -1, -1);
2702
2703         if (IS_ERR(rdev))
2704                 return PTR_ERR(rdev);
2705         err = bind_rdev_to_array(rdev, mddev);
2706  out:
2707         if (err)
2708                 export_rdev(rdev);
2709         return err ? err : len;
2710 }
2711
2712 static struct md_sysfs_entry md_new_device =
2713 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
2714
2715 static ssize_t
2716 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
2717 {
2718         char *end;
2719         unsigned long chunk, end_chunk;
2720
2721         if (!mddev->bitmap)
2722                 goto out;
2723         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
2724         while (*buf) {
2725                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
2726                 if (buf == end) break;
2727                 if (*end == '-') { /* range */
2728                         buf = end + 1;
2729                         end_chunk = simple_strtoul(buf, &end, 0);
2730                         if (buf == end) break;
2731                 }
2732                 if (*end && !isspace(*end)) break;
2733                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
2734                 buf = end;
2735                 while (isspace(*buf)) buf++;
2736         }
2737         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
2738 out:
2739         return len;
2740 }
2741
2742 static struct md_sysfs_entry md_bitmap =
2743 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
2744
2745 static ssize_t
2746 size_show(mddev_t *mddev, char *page)
2747 {
2748         return sprintf(page, "%llu\n", (unsigned long long)mddev->size);
2749 }
2750
2751 static int update_size(mddev_t *mddev, unsigned long size);
2752
2753 static ssize_t
2754 size_store(mddev_t *mddev, const char *buf, size_t len)
2755 {
2756         /* If array is inactive, we can reduce the component size, but
2757          * not increase it (except from 0).
2758          * If array is active, we can try an on-line resize
2759          */
2760         char *e;
2761         int err = 0;
2762         unsigned long long size = simple_strtoull(buf, &e, 10);
2763         if (!*buf || *buf == '\n' ||
2764             (*e && *e != '\n'))
2765                 return -EINVAL;
2766
2767         if (mddev->pers) {
2768                 err = update_size(mddev, size);
2769                 md_update_sb(mddev, 1);
2770         } else {
2771                 if (mddev->size == 0 ||
2772                     mddev->size > size)
2773                         mddev->size = size;
2774                 else
2775                         err = -ENOSPC;
2776         }
2777         return err ? err : len;
2778 }
2779
2780 static struct md_sysfs_entry md_size =
2781 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
2782
2783
2784 /* Metdata version.
2785  * This is one of
2786  *   'none' for arrays with no metadata (good luck...)
2787  *   'external' for arrays with externally managed metadata,
2788  * or N.M for internally known formats
2789  */
2790 static ssize_t
2791 metadata_show(mddev_t *mddev, char *page)
2792 {
2793         if (mddev->persistent)
2794                 return sprintf(page, "%d.%d\n",
2795                                mddev->major_version, mddev->minor_version);
2796         else if (mddev->external)
2797                 return sprintf(page, "external:%s\n", mddev->metadata_type);
2798         else
2799                 return sprintf(page, "none\n");
2800 }
2801
2802 static ssize_t
2803 metadata_store(mddev_t *mddev, const char *buf, size_t len)
2804 {
2805         int major, minor;
2806         char *e;
2807         if (!list_empty(&mddev->disks))
2808                 return -EBUSY;
2809
2810         if (cmd_match(buf, "none")) {
2811                 mddev->persistent = 0;
2812                 mddev->external = 0;
2813                 mddev->major_version = 0;
2814                 mddev->minor_version = 90;
2815                 return len;
2816         }
2817         if (strncmp(buf, "external:", 9) == 0) {
2818                 size_t namelen = len-9;
2819                 if (namelen >= sizeof(mddev->metadata_type))
2820                         namelen = sizeof(mddev->metadata_type)-1;
2821                 strncpy(mddev->metadata_type, buf+9, namelen);
2822                 mddev->metadata_type[namelen] = 0;
2823                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
2824                         mddev->metadata_type[--namelen] = 0;
2825                 mddev->persistent = 0;
2826                 mddev->external = 1;
2827                 mddev->major_version = 0;
2828                 mddev->minor_version = 90;
2829                 return len;
2830         }
2831         major = simple_strtoul(buf, &e, 10);
2832         if (e==buf || *e != '.')
2833                 return -EINVAL;
2834         buf = e+1;
2835         minor = simple_strtoul(buf, &e, 10);
2836         if (e==buf || (*e && *e != '\n') )
2837                 return -EINVAL;
2838         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
2839                 return -ENOENT;
2840         mddev->major_version = major;
2841         mddev->minor_version = minor;
2842         mddev->persistent = 1;
2843         mddev->external = 0;
2844         return len;
2845 }
2846
2847 static struct md_sysfs_entry md_metadata =
2848 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
2849
2850 static ssize_t
2851 action_show(mddev_t *mddev, char *page)
2852 {
2853         char *type = "idle";
2854         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2855             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
2856                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2857                         type = "reshape";
2858                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2859                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2860                                 type = "resync";
2861                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2862                                 type = "check";
2863                         else
2864                                 type = "repair";
2865                 } else
2866                         type = "recover";
2867         }
2868         return sprintf(page, "%s\n", type);
2869 }
2870
2871 static ssize_t
2872 action_store(mddev_t *mddev, const char *page, size_t len)
2873 {
2874         if (!mddev->pers || !mddev->pers->sync_request)
2875                 return -EINVAL;
2876
2877         if (cmd_match(page, "idle")) {
2878                 if (mddev->sync_thread) {
2879                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2880                         md_unregister_thread(mddev->sync_thread);
2881                         mddev->sync_thread = NULL;
2882                         mddev->recovery = 0;
2883                 }
2884         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2885                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
2886                 return -EBUSY;
2887         else if (cmd_match(page, "resync") || cmd_match(page, "recover"))
2888                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2889         else if (cmd_match(page, "reshape")) {
2890                 int err;
2891                 if (mddev->pers->start_reshape == NULL)
2892                         return -EINVAL;
2893                 err = mddev->pers->start_reshape(mddev);
2894                 if (err)
2895                         return err;
2896         } else {
2897                 if (cmd_match(page, "check"))
2898                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
2899                 else if (!cmd_match(page, "repair"))
2900                         return -EINVAL;
2901                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
2902                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
2903         }
2904         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2905         md_wakeup_thread(mddev->thread);
2906         return len;
2907 }
2908
2909 static ssize_t
2910 mismatch_cnt_show(mddev_t *mddev, char *page)
2911 {
2912         return sprintf(page, "%llu\n",
2913                        (unsigned long long) mddev->resync_mismatches);
2914 }
2915
2916 static struct md_sysfs_entry md_scan_mode =
2917 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
2918
2919
2920 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
2921
2922 static ssize_t
2923 sync_min_show(mddev_t *mddev, char *page)
2924 {
2925         return sprintf(page, "%d (%s)\n", speed_min(mddev),
2926                        mddev->sync_speed_min ? "local": "system");
2927 }
2928
2929 static ssize_t
2930 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
2931 {
2932         int min;
2933         char *e;
2934         if (strncmp(buf, "system", 6)==0) {
2935                 mddev->sync_speed_min = 0;
2936                 return len;
2937         }
2938         min = simple_strtoul(buf, &e, 10);
2939         if (buf == e || (*e && *e != '\n') || min <= 0)
2940                 return -EINVAL;
2941         mddev->sync_speed_min = min;
2942         return len;
2943 }
2944
2945 static struct md_sysfs_entry md_sync_min =
2946 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
2947
2948 static ssize_t
2949 sync_max_show(mddev_t *mddev, char *page)
2950 {
2951         return sprintf(page, "%d (%s)\n", speed_max(mddev),
2952                        mddev->sync_speed_max ? "local": "system");
2953 }
2954
2955 static ssize_t
2956 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
2957 {
2958         int max;
2959         char *e;
2960         if (strncmp(buf, "system", 6)==0) {
2961                 mddev->sync_speed_max = 0;
2962                 return len;
2963         }
2964         max = simple_strtoul(buf, &e, 10);
2965         if (buf == e || (*e && *e != '\n') || max <= 0)
2966                 return -EINVAL;
2967         mddev->sync_speed_max = max;
2968         return len;
2969 }
2970
2971 static struct md_sysfs_entry md_sync_max =
2972 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
2973
2974 static ssize_t
2975 degraded_show(mddev_t *mddev, char *page)
2976 {
2977         return sprintf(page, "%d\n", mddev->degraded);
2978 }
2979 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
2980
2981 static ssize_t
2982 sync_speed_show(mddev_t *mddev, char *page)
2983 {
2984         unsigned long resync, dt, db;
2985         resync = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active));
2986         dt = ((jiffies - mddev->resync_mark) / HZ);
2987         if (!dt) dt++;
2988         db = resync - (mddev->resync_mark_cnt);
2989         return sprintf(page, "%ld\n", db/dt/2); /* K/sec */
2990 }
2991
2992 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
2993
2994 static ssize_t
2995 sync_completed_show(mddev_t *mddev, char *page)
2996 {
2997         unsigned long max_blocks, resync;
2998
2999         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
3000                 max_blocks = mddev->resync_max_sectors;
3001         else
3002                 max_blocks = mddev->size << 1;
3003
3004         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
3005         return sprintf(page, "%lu / %lu\n", resync, max_blocks);
3006 }
3007
3008 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
3009
3010 static ssize_t
3011 max_sync_show(mddev_t *mddev, char *page)
3012 {
3013         if (mddev->resync_max == MaxSector)
3014                 return sprintf(page, "max\n");
3015         else
3016                 return sprintf(page, "%llu\n",
3017                                (unsigned long long)mddev->resync_max);
3018 }
3019 static ssize_t
3020 max_sync_store(mddev_t *mddev, const char *buf, size_t len)
3021 {
3022         if (strncmp(buf, "max", 3) == 0)
3023                 mddev->resync_max = MaxSector;
3024         else {
3025                 char *ep;
3026                 unsigned long long max = simple_strtoull(buf, &ep, 10);
3027                 if (ep == buf || (*ep != 0 && *ep != '\n'))
3028                         return -EINVAL;
3029                 if (max < mddev->resync_max &&
3030                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3031                         return -EBUSY;
3032
3033                 /* Must be a multiple of chunk_size */
3034                 if (mddev->chunk_size) {
3035                         if (max & (sector_t)((mddev->chunk_size>>9)-1))
3036                                 return -EINVAL;
3037                 }
3038                 mddev->resync_max = max;
3039         }
3040         wake_up(&mddev->recovery_wait);
3041         return len;
3042 }
3043
3044 static struct md_sysfs_entry md_max_sync =
3045 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
3046
3047 static ssize_t
3048 suspend_lo_show(mddev_t *mddev, char *page)
3049 {
3050         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
3051 }
3052
3053 static ssize_t
3054 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
3055 {
3056         char *e;
3057         unsigned long long new = simple_strtoull(buf, &e, 10);
3058
3059         if (mddev->pers->quiesce == NULL)
3060                 return -EINVAL;
3061         if (buf == e || (*e && *e != '\n'))
3062                 return -EINVAL;
3063         if (new >= mddev->suspend_hi ||
3064             (new > mddev->suspend_lo && new < mddev->suspend_hi)) {
3065                 mddev->suspend_lo = new;
3066                 mddev->pers->quiesce(mddev, 2);
3067                 return len;
3068         } else
3069                 return -EINVAL;
3070 }
3071 static struct md_sysfs_entry md_suspend_lo =
3072 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
3073
3074
3075 static ssize_t
3076 suspend_hi_show(mddev_t *mddev, char *page)
3077 {
3078         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
3079 }
3080
3081 static ssize_t
3082 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
3083 {
3084         char *e;
3085         unsigned long long new = simple_strtoull(buf, &e, 10);
3086
3087         if (mddev->pers->quiesce == NULL)
3088                 return -EINVAL;
3089         if (buf == e || (*e && *e != '\n'))
3090                 return -EINVAL;
3091         if ((new <= mddev->suspend_lo && mddev->suspend_lo >= mddev->suspend_hi) ||
3092             (new > mddev->suspend_lo && new > mddev->suspend_hi)) {
3093                 mddev->suspend_hi = new;
3094                 mddev->pers->quiesce(mddev, 1);
3095                 mddev->pers->quiesce(mddev, 0);
3096                 return len;
3097         } else
3098                 return -EINVAL;
3099 }
3100 static struct md_sysfs_entry md_suspend_hi =
3101 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
3102
3103 static ssize_t
3104 reshape_position_show(mddev_t *mddev, char *page)
3105 {
3106         if (mddev->reshape_position != MaxSector)
3107                 return sprintf(page, "%llu\n",
3108                                (unsigned long long)mddev->reshape_position);
3109         strcpy(page, "none\n");
3110         return 5;
3111 }
3112
3113 static ssize_t
3114 reshape_position_store(mddev_t *mddev, const char *buf, size_t len)
3115 {
3116         char *e;
3117         unsigned long long new = simple_strtoull(buf, &e, 10);
3118         if (mddev->pers)
3119                 return -EBUSY;
3120         if (buf == e || (*e && *e != '\n'))
3121                 return -EINVAL;
3122         mddev->reshape_position = new;
3123         mddev->delta_disks = 0;
3124         mddev->new_level = mddev->level;
3125         mddev->new_layout = mddev->layout;
3126         mddev->new_chunk = mddev->chunk_size;
3127         return len;
3128 }
3129
3130 static struct md_sysfs_entry md_reshape_position =
3131 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
3132        reshape_position_store);
3133
3134
3135 static struct attribute *md_default_attrs[] = {
3136         &md_level.attr,
3137         &md_layout.attr,
3138         &md_raid_disks.attr,
3139         &md_chunk_size.attr,
3140         &md_size.attr,
3141         &md_resync_start.attr,
3142         &md_metadata.attr,
3143         &md_new_device.attr,
3144         &md_safe_delay.attr,
3145         &md_array_state.attr,
3146         &md_reshape_position.attr,
3147         NULL,
3148 };
3149
3150 static struct attribute *md_redundancy_attrs[] = {
3151         &md_scan_mode.attr,
3152         &md_mismatches.attr,
3153         &md_sync_min.attr,
3154         &md_sync_max.attr,
3155         &md_sync_speed.attr,
3156         &md_sync_completed.attr,
3157         &md_max_sync.attr,
3158         &md_suspend_lo.attr,
3159         &md_suspend_hi.attr,
3160         &md_bitmap.attr,
3161         &md_degraded.attr,
3162         NULL,
3163 };
3164 static struct attribute_group md_redundancy_group = {
3165         .name = NULL,
3166         .attrs = md_redundancy_attrs,
3167 };
3168
3169
3170 static ssize_t
3171 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3172 {
3173         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3174         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3175         ssize_t rv;
3176
3177         if (!entry->show)
3178                 return -EIO;
3179         rv = mddev_lock(mddev);
3180         if (!rv) {
3181                 rv = entry->show(mddev, page);
3182                 mddev_unlock(mddev);
3183         }
3184         return rv;
3185 }
3186
3187 static ssize_t
3188 md_attr_store(struct kobject *kobj, struct attribute *attr,
3189               const char *page, size_t length)
3190 {
3191         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3192         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3193         ssize_t rv;
3194
3195         if (!entry->store)
3196                 return -EIO;
3197         if (!capable(CAP_SYS_ADMIN))
3198                 return -EACCES;
3199         rv = mddev_lock(mddev);
3200         if (!rv) {
3201                 rv = entry->store(mddev, page, length);
3202                 mddev_unlock(mddev);
3203         }
3204         return rv;
3205 }
3206
3207 static void md_free(struct kobject *ko)
3208 {
3209         mddev_t *mddev = container_of(ko, mddev_t, kobj);
3210         kfree(mddev);
3211 }
3212
3213 static struct sysfs_ops md_sysfs_ops = {
3214         .show   = md_attr_show,
3215         .store  = md_attr_store,
3216 };
3217 static struct kobj_type md_ktype = {
3218         .release        = md_free,
3219         .sysfs_ops      = &md_sysfs_ops,
3220         .default_attrs  = md_default_attrs,
3221 };
3222
3223 int mdp_major = 0;
3224
3225 static struct kobject *md_probe(dev_t dev, int *part, void *data)
3226 {
3227         static DEFINE_MUTEX(disks_mutex);
3228         mddev_t *mddev = mddev_find(dev);
3229         struct gendisk *disk;
3230         int partitioned = (MAJOR(dev) != MD_MAJOR);
3231         int shift = partitioned ? MdpMinorShift : 0;
3232         int unit = MINOR(dev) >> shift;
3233         int error;
3234
3235         if (!mddev)
3236                 return NULL;
3237
3238         mutex_lock(&disks_mutex);
3239         if (mddev->gendisk) {
3240                 mutex_unlock(&disks_mutex);
3241                 mddev_put(mddev);
3242                 return NULL;
3243         }
3244         disk = alloc_disk(1 << shift);
3245         if (!disk) {
3246                 mutex_unlock(&disks_mutex);
3247                 mddev_put(mddev);
3248                 return NULL;
3249         }
3250         disk->major = MAJOR(dev);
3251         disk->first_minor = unit << shift;
3252         if (partitioned)
3253                 sprintf(disk->disk_name, "md_d%d", unit);
3254         else
3255                 sprintf(disk->disk_name, "md%d", unit);
3256         disk->fops = &md_fops;
3257         disk->private_data = mddev;
3258         disk->queue = mddev->queue;
3259         add_disk(disk);
3260         mddev->gendisk = disk;
3261         mutex_unlock(&disks_mutex);
3262         error = kobject_init_and_add(&mddev->kobj, &md_ktype, &disk->dev.kobj,
3263                                      "%s", "md");
3264         if (error)
3265                 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
3266                        disk->disk_name);
3267         else
3268                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
3269         return NULL;
3270 }
3271
3272 static void md_safemode_timeout(unsigned long data)
3273 {
3274         mddev_t *mddev = (mddev_t *) data;
3275
3276         mddev->safemode = 1;
3277         md_wakeup_thread(mddev->thread);
3278 }
3279
3280 static int start_dirty_degraded;
3281
3282 static int do_md_run(mddev_t * mddev)
3283 {
3284         int err;
3285         int chunk_size;
3286         struct list_head *tmp;
3287         mdk_rdev_t *rdev;
3288         struct gendisk *disk;
3289         struct mdk_personality *pers;
3290         char b[BDEVNAME_SIZE];
3291
3292         if (list_empty(&mddev->disks))
3293                 /* cannot run an array with no devices.. */
3294                 return -EINVAL;
3295
3296         if (mddev->pers)
3297                 return -EBUSY;
3298
3299         /*
3300          * Analyze all RAID superblock(s)
3301          */
3302         if (!mddev->raid_disks) {
3303                 if (!mddev->persistent)
3304                         return -EINVAL;
3305                 analyze_sbs(mddev);
3306         }
3307
3308         chunk_size = mddev->chunk_size;
3309
3310         if (chunk_size) {
3311                 if (chunk_size > MAX_CHUNK_SIZE) {
3312                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
3313                                 chunk_size, MAX_CHUNK_SIZE);
3314                         return -EINVAL;
3315                 }
3316                 /*
3317                  * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
3318                  */