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