md: Relax minimum size restrictions on chunk_size.
[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
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
3530                 /* devices must have minimum size of one chunk */
3531                 rdev_for_each(rdev, tmp, mddev) {
3532                         if (test_bit(Faulty, &rdev->flags))
3533                                 continue;
3534                         if (rdev->size < chunk_size / 1024) {
3535                                 printk(KERN_WARNING
3536                                         "md: Dev %s smaller than chunk_size:"
3537                                         " %lluk < %dk\n",
3538                                         bdevname(rdev->bdev,b),
3539                                         (unsigned long long)rdev->size,
3540                                         chunk_size / 1024);
3541                                 return -EINVAL;
3542                         }
3543                 }
3544         }
3545
3546         if (mddev->level != LEVEL_NONE)
3547                 request_module("md-level-%d", mddev->level);
3548         else if (mddev->clevel[0])
3549                 request_module("md-%s", mddev->clevel);
3550
3551         /*
3552          * Drop all container device buffers, from now on
3553          * the only valid external interface is through the md
3554          * device.
3555          */
3556         rdev_for_each(rdev, tmp, mddev) {
3557                 if (test_bit(Faulty, &rdev->flags))
3558                         continue;
3559                 sync_blockdev(rdev->bdev);
3560                 invalidate_bdev(rdev->bdev);
3561
3562                 /* perform some consistency tests on the device.
3563                  * We don't want the data to overlap the metadata,
3564                  * Internal Bitmap issues has handled elsewhere.
3565                  */
3566                 if (rdev->data_offset < rdev->sb_start) {
3567                         if (mddev->size &&
3568                             rdev->data_offset + mddev->size*2
3569                             > rdev->sb_start) {
3570                                 printk("md: %s: data overlaps metadata\n",
3571                                        mdname(mddev));
3572                                 return -EINVAL;
3573                         }
3574                 } else {
3575                         if (rdev->sb_start + rdev->sb_size/512
3576                             > rdev->data_offset) {
3577                                 printk("md: %s: metadata overlaps data\n",
3578                                        mdname(mddev));
3579                                 return -EINVAL;
3580                         }
3581                 }
3582                 sysfs_notify(&rdev->kobj, NULL, "state");
3583         }
3584
3585         md_probe(mddev->unit, NULL, NULL);
3586         disk = mddev->gendisk;
3587         if (!disk)
3588                 return -ENOMEM;
3589
3590         spin_lock(&pers_lock);
3591         pers = find_pers(mddev->level, mddev->clevel);
3592         if (!pers || !try_module_get(pers->owner)) {
3593                 spin_unlock(&pers_lock);
3594                 if (mddev->level != LEVEL_NONE)
3595                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
3596                                mddev->level);
3597                 else
3598                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
3599                                mddev->clevel);
3600                 return -EINVAL;
3601         }
3602         mddev->pers = pers;
3603         spin_unlock(&pers_lock);
3604         mddev->level = pers->level;
3605         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3606
3607         if (mddev->reshape_position != MaxSector &&
3608             pers->start_reshape == NULL) {
3609                 /* This personality cannot handle reshaping... */
3610                 mddev->pers = NULL;
3611                 module_put(pers->owner);
3612                 return -EINVAL;
3613         }
3614
3615         if (pers->sync_request) {
3616                 /* Warn if this is a potentially silly
3617                  * configuration.
3618                  */
3619                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
3620                 mdk_rdev_t *rdev2;
3621                 struct list_head *tmp2;
3622                 int warned = 0;
3623                 rdev_for_each(rdev, tmp, mddev) {
3624                         rdev_for_each(rdev2, tmp2, mddev) {
3625                                 if (rdev < rdev2 &&
3626                                     rdev->bdev->bd_contains ==
3627                                     rdev2->bdev->bd_contains) {
3628                                         printk(KERN_WARNING
3629                                                "%s: WARNING: %s appears to be"
3630                                                " on the same physical disk as"
3631                                                " %s.\n",
3632                                                mdname(mddev),
3633                                                bdevname(rdev->bdev,b),
3634                                                bdevname(rdev2->bdev,b2));
3635                                         warned = 1;
3636                                 }
3637                         }
3638                 }
3639                 if (warned)
3640                         printk(KERN_WARNING
3641                                "True protection against single-disk"
3642                                " failure might be compromised.\n");
3643         }
3644
3645         mddev->recovery = 0;
3646         mddev->resync_max_sectors = mddev->size << 1; /* may be over-ridden by personality */
3647         mddev->barriers_work = 1;
3648         mddev->ok_start_degraded = start_dirty_degraded;
3649
3650         if (start_readonly)
3651                 mddev->ro = 2; /* read-only, but switch on first write */
3652
3653         err = mddev->pers->run(mddev);
3654         if (err)
3655                 printk(KERN_ERR "md: pers->run() failed ...\n");
3656         else if (mddev->pers->sync_request) {
3657                 err = bitmap_create(mddev);
3658                 if (err) {
3659                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
3660                                mdname(mddev), err);
3661                         mddev->pers->stop(mddev);
3662                 }
3663         }
3664         if (err) {
3665                 module_put(mddev->pers->owner);
3666                 mddev->pers = NULL;
3667                 bitmap_destroy(mddev);
3668                 return err;
3669         }
3670         if (mddev->pers->sync_request) {
3671                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3672                         printk(KERN_WARNING
3673                                "md: cannot register extra attributes for %s\n",
3674                                mdname(mddev));
3675         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
3676                 mddev->ro = 0;
3677
3678         atomic_set(&mddev->writes_pending,0);
3679         mddev->safemode = 0;
3680         mddev->safemode_timer.function = md_safemode_timeout;
3681         mddev->safemode_timer.data = (unsigned long) mddev;
3682         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
3683         mddev->in_sync = 1;
3684
3685         rdev_for_each(rdev, tmp, mddev)
3686                 if (rdev->raid_disk >= 0) {
3687                         char nm[20];
3688                         sprintf(nm, "rd%d", rdev->raid_disk);
3689                         if (sysfs_create_link(&mddev->kobj, &rdev->kobj, nm))
3690                                 printk("md: cannot register %s for %s\n",
3691                                        nm, mdname(mddev));
3692                 }
3693         
3694         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3695         
3696         if (mddev->flags)
3697                 md_update_sb(mddev, 0);
3698
3699         set_capacity(disk, mddev->array_sectors);
3700
3701         /* If we call blk_queue_make_request here, it will
3702          * re-initialise max_sectors etc which may have been
3703          * refined inside -> run.  So just set the bits we need to set.
3704          * Most initialisation happended when we called
3705          * blk_queue_make_request(..., md_fail_request)
3706          * earlier.
3707          */
3708         mddev->queue->queuedata = mddev;
3709         mddev->queue->make_request_fn = mddev->pers->make_request;
3710
3711         /* If there is a partially-recovered drive we need to
3712          * start recovery here.  If we leave it to md_check_recovery,
3713          * it will remove the drives and not do the right thing
3714          */
3715         if (mddev->degraded && !mddev->sync_thread) {
3716                 struct list_head *rtmp;
3717                 int spares = 0;
3718                 rdev_for_each(rdev, rtmp, mddev)
3719                         if (rdev->raid_disk >= 0 &&
3720                             !test_bit(In_sync, &rdev->flags) &&
3721                             !test_bit(Faulty, &rdev->flags))
3722                                 /* complete an interrupted recovery */
3723                                 spares++;
3724                 if (spares && mddev->pers->sync_request) {
3725                         mddev->recovery = 0;
3726                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3727                         mddev->sync_thread = md_register_thread(md_do_sync,
3728                                                                 mddev,
3729                                                                 "%s_resync");
3730                         if (!mddev->sync_thread) {
3731                                 printk(KERN_ERR "%s: could not start resync"
3732                                        " thread...\n",
3733                                        mdname(mddev));
3734                                 /* leave the spares where they are, it shouldn't hurt */
3735                                 mddev->recovery = 0;
3736                         }
3737                 }
3738         }
3739         md_wakeup_thread(mddev->thread);
3740         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
3741
3742         mddev->changed = 1;
3743         md_new_event(mddev);
3744         sysfs_notify(&mddev->kobj, NULL, "array_state");
3745         sysfs_notify(&mddev->kobj, NULL, "sync_action");
3746         sysfs_notify(&mddev->kobj, NULL, "degraded");
3747         kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
3748         return 0;
3749 }
3750
3751 static int restart_array(mddev_t *mddev)
3752 {
3753         struct gendisk *disk = mddev->gendisk;
3754
3755         /* Complain if it has no devices */
3756         if (list_empty(&mddev->disks))
3757                 return -ENXIO;
3758         if (!mddev->pers)
3759                 return -EINVAL;
3760         if (!mddev->ro)
3761                 return -EBUSY;
3762         mddev->safemode = 0;
3763         mddev->ro = 0;
3764         set_disk_ro(disk, 0);
3765         printk(KERN_INFO "md: %s switched to read-write mode.\n",
3766                 mdname(mddev));
3767         /* Kick recovery or resync if necessary */
3768         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3769         md_wakeup_thread(mddev->thread);
3770         md_wakeup_thread(mddev->sync_thread);
3771         sysfs_notify(&mddev->kobj, NULL, "array_state");
3772         return 0;
3773 }
3774
3775 /* similar to deny_write_access, but accounts for our holding a reference
3776  * to the file ourselves */
3777 static int deny_bitmap_write_access(struct file * file)
3778 {
3779         struct inode *inode = file->f_mapping->host;
3780
3781         spin_lock(&inode->i_lock);
3782         if (atomic_read(&inode->i_writecount) > 1) {
3783                 spin_unlock(&inode->i_lock);
3784                 return -ETXTBSY;
3785         }
3786         atomic_set(&inode->i_writecount, -1);
3787         spin_unlock(&inode->i_lock);
3788
3789         return 0;
3790 }
3791
3792 static void restore_bitmap_write_access(struct file *file)
3793 {
3794         struct inode *inode = file->f_mapping->host;
3795
3796         spin_lock(&inode->i_lock);
3797         atomic_set(&inode->i_writecount, 1);
3798         spin_unlock(&inode->i_lock);
3799 }
3800
3801 /* mode:
3802  *   0 - completely stop and dis-assemble array
3803  *   1 - switch to readonly
3804  *   2 - stop but do not disassemble array
3805  */
3806 static int do_md_stop(mddev_t * mddev, int mode, int is_open)
3807 {
3808         int err = 0;
3809         struct gendisk *disk = mddev->gendisk;
3810
3811         if (atomic_read(&mddev->openers) > is_open) {
3812                 printk("md: %s still in use.\n",mdname(mddev));
3813                 return -EBUSY;
3814         }
3815
3816         if (mddev->pers) {
3817
3818                 if (mddev->sync_thread) {
3819                         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3820                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3821                         md_unregister_thread(mddev->sync_thread);
3822                         mddev->sync_thread = NULL;
3823                 }
3824
3825                 del_timer_sync(&mddev->safemode_timer);
3826
3827                 switch(mode) {
3828                 case 1: /* readonly */
3829                         err  = -ENXIO;
3830                         if (mddev->ro==1)
3831                                 goto out;
3832                         mddev->ro = 1;
3833                         break;
3834                 case 0: /* disassemble */
3835                 case 2: /* stop */
3836                         bitmap_flush(mddev);
3837                         md_super_wait(mddev);
3838                         if (mddev->ro)
3839                                 set_disk_ro(disk, 0);
3840                         blk_queue_make_request(mddev->queue, md_fail_request);
3841                         mddev->pers->stop(mddev);
3842                         mddev->queue->merge_bvec_fn = NULL;
3843                         mddev->queue->unplug_fn = NULL;
3844                         mddev->queue->backing_dev_info.congested_fn = NULL;
3845                         if (mddev->pers->sync_request)
3846                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
3847
3848                         module_put(mddev->pers->owner);
3849                         mddev->pers = NULL;
3850                         /* tell userspace to handle 'inactive' */
3851                         sysfs_notify(&mddev->kobj, NULL, "array_state");
3852
3853                         set_capacity(disk, 0);
3854                         mddev->changed = 1;
3855
3856                         if (mddev->ro)
3857                                 mddev->ro = 0;
3858                 }
3859                 if (!mddev->in_sync || mddev->flags) {
3860                         /* mark array as shutdown cleanly */
3861                         mddev->in_sync = 1;
3862                         md_update_sb(mddev, 1);
3863                 }
3864                 if (mode == 1)
3865                         set_disk_ro(disk, 1);
3866                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3867         }
3868
3869         /*
3870          * Free resources if final stop
3871          */
3872         if (mode == 0) {
3873                 mdk_rdev_t *rdev;
3874                 struct list_head *tmp;
3875
3876                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
3877
3878                 bitmap_destroy(mddev);
3879                 if (mddev->bitmap_file) {
3880                         restore_bitmap_write_access(mddev->bitmap_file);
3881                         fput(mddev->bitmap_file);
3882                         mddev->bitmap_file = NULL;
3883                 }
3884                 mddev->bitmap_offset = 0;
3885
3886                 rdev_for_each(rdev, tmp, mddev)
3887                         if (rdev->raid_disk >= 0) {
3888                                 char nm[20];
3889                                 sprintf(nm, "rd%d", rdev->raid_disk);
3890                                 sysfs_remove_link(&mddev->kobj, nm);
3891                         }
3892
3893                 /* make sure all md_delayed_delete calls have finished */
3894                 flush_scheduled_work();
3895
3896                 export_array(mddev);
3897
3898                 mddev->array_sectors = 0;
3899                 mddev->size = 0;
3900                 mddev->raid_disks = 0;
3901                 mddev->recovery_cp = 0;
3902                 mddev->resync_min = 0;
3903                 mddev->resync_max = MaxSector;
3904                 mddev->reshape_position = MaxSector;
3905                 mddev->external = 0;
3906                 mddev->persistent = 0;
3907                 mddev->level = LEVEL_NONE;
3908                 mddev->clevel[0] = 0;
3909                 mddev->flags = 0;
3910                 mddev->ro = 0;
3911                 mddev->metadata_type[0] = 0;
3912                 mddev->chunk_size = 0;
3913                 mddev->ctime = mddev->utime = 0;
3914                 mddev->layout = 0;
3915                 mddev->max_disks = 0;
3916                 mddev->events = 0;
3917                 mddev->delta_disks = 0;
3918                 mddev->new_level = LEVEL_NONE;
3919                 mddev->new_layout = 0;
3920                 mddev->new_chunk = 0;
3921                 mddev->curr_resync = 0;
3922                 mddev->resync_mismatches = 0;
3923                 mddev->suspend_lo = mddev->suspend_hi = 0;
3924                 mddev->sync_speed_min = mddev->sync_speed_max = 0;
3925                 mddev->recovery = 0;
3926                 mddev->in_sync = 0;
3927                 mddev->changed = 0;
3928                 mddev->degraded = 0;
3929                 mddev->barriers_work = 0;
3930                 mddev->safemode = 0;
3931
3932         } else if (mddev->pers)
3933                 printk(KERN_INFO "md: %s switched to read-only mode.\n",
3934                         mdname(mddev));
3935         err = 0;
3936         md_new_event(mddev);
3937         sysfs_notify(&mddev->kobj, NULL, "array_state");
3938 out:
3939         return err;
3940 }
3941
3942 #ifndef MODULE
3943 static void autorun_array(mddev_t *mddev)
3944 {
3945         mdk_rdev_t *rdev;
3946         struct list_head *tmp;
3947         int err;
3948
3949         if (list_empty(&mddev->disks))
3950                 return;
3951
3952         printk(KERN_INFO "md: running: ");
3953
3954         rdev_for_each(rdev, tmp, mddev) {
3955                 char b[BDEVNAME_SIZE];
3956                 printk("<%s>", bdevname(rdev->bdev,b));
3957         }
3958         printk("\n");
3959
3960         err = do_md_run(mddev);
3961         if (err) {
3962                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
3963                 do_md_stop(mddev, 0, 0);
3964         }
3965 }
3966
3967 /*
3968  * lets try to run arrays based on all disks that have arrived
3969  * until now. (those are in pending_raid_disks)
3970  *
3971  * the method: pick the first pending disk, collect all disks with
3972  * the same UUID, remove all from the pending list and put them into
3973  * the 'same_array' list. Then order this list based on superblock
3974  * update time (freshest comes first), kick out 'old' disks and
3975  * compare superblocks. If everything's fine then run it.
3976  *
3977  * If "unit" is allocated, then bump its reference count
3978  */
3979 static void autorun_devices(int part)
3980 {
3981         struct list_head *tmp;
3982         mdk_rdev_t *rdev0, *rdev;
3983         mddev_t *mddev;
3984         char b[BDEVNAME_SIZE];
3985
3986         printk(KERN_INFO "md: autorun ...\n");
3987         while (!list_empty(&pending_raid_disks)) {
3988                 int unit;
3989                 dev_t dev;
3990                 LIST_HEAD(candidates);
3991                 rdev0 = list_entry(pending_raid_disks.next,
3992                                          mdk_rdev_t, same_set);
3993
3994                 printk(KERN_INFO "md: considering %s ...\n",
3995                         bdevname(rdev0->bdev,b));
3996                 INIT_LIST_HEAD(&candidates);
3997                 rdev_for_each_list(rdev, tmp, pending_raid_disks)
3998                         if (super_90_load(rdev, rdev0, 0) >= 0) {
3999                                 printk(KERN_INFO "md:  adding %s ...\n",
4000                                         bdevname(rdev->bdev,b));
4001                                 list_move(&rdev->same_set, &candidates);
4002                         }
4003                 /*
4004                  * now we have a set of devices, with all of them having
4005                  * mostly sane superblocks. It's time to allocate the
4006                  * mddev.
4007                  */
4008                 if (part) {
4009                         dev = MKDEV(mdp_major,
4010                                     rdev0->preferred_minor << MdpMinorShift);
4011                         unit = MINOR(dev) >> MdpMinorShift;
4012                 } else {
4013                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
4014                         unit = MINOR(dev);
4015                 }
4016                 if (rdev0->preferred_minor != unit) {
4017                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
4018                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
4019                         break;
4020                 }
4021
4022                 md_probe(dev, NULL, NULL);
4023                 mddev = mddev_find(dev);
4024                 if (!mddev || !mddev->gendisk) {
4025                         if (mddev)
4026                                 mddev_put(mddev);
4027                         printk(KERN_ERR
4028                                 "md: cannot allocate memory for md drive.\n");
4029                         break;
4030                 }
4031                 if (mddev_lock(mddev)) 
4032                         printk(KERN_WARNING "md: %s locked, cannot run\n",
4033                                mdname(mddev));
4034                 else if (mddev->raid_disks || mddev->major_version
4035                          || !list_empty(&mddev->disks)) {
4036                         printk(KERN_WARNING 
4037                                 "md: %s already running, cannot run %s\n",
4038                                 mdname(mddev), bdevname(rdev0->bdev,b));
4039                         mddev_unlock(mddev);
4040                 } else {
4041                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
4042                         mddev->persistent = 1;
4043                         rdev_for_each_list(rdev, tmp, candidates) {
4044                                 list_del_init(&rdev->same_set);
4045                                 if (bind_rdev_to_array(rdev, mddev))
4046                                         export_rdev(rdev);
4047                         }
4048                         autorun_array(mddev);
4049                         mddev_unlock(mddev);
4050                 }
4051                 /* on success, candidates will be empty, on error
4052                  * it won't...
4053                  */
4054                 rdev_for_each_list(rdev, tmp, candidates) {
4055                         list_del_init(&rdev->same_set);
4056                         export_rdev(rdev);
4057                 }
4058                 mddev_put(mddev);
4059         }
4060         printk(KERN_INFO "md: ... autorun DONE.\n");
4061 }
4062 #endif /* !MODULE */
4063
4064 static int get_version(void __user * arg)
4065 {
4066         mdu_version_t ver;
4067
4068         ver.major = MD_MAJOR_VERSION;
4069         ver.minor = MD_MINOR_VERSION;
4070         ver.patchlevel = MD_PATCHLEVEL_VERSION;
4071
4072         if (copy_to_user(arg, &ver, sizeof(ver)))
4073                 return -EFAULT;
4074
4075         return 0;
4076 }
4077
4078 static int get_array_info(mddev_t * mddev, void __user * arg)
4079 {
4080         mdu_array_info_t info;
4081         int nr,working,active,failed,spare;
4082         mdk_rdev_t *rdev;
4083         struct list_head *tmp;
4084
4085         nr=working=active=failed=spare=0;
4086         rdev_for_each(rdev, tmp, mddev) {
4087                 nr++;
4088                 if (test_bit(Faulty, &rdev->flags))
4089                         failed++;
4090                 else {
4091                         working++;
4092                         if (test_bit(In_sync, &rdev->flags))
4093                                 active++;       
4094                         else
4095                                 spare++;
4096                 }
4097         }
4098
4099         info.major_version = mddev->major_version;
4100         info.minor_version = mddev->minor_version;
4101         info.patch_version = MD_PATCHLEVEL_VERSION;
4102         info.ctime         = mddev->ctime;
4103         info.level         = mddev->level;
4104         info.size          = mddev->size;
4105         if (info.size != mddev->size) /* overflow */
4106                 info.size = -1;
4107         info.nr_disks      = nr;
4108         info.raid_disks    = mddev->raid_disks;
4109         info.md_minor      = mddev->md_minor;
4110         info.not_persistent= !mddev->persistent;
4111
4112         info.utime         = mddev->utime;
4113         info.state         = 0;
4114         if (mddev->in_sync)
4115                 info.state = (1<<MD_SB_CLEAN);
4116         if (mddev->bitmap && mddev->bitmap_offset)
4117                 info.state = (1<<MD_SB_BITMAP_PRESENT);
4118         info.active_disks  = active;
4119         info.working_disks = working;
4120         info.failed_disks  = failed;
4121         info.spare_disks   = spare;
4122
4123         info.layout        = mddev->layout;
4124         info.chunk_size    = mddev->chunk_size;
4125
4126         if (copy_to_user(arg, &info, sizeof(info)))
4127                 return -EFAULT;
4128
4129         return 0;
4130 }
4131
4132 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
4133 {
4134         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
4135         char *ptr, *buf = NULL;
4136         int err = -ENOMEM;
4137
4138         if (md_allow_write(mddev))
4139                 file = kmalloc(sizeof(*file), GFP_NOIO);
4140         else
4141                 file = kmalloc(sizeof(*file), GFP_KERNEL);
4142
4143         if (!file)
4144                 goto out;
4145
4146         /* bitmap disabled, zero the first byte and copy out */
4147         if (!mddev->bitmap || !mddev->bitmap->file) {
4148                 file->pathname[0] = '\0';
4149                 goto copy_out;
4150         }
4151
4152         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
4153         if (!buf)
4154                 goto out;
4155
4156         ptr = d_path(&mddev->bitmap->file->f_path, buf, sizeof(file->pathname));
4157         if (IS_ERR(ptr))
4158                 goto out;
4159
4160         strcpy(file->pathname, ptr);
4161
4162 copy_out:
4163         err = 0;
4164         if (copy_to_user(arg, file, sizeof(*file)))
4165                 err = -EFAULT;
4166 out:
4167         kfree(buf);
4168         kfree(file);
4169         return err;
4170 }
4171
4172 static int get_disk_info(mddev_t * mddev, void __user * arg)
4173 {
4174         mdu_disk_info_t info;
4175         mdk_rdev_t *rdev;
4176
4177         if (copy_from_user(&info, arg, sizeof(info)))
4178                 return -EFAULT;
4179
4180         rdev = find_rdev_nr(mddev, info.number);
4181         if (rdev) {
4182                 info.major = MAJOR(rdev->bdev->bd_dev);
4183                 info.minor = MINOR(rdev->bdev->bd_dev);
4184                 info.raid_disk = rdev->raid_disk;
4185                 info.state = 0;
4186                 if (test_bit(Faulty, &rdev->flags))
4187                         info.state |= (1<<MD_DISK_FAULTY);
4188                 else if (test_bit(In_sync, &rdev->flags)) {
4189                         info.state |= (1<<MD_DISK_ACTIVE);
4190                         info.state |= (1<<MD_DISK_SYNC);
4191                 }
4192                 if (test_bit(WriteMostly, &rdev->flags))
4193                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
4194         } else {
4195                 info.major = info.minor = 0;
4196                 info.raid_disk = -1;
4197                 info.state = (1<<MD_DISK_REMOVED);
4198         }
4199
4200         if (copy_to_user(arg, &info, sizeof(info)))
4201                 return -EFAULT;
4202
4203         return 0;
4204 }
4205
4206 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
4207 {
4208         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4209         mdk_rdev_t *rdev;
4210         dev_t dev = MKDEV(info->major,info->minor);
4211
4212         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
4213                 return -EOVERFLOW;
4214
4215         if (!mddev->raid_disks) {
4216                 int err;
4217                 /* expecting a device which has a superblock */
4218                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
4219                 if (IS_ERR(rdev)) {
4220                         printk(KERN_WARNING 
4221                                 "md: md_import_device returned %ld\n",
4222                                 PTR_ERR(rdev));
4223                         return PTR_ERR(rdev);
4224                 }
4225                 if (!list_empty(&mddev->disks)) {
4226                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
4227                                                         mdk_rdev_t, same_set);
4228                         int err = super_types[mddev->major_version]
4229                                 .load_super(rdev, rdev0, mddev->minor_version);
4230                         if (err < 0) {
4231                                 printk(KERN_WARNING 
4232                                         "md: %s has different UUID to %s\n",
4233                                         bdevname(rdev->bdev,b), 
4234                                         bdevname(rdev0->bdev,b2));
4235                                 export_rdev(rdev);
4236                                 return -EINVAL;
4237                         }
4238                 }
4239                 err = bind_rdev_to_array(rdev, mddev);
4240                 if (err)
4241                         export_rdev(rdev);
4242                 return err;
4243         }
4244
4245         /*
4246          * add_new_disk can be used once the array is assembled
4247          * to add "hot spares".  They must already have a superblock
4248          * written
4249          */
4250         if (mddev->pers) {
4251                 int err;
4252                 if (!mddev->pers->hot_add_disk) {
4253                         printk(KERN_WARNING 
4254                                 "%s: personality does not support diskops!\n",
4255                                mdname(mddev));
4256                         return -EINVAL;
4257                 }
4258                 if (mddev->persistent)
4259                         rdev = md_import_device(dev, mddev->major_version,
4260                                                 mddev->minor_version);
4261                 else
4262                         rdev = md_import_device(dev, -1, -1);
4263                 if (IS_ERR(rdev)) {
4264                         printk(KERN_WARNING 
4265                                 "md: md_import_device returned %ld\n",
4266                                 PTR_ERR(rdev));
4267                         return PTR_ERR(rdev);
4268                 }
4269                 /* set save_raid_disk if appropriate */
4270                 if (!mddev->persistent) {
4271                         if (info->state & (1<<MD_DISK_SYNC)  &&
4272                             info->raid_disk < mddev->raid_disks)
4273                                 rdev->raid_disk = info->raid_disk;
4274                         else
4275                                 rdev->raid_disk = -1;
4276                 } else
4277                         super_types[mddev->major_version].
4278                                 validate_super(mddev, rdev);
4279                 rdev->saved_raid_disk = rdev->raid_disk;
4280
4281                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
4282                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
4283                         set_bit(WriteMostly, &rdev->flags);
4284
4285                 rdev->raid_disk = -1;
4286                 err = bind_rdev_to_array(rdev, mddev);
4287                 if (!err && !mddev->pers->hot_remove_disk) {
4288                         /* If there is hot_add_disk but no hot_remove_disk
4289                          * then added disks for geometry changes,
4290                          * and should be added immediately.
4291                          */
4292                         super_types[mddev->major_version].
4293                                 validate_super(mddev, rdev);
4294                         err = mddev->pers->hot_add_disk(mddev, rdev);
4295                         if (err)
4296                                 unbind_rdev_from_array(rdev);
4297                 }
4298                 if (err)
4299                         export_rdev(rdev);
4300                 else
4301                         sysfs_notify(&rdev->kobj, NULL, "state");
4302
4303                 md_update_sb(mddev, 1);
4304                 if (mddev->degraded)
4305                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4306                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4307                 md_wakeup_thread(mddev->thread);
4308                 return err;
4309         }
4310
4311         /* otherwise, add_new_disk is only allowed
4312          * for major_version==0 superblocks
4313          */
4314         if (mddev->major_version != 0) {
4315                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
4316                        mdname(mddev));
4317                 return -EINVAL;
4318         }
4319
4320         if (!(info->state & (1<<MD_DISK_FAULTY))) {
4321                 int err;
4322                 rdev = md_import_device(dev, -1, 0);
4323                 if (IS_ERR(rdev)) {
4324                         printk(KERN_WARNING 
4325                                 "md: error, md_import_device() returned %ld\n",
4326                                 PTR_ERR(rdev));
4327                         return PTR_ERR(rdev);
4328                 }
4329                 rdev->desc_nr = info->number;
4330                 if (info->raid_disk < mddev->raid_disks)
4331                         rdev->raid_disk = info->raid_disk;
4332                 else
4333                         rdev->raid_disk = -1;
4334
4335                 if (rdev->raid_disk < mddev->raid_disks)
4336                         if (info->state & (1<<MD_DISK_SYNC))
4337                                 set_bit(In_sync, &rdev->flags);
4338
4339                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
4340                         set_bit(WriteMostly, &rdev->flags);
4341
4342                 if (!mddev->persistent) {
4343                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
4344                         rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
4345                 } else 
4346                         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
4347                 rdev->size = calc_num_sectors(rdev, mddev->chunk_size) / 2;
4348
4349                 err = bind_rdev_to_array(rdev, mddev);
4350                 if (err) {
4351                         export_rdev(rdev);
4352                         return err;
4353                 }
4354         }
4355
4356         return 0;
4357 }
4358
4359 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
4360 {
4361         char b[BDEVNAME_SIZE];
4362         mdk_rdev_t *rdev;
4363
4364         rdev = find_rdev(mddev, dev);
4365         if (!rdev)
4366                 return -ENXIO;
4367
4368         if (rdev->raid_disk >= 0)
4369                 goto busy;
4370
4371         kick_rdev_from_array(rdev);
4372         md_update_sb(mddev, 1);
4373         md_new_event(mddev);
4374
4375         return 0;
4376 busy:
4377         printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
4378                 bdevname(rdev->bdev,b), mdname(mddev));
4379         return -EBUSY;
4380 }
4381
4382 static int hot_add_disk(mddev_t * mddev, dev_t dev)
4383 {
4384         char b[BDEVNAME_SIZE];
4385         int err;
4386         mdk_rdev_t *rdev;
4387
4388         if (!mddev->pers)
4389                 return -ENODEV;
4390
4391         if (mddev->major_version != 0) {
4392                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
4393                         " version-0 superblocks.\n",
4394                         mdname(mddev));
4395                 return -EINVAL;
4396         }
4397         if (!mddev->pers->hot_add_disk) {
4398                 printk(KERN_WARNING 
4399                         "%s: personality does not support diskops!\n",
4400                         mdname(mddev));
4401                 return -EINVAL;
4402         }
4403
4404         rdev = md_import_device(dev, -1, 0);
4405         if (IS_ERR(rdev)) {
4406                 printk(KERN_WARNING 
4407                         "md: error, md_import_device() returned %ld\n",
4408                         PTR_ERR(rdev));
4409                 return -EINVAL;
4410         }
4411
4412         if (mddev->persistent)
4413                 rdev->sb_start = calc_dev_sboffset(rdev->bdev);
4414         else
4415                 rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
4416
4417         rdev->size = calc_num_sectors(rdev, mddev->chunk_size) / 2;
4418
4419         if (test_bit(Faulty, &rdev->flags)) {
4420                 printk(KERN_WARNING 
4421                         "md: can not hot-add faulty %s disk to %s!\n",
4422                         bdevname(rdev->bdev,b), mdname(mddev));
4423                 err = -EINVAL;
4424                 goto abort_export;
4425         }
4426         clear_bit(In_sync, &rdev->flags);
4427         rdev->desc_nr = -1;
4428         rdev->saved_raid_disk = -1;
4429         err = bind_rdev_to_array(rdev, mddev);
4430         if (err)
4431                 goto abort_export;
4432
4433         /*
4434          * The rest should better be atomic, we can have disk failures
4435          * noticed in interrupt contexts ...
4436          */
4437
4438         if (rdev->desc_nr == mddev->max_disks) {
4439                 printk(KERN_WARNING "%s: can not hot-add to full array!\n",
4440                         mdname(mddev));
4441                 err = -EBUSY;
4442                 goto abort_unbind_export;
4443         }
4444
4445         rdev->raid_disk = -1;
4446
4447         md_update_sb(mddev, 1);
4448
4449         /*
4450          * Kick recovery, maybe this spare has to be added to the
4451          * array immediately.
4452          */
4453         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4454         md_wakeup_thread(mddev->thread);
4455         md_new_event(mddev);
4456         return 0;
4457
4458 abort_unbind_export:
4459         unbind_rdev_from_array(rdev);
4460
4461 abort_export:
4462         export_rdev(rdev);
4463         return err;
4464 }
4465
4466 static int set_bitmap_file(mddev_t *mddev, int fd)
4467 {
4468         int err;
4469
4470         if (mddev->pers) {
4471                 if (!mddev->pers->quiesce)
4472                         return -EBUSY;
4473                 if (mddev->recovery || mddev->sync_thread)
4474                         return -EBUSY;
4475                 /* we should be able to change the bitmap.. */
4476         }
4477
4478
4479         if (fd >= 0) {
4480                 if (mddev->bitmap)
4481                         return -EEXIST; /* cannot add when bitmap is present */
4482                 mddev->bitmap_file = fget(fd);
4483
4484                 if (mddev->bitmap_file == NULL) {
4485                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
4486                                mdname(mddev));
4487                         return -EBADF;
4488                 }
4489
4490                 err = deny_bitmap_write_access(mddev->bitmap_file);
4491                 if (err) {
4492                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
4493                                mdname(mddev));
4494                         fput(mddev->bitmap_file);
4495                         mddev->bitmap_file = NULL;
4496                         return err;
4497                 }
4498                 mddev->bitmap_offset = 0; /* file overrides offset */
4499         } else if (mddev->bitmap == NULL)
4500                 return -ENOENT; /* cannot remove what isn't there */
4501         err = 0;
4502         if (mddev->pers) {
4503                 mddev->pers->quiesce(mddev, 1);
4504                 if (fd >= 0)
4505                         err = bitmap_create(mddev);
4506                 if (fd < 0 || err) {
4507                         bitmap_destroy(mddev);
4508                         fd = -1; /* make sure to put the file */
4509                 }
4510                 mddev->pers->quiesce(mddev, 0);
4511         }
4512         if (fd < 0) {
4513                 if (mddev->bitmap_file) {
4514                         restore_bitmap_write_access(mddev->bitmap_file);
4515                         fput(mddev->bitmap_file);
4516                 }
4517                 mddev->bitmap_file = NULL;
4518         }
4519
4520         return err;
4521 }
4522
4523 /*
4524  * set_array_info is used two different ways
4525  * The original usage is when creating a new array.
4526  * In this usage, raid_disks is > 0 and it together with
4527  *  level, size, not_persistent,layout,chunksize determine the
4528  *  shape of the array.
4529  *  This will always create an array with a type-0.90.0 superblock.
4530  * The newer usage is when assembling an array.
4531  *  In this case raid_disks will be 0, and the major_version field is
4532  *  use to determine which style super-blocks are to be found on the devices.
4533  *  The minor and patch _version numbers are also kept incase the
4534  *  super_block handler wishes to interpret them.
4535  */
4536 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
4537 {
4538
4539         if (info->raid_disks == 0) {
4540                 /* just setting version number for superblock loading */
4541                 if (info->major_version < 0 ||
4542                     info->major_version >= ARRAY_SIZE(super_types) ||
4543                     super_types[info->major_version].name == NULL) {
4544                         /* maybe try to auto-load a module? */
4545                         printk(KERN_INFO 
4546                                 "md: superblock version %d not known\n",
4547                                 info->major_version);
4548                         return -EINVAL;
4549                 }
4550                 mddev->major_version = info->major_version;
4551                 mddev->minor_version = info->minor_version;
4552                 mddev->patch_version = info->patch_version;
4553                 mddev->persistent = !info->not_persistent;
4554                 return 0;
4555         }
4556         mddev->major_version = MD_MAJOR_VERSION;
4557         mddev->minor_version = MD_MINOR_VERSION;
4558         mddev->patch_version = MD_PATCHLEVEL_VERSION;
4559         mddev->ctime         = get_seconds();
4560
4561         mddev->level         = info->level;
4562         mddev->clevel[0]     = 0;
4563         mddev->size          = info->size;
4564         mddev->raid_disks    = info->raid_disks;
4565         /* don't set md_minor, it is determined by which /dev/md* was
4566          * openned
4567          */
4568         if (info->state & (1<<MD_SB_CLEAN))
4569                 mddev->recovery_cp = MaxSector;
4570         else
4571                 mddev->recovery_cp = 0;
4572         mddev->persistent    = ! info->not_persistent;
4573         mddev->external      = 0;
4574
4575         mddev->layout        = info->layout;
4576         mddev->chunk_size    = info->chunk_size;
4577
4578         mddev->max_disks     = MD_SB_DISKS;
4579
4580         if (mddev->persistent)
4581                 mddev->flags         = 0;
4582         set_bit(MD_CHANGE_DEVS, &mddev->flags);
4583
4584         mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
4585         mddev->bitmap_offset = 0;
4586
4587         mddev->reshape_position = MaxSector;
4588
4589         /*
4590          * Generate a 128 bit UUID
4591          */
4592         get_random_bytes(mddev->uuid, 16);
4593
4594         mddev->new_level = mddev->level;
4595         mddev->new_chunk = mddev->chunk_size;
4596         mddev->new_layout = mddev->layout;
4597         mddev->delta_disks = 0;
4598
4599         return 0;
4600 }
4601
4602 static int update_size(mddev_t *mddev, sector_t num_sectors)
4603 {
4604         mdk_rdev_t * rdev;
4605         int rv;
4606         struct list_head *tmp;
4607         int fit = (num_sectors == 0);
4608
4609         if (mddev->pers->resize == NULL)
4610                 return -EINVAL;
4611         /* The "num_sectors" is the number of sectors of each device that
4612          * is used.  This can only make sense for arrays with redundancy.
4613          * linear and raid0 always use whatever space is available. We can only
4614          * consider changing this number if no resync or reconstruction is
4615          * happening, and if the new size is acceptable. It must fit before the
4616          * sb_start or, if that is <data_offset, it must fit before the size
4617          * of each device.  If num_sectors is zero, we find the largest size
4618          * that fits.
4619
4620          */
4621         if (mddev->sync_thread)
4622                 return -EBUSY;
4623         if (mddev->bitmap)
4624                 /* Sorry, cannot grow a bitmap yet, just remove it,
4625                  * grow, and re-add.
4626                  */
4627                 return -EBUSY;
4628         rdev_for_each(rdev, tmp, mddev) {
4629                 sector_t avail;
4630                 avail = rdev->size * 2;
4631
4632                 if (fit && (num_sectors == 0 || num_sectors > avail))
4633                         num_sectors = avail;
4634                 if (avail < num_sectors)
4635                         return -ENOSPC;
4636         }
4637         rv = mddev->pers->resize(mddev, num_sectors);
4638         if (!rv) {
4639                 struct block_device *bdev;
4640
4641                 bdev = bdget_disk(mddev->gendisk, 0);
4642                 if (bdev) {
4643                         mutex_lock(&bdev->bd_inode->i_mutex);
4644                         i_size_write(bdev->bd_inode,
4645                                      (loff_t)mddev->array_sectors << 9);
4646                         mutex_unlock(&bdev->bd_inode->i_mutex);
4647                         bdput(bdev);
4648                 }
4649         }
4650         return rv;
4651 }
4652
4653 static int update_raid_disks(mddev_t *mddev, int raid_disks)
4654 {
4655         int rv;
4656         /* change the number of raid disks */
4657         if (mddev->pers->check_reshape == NULL)
4658                 return -EINVAL;
4659         if (raid_disks <= 0 ||
4660             raid_disks >= mddev->max_disks)
4661                 return -EINVAL;
4662         if (mddev->sync_thread || mddev->reshape_position != MaxSector)
4663                 return -EBUSY;
4664         mddev->delta_disks = raid_disks - mddev->raid_disks;
4665
4666         rv = mddev->pers->check_reshape(mddev);
4667         return rv;
4668 }
4669
4670
4671 /*
4672  * update_array_info is used to change the configuration of an
4673  * on-line array.
4674  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
4675  * fields in the info are checked against the array.
4676  * Any differences that cannot be handled will cause an error.
4677  * Normally, only one change can be managed at a time.
4678  */
4679 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
4680 {
4681         int rv = 0;
4682         int cnt = 0;
4683         int state = 0;
4684
4685         /* calculate expected state,ignoring low bits */
4686         if (mddev->bitmap && mddev->bitmap_offset)
4687                 state |= (1 << MD_SB_BITMAP_PRESENT);
4688
4689         if (mddev->major_version != info->major_version ||
4690             mddev->minor_version != info->minor_version ||
4691 /*          mddev->patch_version != info->patch_version || */
4692             mddev->ctime         != info->ctime         ||
4693             mddev->level         != info->level         ||
4694 /*          mddev->layout        != info->layout        || */
4695             !mddev->persistent   != info->not_persistent||
4696             mddev->chunk_size    != info->chunk_size    ||
4697             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
4698             ((state^info->state) & 0xfffffe00)
4699                 )
4700                 return -EINVAL;
4701         /* Check there is only one change */
4702         if (info->size >= 0 && mddev->size != info->size) cnt++;
4703         if (mddev->raid_disks != info->raid_disks) cnt++;
4704         if (mddev->layout != info->layout) cnt++;
4705         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) cnt++;
4706         if (cnt == 0) return 0;
4707         if (cnt > 1) return -EINVAL;
4708
4709         if (mddev->layout != info->layout) {
4710                 /* Change layout
4711                  * we don't need to do anything at the md level, the
4712                  * personality will take care of it all.
4713                  */
4714                 if (mddev->pers->reconfig == NULL)
4715                         return -EINVAL;
4716                 else
4717                         return mddev->pers->reconfig(mddev, info->layout, -1);
4718         }
4719         if (info->size >= 0 && mddev->size != info->size)
4720                 rv = update_size(mddev, (sector_t)info->size * 2);
4721
4722         if (mddev->raid_disks    != info->raid_disks)
4723                 rv = update_raid_disks(mddev, info->raid_disks);
4724
4725         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
4726                 if (mddev->pers->quiesce == NULL)
4727                         return -EINVAL;
4728                 if (mddev->recovery || mddev->sync_thread)
4729                         return -EBUSY;
4730                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
4731                         /* add the bitmap */
4732                         if (mddev->bitmap)
4733                                 return -EEXIST;
4734                         if (mddev->default_bitmap_offset == 0)
4735                                 return -EINVAL;
4736                         mddev->bitmap_offset = mddev->default_bitmap_offset;
4737                         mddev->pers->quiesce(mddev, 1);
4738                         rv = bitmap_create(mddev);
4739                         if (rv)
4740                                 bitmap_destroy(mddev);
4741                         mddev->pers->quiesce(mddev, 0);
4742                 } else {
4743                         /* remove the bitmap */
4744                         if (!mddev->bitmap)
4745                                 return -ENOENT;
4746                         if (mddev->bitmap->file)
4747                                 return -EINVAL;
4748                         mddev->pers->quiesce(mddev, 1);
4749                         bitmap_destroy(mddev);
4750                         mddev->pers->quiesce(mddev, 0);
4751                         mddev->bitmap_offset = 0;
4752                 }
4753         }
4754         md_update_sb(mddev, 1);
4755         return rv;
4756 }
4757
4758 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
4759 {
4760         mdk_rdev_t *rdev;
4761
4762         if (mddev->pers == NULL)
4763                 return -ENODEV;
4764
4765         rdev = find_rdev(mddev, dev);
4766         if (!rdev)
4767                 return -ENODEV;
4768
4769         md_error(mddev, rdev);
4770         return 0;
4771 }
4772
4773 /*
4774  * We have a problem here : there is no easy way to give a CHS
4775  * virtual geometry. We currently pretend that we have a 2 heads
4776  * 4 sectors (with a BIG number of cylinders...). This drives
4777  * dosfs just mad... ;-)
4778  */
4779 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
4780 {
4781         mddev_t *mddev = bdev->bd_disk->private_data;
4782
4783         geo->heads = 2;
4784         geo->sectors = 4;
4785         geo->cylinders = get_capacity(mddev->gendisk) / 8;
4786         return 0;
4787 }
4788
4789 static int md_ioctl(struct inode *inode, struct file *file,
4790                         unsigned int cmd, unsigned long arg)
4791 {
4792         int err = 0;
4793         void __user *argp = (void __user *)arg;
4794         mddev_t *mddev = NULL;
4795
4796         if (!capable(CAP_SYS_ADMIN))
4797                 return -EACCES;
4798
4799         /*
4800          * Commands dealing with the RAID driver but not any
4801          * particular array:
4802          */
4803         switch (cmd)
4804         {
4805                 case RAID_VERSION:
4806                         err = get_version(argp);
4807                         goto done;
4808
4809                 case PRINT_RAID_DEBUG:
4810                         err = 0;
4811                         md_print_devices();
4812                         goto done;
4813
4814 #ifndef MODULE
4815                 case RAID_AUTORUN:
4816                         err = 0;
4817                         autostart_arrays(arg);
4818                         goto done;
4819 #endif
4820                 default:;
4821         }
4822
4823         /*
4824          * Commands creating/starting a new array:
4825          */
4826
4827         mddev = inode->i_bdev->bd_disk->private_data;
4828
4829         if (!mddev) {
4830                 BUG();
4831                 goto abort;
4832         }
4833
4834         err = mddev_lock(mddev);
4835         if (err) {
4836                 printk(KERN_INFO 
4837                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
4838                         err, cmd);
4839                 goto abort;
4840         }
4841
4842         switch (cmd)
4843         {
4844                 case SET_ARRAY_INFO:
4845                         {
4846                                 mdu_array_info_t info;
4847                                 if (!arg)
4848                                         memset(&info, 0, sizeof(info));
4849                                 else if (copy_from_user(&info, argp, sizeof(info))) {
4850                                         err = -EFAULT;
4851                                         goto abort_unlock;
4852                                 }
4853                                 if (mddev->pers) {
4854                                         err = update_array_info(mddev, &info);
4855                                         if (err) {
4856                                                 printk(KERN_WARNING "md: couldn't update"
4857                                                        " array info. %d\n", err);
4858                                                 goto abort_unlock;
4859                                         }
4860                                         goto done_unlock;
4861                                 }
4862                                 if (!list_empty(&mddev->disks)) {
4863                                         printk(KERN_WARNING
4864                                                "md: array %s already has disks!\n",
4865                                                mdname(mddev));
4866                                         err = -EBUSY;
4867                                         goto abort_unlock;
4868                                 }
4869                                 if (mddev->raid_disks) {
4870                                         printk(KERN_WARNING
4871                                                "md: array %s already initialised!\n",
4872                                                mdname(mddev));
4873                                         err = -EBUSY;
4874                                         goto abort_unlock;
4875                                 }
4876                                 err = set_array_info(mddev, &info);
4877                                 if (err) {
4878                                         printk(KERN_WARNING "md: couldn't set"
4879                                                " array info. %d\n", err);
4880                                         goto abort_unlock;
4881                                 }
4882                         }
4883                         goto done_unlock;
4884
4885                 default:;
4886         }
4887
4888         /*
4889          * Commands querying/configuring an existing array:
4890          */
4891         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
4892          * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
4893         if ((!mddev->raid_disks && !mddev->external)
4894             && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
4895             && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
4896             && cmd != GET_BITMAP_FILE) {
4897                 err = -ENODEV;
4898                 goto abort_unlock;
4899         }
4900
4901         /*
4902          * Commands even a read-only array can execute:
4903          */
4904         switch (cmd)
4905         {
4906                 case GET_ARRAY_INFO:
4907                         err = get_array_info(mddev, argp);
4908                         goto done_unlock;
4909
4910                 case GET_BITMAP_FILE:
4911                         err = get_bitmap_file(mddev, argp);
4912                         goto done_unlock;
4913
4914                 case GET_DISK_INFO:
4915                         err = get_disk_info(mddev, argp);
4916                         goto done_unlock;
4917
4918                 case RESTART_ARRAY_RW:
4919                         err = restart_array(mddev);
4920                         goto done_unlock;
4921
4922                 case STOP_ARRAY:
4923                         err = do_md_stop(mddev, 0, 1);
4924                         goto done_unlock;
4925
4926                 case STOP_ARRAY_RO:
4927                         err = do_md_stop(mddev, 1, 1);
4928                         goto done_unlock;
4929
4930         }
4931
4932         /*
4933          * The remaining ioctls are changing the state of the
4934          * superblock, so we do not allow them on read-only arrays.
4935          * However non-MD ioctls (e.g. get-size) will still come through
4936          * here and hit the 'default' below, so only disallow
4937          * 'md' ioctls, and switch to rw mode if started auto-readonly.
4938          */
4939         if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
4940                 if (mddev->ro == 2) {
4941                         mddev->ro = 0;
4942                         sysfs_notify(&mddev->kobj, NULL, "array_state");
4943                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4944                         md_wakeup_thread(mddev->thread);
4945                 } else {
4946                         err = -EROFS;
4947                         goto abort_unlock;
4948                 }
4949         }
4950
4951         switch (cmd)
4952         {
4953                 case ADD_NEW_DISK:
4954                 {
4955                         mdu_disk_info_t info;
4956                         if (copy_from_user(&info, argp, sizeof(info)))
4957                                 err = -EFAULT;
4958                         else
4959                                 err = add_new_disk(mddev, &info);
4960                         goto done_unlock;
4961                 }
4962
4963                 case HOT_REMOVE_DISK:
4964                         err = hot_remove_disk(mddev, new_decode_dev(arg));
4965                         goto done_unlock;
4966
4967                 case HOT_ADD_DISK:
4968                         err = hot_add_disk(mddev, new_decode_dev(arg));
4969                         goto done_unlock;
4970
4971                 case SET_DISK_FAULTY:
4972                         err = set_disk_faulty(mddev, new_decode_dev(arg));
4973                         goto done_unlock;
4974
4975                 case RUN_ARRAY:
4976                         err = do_md_run(mddev);
4977                         goto done_unlock;
4978
4979                 case SET_BITMAP_FILE:
4980                         err = set_bitmap_file(mddev, (int)arg);
4981                         goto done_unlock;
4982
4983                 default:
4984                         err = -EINVAL;
4985                         goto abort_unlock;
4986         }
4987
4988 done_unlock:
4989 abort_unlock:
4990         mddev_unlock(mddev);
4991
4992         return err;
4993 done:
4994         if (err)
4995                 MD_BUG();
4996 abort:
4997         return err;
4998 }
4999
5000 static int md_open(struct inode *inode, struct file *file)
5001 {
5002         /*
5003          * Succeed if we can lock the mddev, which confirms that
5004          * it isn't being stopped right now.
5005          */
5006         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
5007         int err;
5008
5009         if ((err = mutex_lock_interruptible_nested(&mddev->reconfig_mutex, 1)))
5010                 goto out;
5011
5012         err = 0;
5013         mddev_get(mddev);
5014         atomic_inc(&mddev->openers);
5015         mddev_unlock(mddev);
5016
5017         check_disk_change(inode->i_bdev);
5018  out:
5019         return err;
5020 }
5021
5022 static int md_release(struct inode *inode, struct file * file)
5023 {
5024         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
5025
5026         BUG_ON(!mddev);
5027         atomic_dec(&mddev->openers);
5028         mddev_put(mddev);
5029
5030         return 0;
5031 }
5032
5033 static int md_media_changed(struct gendisk *disk)
5034 {
5035         mddev_t *mddev = disk->private_data;
5036
5037         return mddev->changed;
5038 }
5039
5040 static int md_revalidate(struct gendisk *disk)
5041 {
5042         mddev_t *mddev = disk->private_data;
5043
5044         mddev->changed = 0;
5045         return 0;
5046 }
5047 static struct block_device_operations md_fops =
5048 {
5049         .owner          = THIS_MODULE,
5050         .open           = md_open,
5051         .release        = md_release,
5052         .ioctl          = md_ioctl,
5053         .getgeo         = md_getgeo,
5054         .media_changed  = md_media_changed,
5055         .revalidate_disk= md_revalidate,
5056 };
5057
5058 static int md_thread(void * arg)
5059 {
5060         mdk_thread_t *thread = arg;
5061
5062         /*
5063          * md_thread is a 'system-thread', it's priority should be very
5064          * high. We avoid resource deadlocks individually in each
5065          * raid personality. (RAID5 does preallocation) We also use RR and
5066          * the very same RT priority as kswapd, thus we will never get
5067          * into a priority inversion deadlock.
5068          *
5069          * we definitely have to have equal or higher priority than
5070          * bdflush, otherwise bdflush will deadlock if there are too
5071          * many dirty RAID5 blocks.
5072          */
5073
5074         allow_signal(SIGKILL);
5075         while (!kthread_should_stop()) {
5076
5077                 /* We need to wait INTERRUPTIBLE so that
5078                  * we don't add to the load-average.
5079                  * That means we need to be sure no signals are
5080                  * pending
5081                  */
5082                 if (signal_pending(current))
5083                         flush_signals(current);
5084
5085                 wait_event_interruptible_timeout
5086                         (thread->wqueue,
5087                          test_bit(THREAD_WAKEUP, &thread->flags)
5088                          || kthread_should_stop(),
5089                          thread->timeout);
5090
5091                 clear_bit(THREAD_WAKEUP, &thread->flags);
5092
5093                 thread->run(thread->mddev);
5094         }
5095
5096         return 0;
5097 }
5098
5099 void md_wakeup_thread(mdk_thread_t *thread)
5100 {
5101         if (thread) {
5102                 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
5103                 set_bit(THREAD_WAKEUP, &thread->flags);
5104                 wake_up(&thread->wqueue);
5105         }
5106 }
5107
5108 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
5109                                  const char *name)
5110 {
5111         mdk_thread_t *thread;
5112
5113         thread = kzalloc(sizeof(mdk_thread_t), GFP_KERNEL);
5114         if (!thread)
5115                 return NULL;
5116
5117         init_waitqueue_head(&thread->wqueue);
5118
5119         thread->run = run;
5120         thread->mddev = mddev;
5121         thread->timeout = MAX_SCHEDULE_TIMEOUT;
5122         thread->tsk = kthread_run(md_thread, thread, name, mdname(thread->mddev));
5123         if (IS_ERR(thread->tsk)) {
5124                 kfree(thread);
5125                 return NULL;
5126         }
5127         return thread;
5128 }
5129
5130 void md_unregister_thread(mdk_thread_t *thread)
5131 {
5132         dprintk("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
5133
5134         kthread_stop(thread->tsk);
5135         kfree(thread);
5136 }
5137
5138 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
5139 {
5140         if (!mddev) {
5141                 MD_BUG();
5142                 return;
5143         }
5144
5145         if (!rdev || test_bit(Faulty, &rdev->flags))
5146                 return;
5147
5148         if (mddev->external)
5149                 set_bit(Blocked, &rdev->flags);
5150 /*
5151         dprintk("md_error dev:%s, rdev:(%d:%d), (caller: %p,%p,%p,%p).\n",
5152                 mdname(mddev),
5153                 MAJOR(rdev->bdev->bd_dev), MINOR(rdev->bdev->bd_dev),
5154                 __builtin_return_address(0),__builtin_return_address(1),
5155                 __builtin_return_address(2),__builtin_return_address(3));
5156 */
5157         if (!mddev->pers)
5158                 return;
5159         if (!mddev->pers->error_handler)
5160                 return;
5161         mddev->pers->error_handler(mddev,rdev);
5162         if (mddev->degraded)
5163                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5164         set_bit(StateChanged, &rdev->flags);
5165         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5166         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5167         md_wakeup_thread(mddev->thread);
5168         md_new_event_inintr(mddev);
5169 }
5170
5171 /* seq_file implementation /proc/mdstat */
5172
5173 static void status_unused(struct seq_file *seq)
5174 {
5175         int i = 0;
5176         mdk_rdev_t *rdev;
5177         struct list_head *tmp;
5178
5179         seq_printf(seq, "unused devices: ");
5180
5181         rdev_for_each_list(rdev, tmp, pending_raid_disks) {
5182                 char b[BDEVNAME_SIZE];
5183                 i++;
5184                 seq_printf(seq, "%s ",
5185                               bdevname(rdev->bdev,b));
5186         }
5187         if (!i)
5188                 seq_printf(seq, "<none>");
5189
5190         seq_printf(seq, "\n");
5191 }
5192
5193
5194 static void status_resync(struct seq_file *seq, mddev_t * mddev)
5195 {
5196         sector_t max_blocks, resync, res;
5197         unsigned long dt, db, rt;
5198         int scale;
5199         unsigned int per_milli;
5200
5201         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active))/2;
5202
5203         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
5204                 max_blocks = mddev->resync_max_sectors >> 1;
5205         else
5206                 max_blocks = mddev->size;
5207
5208         /*
5209          * Should not happen.
5210          */
5211         if (!max_blocks) {
5212                 MD_BUG();
5213                 return;
5214         }
5215         /* Pick 'scale' such that (resync>>scale)*1000 will fit
5216          * in a sector_t, and (max_blocks>>scale) will fit in a
5217          * u32, as those are the requirements for sector_div.
5218          * Thus 'scale' must be at least 10
5219          */
5220         scale = 10;
5221         if (sizeof(sector_t) > sizeof(unsigned long)) {
5222                 while ( max_blocks/2 > (1ULL<<(scale+32)))
5223                         scale++;
5224         }
5225         res = (resync>>scale)*1000;
5226         sector_div(res, (u32)((max_blocks>>scale)+1));
5227
5228         per_milli = res;
5229         {
5230                 int i, x = per_milli/50, y = 20-x;
5231                 seq_printf(seq, "[");
5232                 for (i = 0; i < x; i++)
5233                         seq_printf(seq, "=");
5234                 seq_printf(seq, ">");
5235                 for (i = 0; i < y; i++)
5236                         seq_printf(seq, ".");
5237                 seq_printf(seq, "] ");
5238         }
5239         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
5240                    (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
5241                     "reshape" :
5242                     (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
5243                      "check" :
5244                      (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
5245                       "resync" : "recovery"))),
5246                    per_milli/10, per_milli % 10,
5247                    (unsigned long long) resync,
5248                    (unsigned long long) max_blocks);
5249
5250         /*
5251          * We do not want to overflow, so the order of operands and
5252          * the * 100 / 100 trick are important. We do a +1 to be
5253          * safe against division by zero. We only estimate anyway.
5254          *
5255          * dt: time from mark until now
5256          * db: blocks written from mark until now
5257          * rt: remaining time
5258          */
5259         dt = ((jiffies - mddev->resync_mark) / HZ);
5260         if (!dt) dt++;
5261         db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
5262                 - mddev->resync_mark_cnt;
5263         rt = (dt * ((unsigned long)(max_blocks-resync) / (db/2/100+1)))/100;
5264
5265         seq_printf(seq, " finish=%lu.%lumin", rt / 60, (rt % 60)/6);
5266
5267         seq_printf(seq, " speed=%ldK/sec", db/2/dt);
5268 }
5269
5270 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
5271 {
5272         struct list_head *tmp;
5273         loff_t l = *pos;
5274         mddev_t *mddev;
5275
5276         if (l >= 0x10000)
5277                 return NULL;
5278         if (!l--)
5279                 /* header */
5280                 return (void*)1;
5281
5282         spin_lock(&all_mddevs_lock);
5283         list_for_each(tmp,&all_mddevs)
5284                 if (!l--) {
5285                         mddev = list_entry(tmp, mddev_t, all_mddevs);
5286                         mddev_get(mddev);
5287                         spin_unlock(&all_mddevs_lock);
5288                         return mddev;
5289                 }
5290         spin_unlock(&all_mddevs_lock);
5291         if (!l--)
5292                 return (void*)2;/* tail */
5293         return NULL;
5294 }
5295
5296 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
5297 {
5298         struct list_head *tmp;
5299         mddev_t *next_mddev, *mddev = v;
5300         
5301         ++*pos;
5302         if (v == (void*)2)
5303                 return NULL;
5304
5305         spin_lock(&all_mddevs_lock);
5306         if (v == (void*)1)
5307                 tmp = all_mddevs.next;
5308         else
5309                 tmp = mddev->all_mddevs.next;
5310         if (tmp != &all_mddevs)
5311                 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
5312         else {
5313                 next_mddev = (void*)2;
5314                 *pos = 0x10000;
5315         }               
5316         spin_unlock(&all_mddevs_lock);
5317
5318         if (v != (void*)1)
5319                 mddev_put(mddev);
5320         return next_mddev;
5321
5322 }
5323
5324 static void md_seq_stop(struct seq_file *seq, void *v)
5325 {
5326         mddev_t *mddev = v;
5327
5328         if (mddev && v != (void*)1 && v != (void*)2)
5329                 mddev_put(mddev);
5330 }
5331
5332 struct mdstat_info {
5333         int event;
5334 };
5335
5336 static int md_seq_show(struct seq_file *seq, void *v)
5337 {
5338         mddev_t *mddev = v;
5339         sector_t size;
5340         struct list_head *tmp2;
5341         mdk_rdev_t *rdev;
5342         struct mdstat_info *mi = seq->private;
5343         struct bitmap *bitmap;
5344
5345         if (v == (void*)1) {
5346                 struct mdk_personality *pers;
5347                 seq_printf(seq, "Personalities : ");
5348                 spin_lock(&pers_lock);
5349                 list_for_each_entry(pers, &pers_list, list)
5350                         seq_printf(seq, "[%s] ", pers->name);
5351
5352                 spin_unlock(&pers_lock);
5353                 seq_printf(seq, "\n");
5354                 mi->event = atomic_read(&md_event_count);
5355                 return 0;
5356         }
5357         if (v == (void*)2) {
5358                 status_unused(seq);
5359                 return 0;
5360         }
5361
5362         if (mddev_lock(mddev) < 0)
5363                 return -EINTR;
5364
5365         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
5366                 seq_printf(seq, "%s : %sactive", mdname(mddev),
5367                                                 mddev->pers ? "" : "in");
5368                 if (mddev->pers) {
5369                         if (mddev->ro==1)
5370                                 seq_printf(seq, " (read-only)");
5371                         if (mddev->ro==2)
5372                                 seq_printf(seq, " (auto-read-only)");
5373                         seq_printf(seq, " %s", mddev->pers->name);
5374                 }
5375
5376                 size = 0;
5377                 rdev_for_each(rdev, tmp2, mddev) {
5378                         char b[BDEVNAME_SIZE];
5379                         seq_printf(seq, " %s[%d]",
5380                                 bdevname(rdev->bdev,b), rdev->desc_nr);
5381                         if (test_bit(WriteMostly, &rdev->flags))
5382                                 seq_printf(seq, "(W)");
5383                         if (test_bit(Faulty, &rdev->flags)) {
5384                                 seq_printf(seq, "(F)");
5385                                 continue;
5386                         } else if (rdev->raid_disk < 0)
5387                                 seq_printf(seq, "(S)"); /* spare */
5388                         size += rdev->size;
5389                 }
5390
5391                 if (!list_empty(&mddev->disks)) {
5392                         if (mddev->pers)
5393                                 seq_printf(seq, "\n      %llu blocks",
5394                                            (unsigned long long)
5395                                            mddev->array_sectors / 2);
5396                         else
5397                                 seq_printf(seq, "\n      %llu blocks",
5398                                            (unsigned long long)size);
5399                 }
5400                 if (mddev->persistent) {
5401                         if (mddev->major_version != 0 ||
5402                             mddev->minor_version != 90) {
5403                                 seq_printf(seq," super %d.%d",
5404                                            mddev->major_version,
5405                                            mddev->minor_version);
5406                         }
5407                 } else if (mddev->external)
5408                         seq_printf(seq, " super external:%s",
5409                                    mddev->metadata_type);
5410                 else
5411                         seq_printf(seq, " super non-persistent");
5412
5413                 if (mddev->pers) {
5414                         mddev->pers->status(seq, mddev);
5415                         seq_printf(seq, "\n      ");
5416                         if (mddev->pers->sync_request) {
5417                                 if (mddev->curr_resync > 2) {
5418                                         status_resync(seq, mddev);
5419                                         seq_printf(seq, "\n      ");
5420                                 } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
5421                                         seq_printf(seq, "\tresync=DELAYED\n      ");
5422                                 else if (mddev->recovery_cp < MaxSector)
5423                                         seq_printf(seq, "\tresync=PENDING\n      ");
5424                         }
5425                 } else
5426                         seq_printf(seq, "\n       ");
5427
5428                 if ((bitmap = mddev->bitmap)) {
5429                         unsigned long chunk_kb;
5430                         unsigned long flags;
5431                         spin_lock_irqsave(&bitmap->lock, flags);
5432                         chunk_kb = bitmap->chunksize >> 10;
5433                         seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
5434                                 "%lu%s chunk",
5435                                 bitmap->pages - bitmap->missing_pages,
5436                                 bitmap->pages,
5437                                 (bitmap->pages - bitmap->missing_pages)
5438                                         << (PAGE_SHIFT - 10),
5439                                 chunk_kb ? chunk_kb : bitmap->chunksize,
5440                                 chunk_kb ? "KB" : "B");
5441                         if (bitmap->file) {
5442                                 seq_printf(seq, ", file: ");
5443                                 seq_path(seq, &bitmap->file->f_path, " \t\n");
5444                         }
5445
5446                         seq_printf(seq, "\n");
5447                         spin_unlock_irqrestore(&bitmap->lock, flags);
5448                 }
5449
5450                 seq_printf(seq, "\n");
5451         }
5452         mddev_unlock(mddev);
5453         
5454         return 0;
5455 }
5456
5457 static struct seq_operations md_seq_ops = {
5458         .start  = md_seq_start,
5459         .next   = md_seq_next,
5460         .stop   = md_seq_stop,
5461         .show   = md_seq_show,
5462 };
5463
5464 static int md_seq_open(struct inode *inode, struct file *file)
5465 {
5466         int error;
5467         struct mdstat_info *mi = kmalloc(sizeof(*mi), GFP_KERNEL);
5468         if (mi == NULL)
5469                 return -ENOMEM;
5470
5471         error = seq_open(file, &md_seq_ops);
5472         if (error)
5473                 kfree(mi);
5474         else {
5475                 struct seq_file *p = file->private_data;
5476                 p->private = mi;
5477                 mi->event = atomic_read(&md_event_count);
5478         }
5479         return error;
5480 }
5481
5482 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
5483 {
5484         struct seq_file *m = filp->private_data;
5485         struct mdstat_info *mi = m->private;
5486         int mask;
5487
5488         poll_wait(filp, &md_event_waiters, wait);
5489
5490         /* always allow read */
5491         mask = POLLIN | POLLRDNORM;
5492
5493         if (mi->event != atomic_read(&md_event_count))
5494                 mask |= POLLERR | POLLPRI;
5495         return mask;
5496 }
5497
5498 static const struct file_operations md_seq_fops = {
5499         .owner          = THIS_MODULE,
5500         .open           = md_seq_open,
5501         .read           = seq_read,
5502         .llseek         = seq_lseek,
5503         .release        = seq_release_private,
5504         .poll           = mdstat_poll,
5505 };
5506
5507 int register_md_personality(struct mdk_personality *p)
5508 {
5509         spin_lock(&pers_lock);
5510         list_add_tail(&p->list, &pers_list);
5511         printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
5512         spin_unlock(&pers_lock);
5513         return 0;
5514 }
5515
5516 int unregister_md_personality(struct mdk_personality *p)
5517 {
5518         printk(KERN_INFO "md: %s personality unregistered\n", p->name);
5519         spin_lock(&pers_lock);
5520         list_del_init(&p->list);
5521         spin_unlock(&pers_lock);
5522         return 0;
5523 }
5524
5525 static int is_mddev_idle(mddev_t *mddev)
5526 {
5527         mdk_rdev_t * rdev;
5528         int idle;
5529         long curr_events;
5530
5531         idle = 1;
5532         rcu_read_lock();
5533         rdev_for_each_rcu(rdev, mddev) {
5534                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
5535                 curr_events = part_stat_read(&disk->part0, sectors[0]) +
5536                                 part_stat_read(&disk->part0, sectors[1]) -
5537                                 atomic_read(&disk->sync_io);
5538                 /* sync IO will cause sync_io to increase before the disk_stats
5539                  * as sync_io is counted when a request starts, and
5540                  * disk_stats is counted when it completes.
5541                  * So resync activity will cause curr_events to be smaller than
5542                  * when there was no such activity.
5543                  * non-sync IO will cause disk_stat to increase without
5544                  * increasing sync_io so curr_events will (eventually)
5545                  * be larger than it was before.  Once it becomes
5546                  * substantially larger, the test below will cause
5547                  * the array to appear non-idle, and resync will slow
5548                  * down.
5549                  * If there is a lot of outstanding resync activity when
5550                  * we set last_event to curr_events, then all that activity
5551                  * completing might cause the array to appear non-idle
5552                  * and resync will be slowed down even though there might
5553                  * not have been non-resync activity.  This will only
5554                  * happen once though.  'last_events' will soon reflect
5555                  * the state where there is little or no outstanding
5556                  * resync requests, and further resync activity will
5557                  * always make curr_events less than last_events.
5558                  *
5559                  */
5560                 if (curr_events - rdev->last_events > 4096) {
5561                         rdev->last_events = curr_events;
5562                         idle = 0;
5563                 }
5564         }
5565         rcu_read_unlock();
5566         return idle;
5567 }
5568
5569 void md_done_sync(mddev_t *mddev, int blocks, int ok)
5570 {
5571         /* another "blocks" (512byte) blocks have been synced */
5572         atomic_sub(blocks, &mddev->recovery_active);
5573         wake_up(&mddev->recovery_wait);
5574         if (!ok) {
5575                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5576                 md_wakeup_thread(mddev->thread);
5577                 // stop recovery, signal do_sync ....
5578         }
5579 }
5580
5581
5582 /* md_write_start(mddev, bi)
5583  * If we need to update some array metadata (e.g. 'active' flag
5584  * in superblock) before writing, schedule a superblock update
5585  * and wait for it to complete.
5586  */
5587 void md_write_start(mddev_t *mddev, struct bio *bi)
5588 {
5589         int did_change = 0;
5590         if (bio_data_dir(bi) != WRITE)
5591                 return;
5592
5593         BUG_ON(mddev->ro == 1);
5594         if (mddev->ro == 2) {
5595                 /* need to switch to read/write */
5596                 mddev->ro = 0;
5597                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5598                 md_wakeup_thread(mddev->thread);
5599                 md_wakeup_thread(mddev->sync_thread);
5600                 did_change = 1;
5601         }
5602         atomic_inc(&mddev->writes_pending);
5603         if (mddev->safemode == 1)
5604                 mddev->safemode = 0;
5605         if (mddev->in_sync) {
5606                 spin_lock_irq(&mddev->write_lock);
5607                 if (mddev->in_sync) {
5608                         mddev->in_sync = 0;
5609                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
5610                         md_wakeup_thread(mddev->thread);
5611                         did_change = 1;
5612                 }
5613                 spin_unlock_irq(&mddev->write_lock);
5614         }
5615         if (did_change)
5616                 sysfs_notify(&mddev->kobj, NULL, "array_state");
5617         wait_event(mddev->sb_wait,
5618                    !test_bit(MD_CHANGE_CLEAN, &mddev->flags) &&
5619                    !test_bit(MD_CHANGE_PENDING, &mddev->flags));
5620 }
5621
5622 void md_write_end(mddev_t *mddev)
5623 {
5624         if (atomic_dec_and_test(&mddev->writes_pending)) {
5625                 if (mddev->safemode == 2)
5626                         md_wakeup_thread(mddev->thread);
5627                 else if (mddev->safemode_delay)
5628                         mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
5629         }
5630 }
5631
5632 /* md_allow_write(mddev)
5633  * Calling this ensures that the array is marked 'active' so that writes
5634  * may proceed without blocking.  It is important to call this before
5635  * attempting a GFP_KERNEL allocation while holding the mddev lock.
5636  * Must be called with mddev_lock held.
5637  *
5638  * In the ->external case MD_CHANGE_CLEAN can not be cleared until mddev->lock
5639  * is dropped, so return -EAGAIN after notifying userspace.
5640  */
5641 int md_allow_write(mddev_t *mddev)
5642 {
5643         if (!mddev->pers)
5644                 return 0;
5645         if (mddev->ro)
5646                 return 0;
5647         if (!mddev->pers->sync_request)
5648                 return 0;
5649
5650         spin_lock_irq(&mddev->write_lock);
5651         if (mddev->in_sync) {
5652                 mddev->in_sync = 0;
5653                 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
5654                 if (mddev->safemode_delay &&
5655                     mddev->safemode == 0)
5656                         mddev->safemode = 1;
5657                 spin_unlock_irq(&mddev->write_lock);
5658                 md_update_sb(mddev, 0);
5659                 sysfs_notify(&mddev->kobj, NULL, "array_state");
5660         } else
5661                 spin_unlock_irq(&mddev->write_lock);
5662
5663         if (test_bit(MD_CHANGE_CLEAN, &mddev->flags))
5664                 return -EAGAIN;
5665         else
5666                 return 0;
5667 }
5668 EXPORT_SYMBOL_GPL(md_allow_write);
5669
5670 #define SYNC_MARKS      10
5671 #define SYNC_MARK_STEP  (3*HZ)
5672 void md_do_sync(mddev_t *mddev)
5673 {
5674         mddev_t *mddev2;
5675         unsigned int currspeed = 0,
5676                  window;
5677         sector_t max_sectors,j, io_sectors;
5678         unsigned long mark[SYNC_MARKS];
5679         sector_t mark_cnt[SYNC_MARKS];
5680         int last_mark,m;
5681         struct list_head *tmp;
5682         sector_t last_check;
5683         int skipped = 0;
5684         struct list_head *rtmp;
5685         mdk_rdev_t *rdev;
5686         char *desc;
5687
5688         /* just incase thread restarts... */
5689         if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
5690                 return;
5691         if (mddev->ro) /* never try to sync a read-only array */
5692                 return;
5693
5694         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5695                 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
5696                         desc = "data-check";
5697                 else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
5698                         desc = "requested-resync";
5699                 else
5700                         desc = "resync";
5701         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5702                 desc = "reshape";
5703         else
5704                 desc = "recovery";
5705
5706         /* we overload curr_resync somewhat here.
5707          * 0 == not engaged in resync at all
5708          * 2 == checking that there is no conflict with another sync
5709          * 1 == like 2, but have yielded to allow conflicting resync to
5710          *              commense
5711          * other == active in resync - this many blocks
5712          *
5713          * Before starting a resync we must have set curr_resync to
5714          * 2, and then checked that every "conflicting" array has curr_resync
5715          * less than ours.  When we find one that is the same or higher
5716          * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
5717          * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
5718          * This will mean we have to start checking from the beginning again.
5719          *
5720          */
5721
5722         do {
5723                 mddev->curr_resync = 2;
5724
5725         try_again:
5726                 if (kthread_should_stop()) {
5727                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5728                         goto skip;
5729                 }
5730                 for_each_mddev(mddev2, tmp) {
5731                         if (mddev2 == mddev)
5732                                 continue;
5733                         if (!mddev->parallel_resync
5734                         &&  mddev2->curr_resync
5735                         &&  match_mddev_units(mddev, mddev2)) {
5736                                 DEFINE_WAIT(wq);
5737                                 if (mddev < mddev2 && mddev->curr_resync == 2) {
5738                                         /* arbitrarily yield */
5739                                         mddev->curr_resync = 1;
5740                                         wake_up(&resync_wait);
5741                                 }
5742                                 if (mddev > mddev2 && mddev->curr_resync == 1)
5743                                         /* no need to wait here, we can wait the next
5744                                          * time 'round when curr_resync == 2
5745                                          */
5746                                         continue;
5747                                 /* We need to wait 'interruptible' so as not to
5748                                  * contribute to the load average, and not to
5749                                  * be caught by 'softlockup'
5750                                  */
5751                                 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
5752                                 if (!kthread_should_stop() &&
5753                                     mddev2->curr_resync >= mddev->curr_resync) {
5754                                         printk(KERN_INFO "md: delaying %s of %s"
5755                                                " until %s has finished (they"
5756                                                " share one or more physical units)\n",
5757                                                desc, mdname(mddev), mdname(mddev2));
5758                                         mddev_put(mddev2);
5759                                         if (signal_pending(current))
5760                                                 flush_signals(current);
5761                                         schedule();
5762                                         finish_wait(&resync_wait, &wq);
5763                                         goto try_again;
5764                                 }
5765                                 finish_wait(&resync_wait, &wq);
5766                         }
5767                 }
5768         } while (mddev->curr_resync < 2);
5769
5770         j = 0;
5771         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5772                 /* resync follows the size requested by the personality,
5773                  * which defaults to physical size, but can be virtual size
5774                  */
5775                 max_sectors = mddev->resync_max_sectors;
5776                 mddev->resync_mismatches = 0;
5777                 /* we don't use the checkpoint if there's a bitmap */
5778                 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
5779                         j = mddev->resync_min;
5780                 else if (!mddev->bitmap)
5781                         j = mddev->recovery_cp;
5782
5783         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5784                 max_sectors = mddev->size << 1;
5785         else {
5786                 /* recovery follows the physical size of devices */
5787                 max_sectors = mddev->size << 1;
5788                 j = MaxSector;
5789                 rdev_for_each(rdev, rtmp, mddev)
5790                         if (rdev->raid_disk >= 0 &&
5791                             !test_bit(Faulty, &rdev->flags) &&
5792                             !test_bit(In_sync, &rdev->flags) &&
5793                             rdev->recovery_offset < j)
5794                                 j = rdev->recovery_offset;
5795         }
5796
5797         printk(KERN_INFO "md: %s of RAID array %s\n", desc, mdname(mddev));
5798         printk(KERN_INFO "md: minimum _guaranteed_  speed:"
5799                 " %d KB/sec/disk.\n", speed_min(mddev));
5800         printk(KERN_INFO "md: using maximum available idle IO bandwidth "
5801                "(but not more than %d KB/sec) for %s.\n",
5802                speed_max(mddev), desc);
5803
5804         is_mddev_idle(mddev); /* this also initializes IO event counters */
5805
5806         io_sectors = 0;
5807         for (m = 0; m < SYNC_MARKS; m++) {
5808                 mark[m] = jiffies;
5809                 mark_cnt[m] = io_sectors;
5810         }
5811         last_mark = 0;
5812         mddev->resync_mark = mark[last_mark];
5813         mddev->resync_mark_cnt = mark_cnt[last_mark];
5814
5815         /*
5816          * Tune reconstruction:
5817          */
5818         window = 32*(PAGE_SIZE/512);
5819         printk(KERN_INFO "md: using %dk window, over a total of %llu blocks.\n",
5820                 window/2,(unsigned long long) max_sectors/2);
5821
5822         atomic_set(&mddev->recovery_active, 0);
5823         last_check = 0;
5824
5825         if (j>2) {
5826                 printk(KERN_INFO 
5827                        "md: resuming %s of %s from checkpoint.\n",
5828                        desc, mdname(mddev));
5829                 mddev->curr_resync = j;
5830         }
5831
5832         while (j < max_sectors) {
5833                 sector_t sectors;
5834
5835                 skipped = 0;
5836                 if (j >= mddev->resync_max) {
5837                         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5838                         wait_event(mddev->recovery_wait,
5839                                    mddev->resync_max > j
5840                                    || kthread_should_stop());
5841                 }
5842                 if (kthread_should_stop())
5843                         goto interrupted;
5844                 sectors = mddev->pers->sync_request(mddev, j, &skipped,
5845                                                   currspeed < speed_min(mddev));
5846                 if (sectors == 0) {
5847                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5848                         goto out;
5849                 }
5850
5851                 if (!skipped) { /* actual IO requested */
5852                         io_sectors += sectors;
5853                         atomic_add(sectors, &mddev->recovery_active);
5854                 }
5855
5856                 j += sectors;
5857                 if (j>1) mddev->curr_resync = j;
5858                 mddev->curr_mark_cnt = io_sectors;
5859                 if (last_check == 0)
5860                         /* this is the earliers that rebuilt will be
5861                          * visible in /proc/mdstat
5862                          */