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