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