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