md: 'array_size' sysfs attribute
[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         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
2892 }
2893
2894 static ssize_t
2895 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
2896 {
2897         char *e;
2898         unsigned long long n = simple_strtoull(buf, &e, 10);
2899
2900         if (mddev->pers)
2901                 return -EBUSY;
2902         if (!*buf || (*e && *e != '\n'))
2903                 return -EINVAL;
2904
2905         mddev->recovery_cp = n;
2906         return len;
2907 }
2908 static struct md_sysfs_entry md_resync_start =
2909 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
2910
2911 /*
2912  * The array state can be:
2913  *
2914  * clear
2915  *     No devices, no size, no level
2916  *     Equivalent to STOP_ARRAY ioctl
2917  * inactive
2918  *     May have some settings, but array is not active
2919  *        all IO results in error
2920  *     When written, doesn't tear down array, but just stops it
2921  * suspended (not supported yet)
2922  *     All IO requests will block. The array can be reconfigured.
2923  *     Writing this, if accepted, will block until array is quiescent
2924  * readonly
2925  *     no resync can happen.  no superblocks get written.
2926  *     write requests fail
2927  * read-auto
2928  *     like readonly, but behaves like 'clean' on a write request.
2929  *
2930  * clean - no pending writes, but otherwise active.
2931  *     When written to inactive array, starts without resync
2932  *     If a write request arrives then
2933  *       if metadata is known, mark 'dirty' and switch to 'active'.
2934  *       if not known, block and switch to write-pending
2935  *     If written to an active array that has pending writes, then fails.
2936  * active
2937  *     fully active: IO and resync can be happening.
2938  *     When written to inactive array, starts with resync
2939  *
2940  * write-pending
2941  *     clean, but writes are blocked waiting for 'active' to be written.
2942  *
2943  * active-idle
2944  *     like active, but no writes have been seen for a while (100msec).
2945  *
2946  */
2947 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
2948                    write_pending, active_idle, bad_word};
2949 static char *array_states[] = {
2950         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
2951         "write-pending", "active-idle", NULL };
2952
2953 static int match_word(const char *word, char **list)
2954 {
2955         int n;
2956         for (n=0; list[n]; n++)
2957                 if (cmd_match(word, list[n]))
2958                         break;
2959         return n;
2960 }
2961
2962 static ssize_t
2963 array_state_show(mddev_t *mddev, char *page)
2964 {
2965         enum array_state st = inactive;
2966
2967         if (mddev->pers)
2968                 switch(mddev->ro) {
2969                 case 1:
2970                         st = readonly;
2971                         break;
2972                 case 2:
2973                         st = read_auto;
2974                         break;
2975                 case 0:
2976                         if (mddev->in_sync)
2977                                 st = clean;
2978                         else if (test_bit(MD_CHANGE_CLEAN, &mddev->flags))
2979                                 st = write_pending;
2980                         else if (mddev->safemode)
2981                                 st = active_idle;
2982                         else
2983                                 st = active;
2984                 }
2985         else {
2986                 if (list_empty(&mddev->disks) &&
2987                     mddev->raid_disks == 0 &&
2988                     mddev->dev_sectors == 0)
2989                         st = clear;
2990                 else
2991                         st = inactive;
2992         }
2993         return sprintf(page, "%s\n", array_states[st]);
2994 }
2995
2996 static int do_md_stop(mddev_t * mddev, int ro, int is_open);
2997 static int do_md_run(mddev_t * mddev);
2998 static int restart_array(mddev_t *mddev);
2999
3000 static ssize_t
3001 array_state_store(mddev_t *mddev, const char *buf, size_t len)
3002 {
3003         int err = -EINVAL;
3004         enum array_state st = match_word(buf, array_states);
3005         switch(st) {
3006         case bad_word:
3007                 break;
3008         case clear:
3009                 /* stopping an active array */
3010                 if (atomic_read(&mddev->openers) > 0)
3011                         return -EBUSY;
3012                 err = do_md_stop(mddev, 0, 0);
3013                 break;
3014         case inactive:
3015                 /* stopping an active array */
3016                 if (mddev->pers) {
3017                         if (atomic_read(&mddev->openers) > 0)
3018                                 return -EBUSY;
3019                         err = do_md_stop(mddev, 2, 0);
3020                 } else
3021                         err = 0; /* already inactive */
3022                 break;
3023         case suspended:
3024                 break; /* not supported yet */
3025         case readonly:
3026                 if (mddev->pers)
3027                         err = do_md_stop(mddev, 1, 0);
3028                 else {
3029                         mddev->ro = 1;
3030                         set_disk_ro(mddev->gendisk, 1);
3031                         err = do_md_run(mddev);
3032                 }
3033                 break;
3034         case read_auto:
3035                 if (mddev->pers) {
3036                         if (mddev->ro == 0)
3037                                 err = do_md_stop(mddev, 1, 0);
3038                         else if (mddev->ro == 1)
3039                                 err = restart_array(mddev);
3040                         if (err == 0) {
3041                                 mddev->ro = 2;
3042                                 set_disk_ro(mddev->gendisk, 0);
3043                         }
3044                 } else {
3045                         mddev->ro = 2;
3046                         err = do_md_run(mddev);
3047                 }
3048                 break;
3049         case clean:
3050                 if (mddev->pers) {
3051                         restart_array(mddev);
3052                         spin_lock_irq(&mddev->write_lock);
3053                         if (atomic_read(&mddev->writes_pending) == 0) {
3054                                 if (mddev->in_sync == 0) {
3055                                         mddev->in_sync = 1;
3056                                         if (mddev->safemode == 1)
3057                                                 mddev->safemode = 0;
3058                                         if (mddev->persistent)
3059                                                 set_bit(MD_CHANGE_CLEAN,
3060                                                         &mddev->flags);
3061                                 }
3062                                 err = 0;
3063                         } else
3064                                 err = -EBUSY;
3065                         spin_unlock_irq(&mddev->write_lock);
3066                 } else {
3067                         mddev->ro = 0;
3068                         mddev->recovery_cp = MaxSector;
3069                         err = do_md_run(mddev);
3070                 }
3071                 break;
3072         case active:
3073                 if (mddev->pers) {
3074                         restart_array(mddev);
3075                         if (mddev->external)
3076                                 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
3077                         wake_up(&mddev->sb_wait);
3078                         err = 0;
3079                 } else {
3080                         mddev->ro = 0;
3081                         set_disk_ro(mddev->gendisk, 0);
3082                         err = do_md_run(mddev);
3083                 }
3084                 break;
3085         case write_pending:
3086         case active_idle:
3087                 /* these cannot be set */
3088                 break;
3089         }
3090         if (err)
3091                 return err;
3092         else {
3093                 sysfs_notify_dirent(mddev->sysfs_state);
3094                 return len;
3095         }
3096 }
3097 static struct md_sysfs_entry md_array_state =
3098 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3099
3100 static ssize_t
3101 null_show(mddev_t *mddev, char *page)
3102 {
3103         return -EINVAL;
3104 }
3105
3106 static ssize_t
3107 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
3108 {
3109         /* buf must be %d:%d\n? giving major and minor numbers */
3110         /* The new device is added to the array.
3111          * If the array has a persistent superblock, we read the
3112          * superblock to initialise info and check validity.
3113          * Otherwise, only checking done is that in bind_rdev_to_array,
3114          * which mainly checks size.
3115          */
3116         char *e;
3117         int major = simple_strtoul(buf, &e, 10);
3118         int minor;
3119         dev_t dev;
3120         mdk_rdev_t *rdev;
3121         int err;
3122
3123         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
3124                 return -EINVAL;
3125         minor = simple_strtoul(e+1, &e, 10);
3126         if (*e && *e != '\n')
3127                 return -EINVAL;
3128         dev = MKDEV(major, minor);
3129         if (major != MAJOR(dev) ||
3130             minor != MINOR(dev))
3131                 return -EOVERFLOW;
3132
3133
3134         if (mddev->persistent) {
3135                 rdev = md_import_device(dev, mddev->major_version,
3136                                         mddev->minor_version);
3137                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
3138                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
3139                                                        mdk_rdev_t, same_set);
3140                         err = super_types[mddev->major_version]
3141                                 .load_super(rdev, rdev0, mddev->minor_version);
3142                         if (err < 0)
3143                                 goto out;
3144                 }
3145         } else if (mddev->external)
3146                 rdev = md_import_device(dev, -2, -1);
3147         else
3148                 rdev = md_import_device(dev, -1, -1);
3149
3150         if (IS_ERR(rdev))
3151                 return PTR_ERR(rdev);
3152         err = bind_rdev_to_array(rdev, mddev);
3153  out:
3154         if (err)
3155                 export_rdev(rdev);
3156         return err ? err : len;
3157 }
3158
3159 static struct md_sysfs_entry md_new_device =
3160 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
3161
3162 static ssize_t
3163 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
3164 {
3165         char *end;
3166         unsigned long chunk, end_chunk;
3167
3168         if (!mddev->bitmap)
3169                 goto out;
3170         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
3171         while (*buf) {
3172                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
3173                 if (buf == end) break;
3174                 if (*end == '-') { /* range */
3175                         buf = end + 1;
3176                         end_chunk = simple_strtoul(buf, &end, 0);
3177                         if (buf == end) break;
3178                 }
3179                 if (*end && !isspace(*end)) break;
3180                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
3181                 buf = end;
3182                 while (isspace(*buf)) buf++;
3183         }
3184         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
3185 out:
3186         return len;
3187 }
3188
3189 static struct md_sysfs_entry md_bitmap =
3190 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
3191
3192 static ssize_t
3193 size_show(mddev_t *mddev, char *page)
3194 {
3195         return sprintf(page, "%llu\n",
3196                 (unsigned long long)mddev->dev_sectors / 2);
3197 }
3198
3199 static int update_size(mddev_t *mddev, sector_t num_sectors);
3200
3201 static ssize_t
3202 size_store(mddev_t *mddev, const char *buf, size_t len)
3203 {
3204         /* If array is inactive, we can reduce the component size, but
3205          * not increase it (except from 0).
3206          * If array is active, we can try an on-line resize
3207          */
3208         sector_t sectors;
3209         int err = strict_blocks_to_sectors(buf, &sectors);
3210
3211         if (err < 0)
3212                 return err;
3213         if (mddev->pers) {
3214                 err = update_size(mddev, sectors);
3215                 md_update_sb(mddev, 1);
3216         } else {
3217                 if (mddev->dev_sectors == 0 ||
3218                     mddev->dev_sectors > sectors)
3219                         mddev->dev_sectors = sectors;
3220                 else
3221                         err = -ENOSPC;
3222         }
3223         return err ? err : len;
3224 }
3225
3226 static struct md_sysfs_entry md_size =
3227 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
3228
3229
3230 /* Metdata version.
3231  * This is one of
3232  *   'none' for arrays with no metadata (good luck...)
3233  *   'external' for arrays with externally managed metadata,
3234  * or N.M for internally known formats
3235  */
3236 static ssize_t
3237 metadata_show(mddev_t *mddev, char *page)
3238 {
3239         if (mddev->persistent)
3240                 return sprintf(page, "%d.%d\n",
3241                                mddev->major_version, mddev->minor_version);
3242         else if (mddev->external)
3243                 return sprintf(page, "external:%s\n", mddev->metadata_type);
3244         else
3245                 return sprintf(page, "none\n");
3246 }
3247
3248 static ssize_t
3249 metadata_store(mddev_t *mddev, const char *buf, size_t len)
3250 {
3251         int major, minor;
3252         char *e;
3253         /* Changing the details of 'external' metadata is
3254          * always permitted.  Otherwise there must be
3255          * no devices attached to the array.
3256          */
3257         if (mddev->external && strncmp(buf, "external:", 9) == 0)
3258                 ;
3259         else if (!list_empty(&mddev->disks))
3260                 return -EBUSY;
3261
3262         if (cmd_match(buf, "none")) {
3263                 mddev->persistent = 0;
3264                 mddev->external = 0;
3265                 mddev->major_version = 0;
3266                 mddev->minor_version = 90;
3267                 return len;
3268         }
3269         if (strncmp(buf, "external:", 9) == 0) {
3270                 size_t namelen = len-9;
3271                 if (namelen >= sizeof(mddev->metadata_type))
3272                         namelen = sizeof(mddev->metadata_type)-1;
3273                 strncpy(mddev->metadata_type, buf+9, namelen);
3274                 mddev->metadata_type[namelen] = 0;
3275                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
3276                         mddev->metadata_type[--namelen] = 0;
3277                 mddev->persistent = 0;
3278                 mddev->external = 1;
3279                 mddev->major_version = 0;
3280                 mddev->minor_version = 90;
3281                 return len;
3282         }
3283         major = simple_strtoul(buf, &e, 10);
3284         if (e==buf || *e != '.')
3285                 return -EINVAL;
3286         buf = e+1;
3287         minor = simple_strtoul(buf, &e, 10);
3288         if (e==buf || (*e && *e != '\n') )
3289                 return -EINVAL;
3290         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
3291                 return -ENOENT;
3292         mddev->major_version = major;
3293         mddev->minor_version = minor;
3294         mddev->persistent = 1;
3295         mddev->external = 0;
3296         return len;
3297 }
3298
3299 static struct md_sysfs_entry md_metadata =
3300 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
3301
3302 static ssize_t
3303 action_show(mddev_t *mddev, char *page)
3304 {
3305         char *type = "idle";
3306         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3307             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
3308                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
3309                         type = "reshape";
3310                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
3311                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
3312                                 type = "resync";
3313                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
3314                                 type = "check";
3315                         else
3316                                 type = "repair";
3317                 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
3318                         type = "recover";
3319         }
3320         return sprintf(page, "%s\n", type);
3321 }
3322
3323 static ssize_t
3324 action_store(mddev_t *mddev, const char *page, size_t len)
3325 {
3326         if (!mddev->pers || !mddev->pers->sync_request)
3327                 return -EINVAL;
3328
3329         if (cmd_match(page, "idle")) {
3330                 if (mddev->sync_thread) {
3331                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3332                         md_unregister_thread(mddev->sync_thread);
3333                         mddev->sync_thread = NULL;
3334                         mddev->recovery = 0;
3335                 }
3336         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3337                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
3338                 return -EBUSY;
3339         else if (cmd_match(page, "resync"))
3340                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3341         else if (cmd_match(page, "recover")) {
3342                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
3343                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3344         } else if (cmd_match(page, "reshape")) {
3345                 int err;
3346                 if (mddev->pers->start_reshape == NULL)
3347                         return -EINVAL;
3348                 err = mddev->pers->start_reshape(mddev);
3349                 if (err)
3350                         return err;
3351                 sysfs_notify(&mddev->kobj, NULL, "degraded");
3352         } else {
3353                 if (cmd_match(page, "check"))
3354                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3355                 else if (!cmd_match(page, "repair"))
3356                         return -EINVAL;
3357                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
3358                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3359         }
3360         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3361         md_wakeup_thread(mddev->thread);
3362         sysfs_notify_dirent(mddev->sysfs_action);
3363         return len;
3364 }
3365
3366 static ssize_t
3367 mismatch_cnt_show(mddev_t *mddev, char *page)
3368 {
3369         return sprintf(page, "%llu\n",
3370                        (unsigned long long) mddev->resync_mismatches);
3371 }
3372
3373 static struct md_sysfs_entry md_scan_mode =
3374 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
3375
3376
3377 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
3378
3379 static ssize_t
3380 sync_min_show(mddev_t *mddev, char *page)
3381 {
3382         return sprintf(page, "%d (%s)\n", speed_min(mddev),
3383                        mddev->sync_speed_min ? "local": "system");
3384 }
3385
3386 static ssize_t
3387 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
3388 {
3389         int min;
3390         char *e;
3391         if (strncmp(buf, "system", 6)==0) {
3392                 mddev->sync_speed_min = 0;
3393                 return len;
3394         }
3395         min = simple_strtoul(buf, &e, 10);
3396         if (buf == e || (*e && *e != '\n') || min <= 0)
3397                 return -EINVAL;
3398         mddev->sync_speed_min = min;
3399         return len;
3400 }
3401
3402 static struct md_sysfs_entry md_sync_min =
3403 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
3404
3405 static ssize_t
3406 sync_max_show(mddev_t *mddev, char *page)
3407 {
3408         return sprintf(page, "%d (%s)\n", speed_max(mddev),
3409                        mddev->sync_speed_max ? "local": "system");
3410 }
3411
3412 static ssize_t
3413 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
3414 {
3415         int max;
3416         char *e;
3417         if (strncmp(buf, "system", 6)==0) {
3418                 mddev->sync_speed_max = 0;
3419                 return len;
3420         }
3421         max = simple_strtoul(buf, &e, 10);
3422         if (buf == e || (*e && *e != '\n') || max <= 0)
3423                 return -EINVAL;
3424         mddev->sync_speed_max = max;
3425         return len;
3426 }
3427
3428 static struct md_sysfs_entry md_sync_max =
3429 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
3430
3431 static ssize_t
3432 degraded_show(mddev_t *mddev, char *page)
3433 {
3434         return sprintf(page, "%d\n", mddev->degraded);
3435 }
3436 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
3437
3438 static ssize_t
3439 sync_force_parallel_show(mddev_t *mddev, char *page)
3440 {
3441         return sprintf(page, "%d\n", mddev->parallel_resync);
3442 }
3443
3444 static ssize_t
3445 sync_force_parallel_store(mddev_t *mddev, const char *buf, size_t len)
3446 {
3447         long n;
3448
3449         if (strict_strtol(buf, 10, &n))
3450                 return -EINVAL;
3451
3452         if (n != 0 && n != 1)
3453                 return -EINVAL;
3454
3455         mddev->parallel_resync = n;
3456
3457         if (mddev->sync_thread)
3458                 wake_up(&resync_wait);
3459
3460         return len;
3461 }
3462
3463 /* force parallel resync, even with shared block devices */
3464 static struct md_sysfs_entry md_sync_force_parallel =
3465 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
3466        sync_force_parallel_show, sync_force_parallel_store);
3467
3468 static ssize_t
3469 sync_speed_show(mddev_t *mddev, char *page)
3470 {
3471         unsigned long resync, dt, db;
3472         resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
3473         dt = (jiffies - mddev->resync_mark) / HZ;
3474         if (!dt) dt++;
3475         db = resync - mddev->resync_mark_cnt;
3476         return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
3477 }
3478
3479 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
3480
3481 static ssize_t
3482 sync_completed_show(mddev_t *mddev, char *page)
3483 {
3484         unsigned long max_sectors, resync;
3485
3486         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
3487                 max_sectors = mddev->resync_max_sectors;
3488         else
3489                 max_sectors = mddev->dev_sectors;
3490
3491         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
3492         return sprintf(page, "%lu / %lu\n", resync, max_sectors);
3493 }
3494
3495 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
3496
3497 static ssize_t
3498 min_sync_show(mddev_t *mddev, char *page)
3499 {
3500         return sprintf(page, "%llu\n",
3501                        (unsigned long long)mddev->resync_min);
3502 }
3503 static ssize_t
3504 min_sync_store(mddev_t *mddev, const char *buf, size_t len)
3505 {
3506         unsigned long long min;
3507         if (strict_strtoull(buf, 10, &min))
3508                 return -EINVAL;
3509         if (min > mddev->resync_max)
3510                 return -EINVAL;
3511         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3512                 return -EBUSY;
3513
3514         /* Must be a multiple of chunk_size */
3515         if (mddev->chunk_size) {
3516                 if (min & (sector_t)((mddev->chunk_size>>9)-1))
3517                         return -EINVAL;
3518         }
3519         mddev->resync_min = min;
3520
3521         return len;
3522 }
3523
3524 static struct md_sysfs_entry md_min_sync =
3525 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
3526
3527 static ssize_t
3528 max_sync_show(mddev_t *mddev, char *page)
3529 {
3530         if (mddev->resync_max == MaxSector)
3531                 return sprintf(page, "max\n");
3532         else
3533                 return sprintf(page, "%llu\n",
3534                                (unsigned long long)mddev->resync_max);
3535 }
3536 static ssize_t
3537 max_sync_store(mddev_t *mddev, const char *buf, size_t len)
3538 {
3539         if (strncmp(buf, "max", 3) == 0)
3540                 mddev->resync_max = MaxSector;
3541         else {
3542                 unsigned long long max;
3543                 if (strict_strtoull(buf, 10, &max))
3544                         return -EINVAL;
3545                 if (max < mddev->resync_min)
3546                         return -EINVAL;
3547                 if (max < mddev->resync_max &&
3548                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3549                         return -EBUSY;
3550
3551                 /* Must be a multiple of chunk_size */
3552                 if (mddev->chunk_size) {
3553                         if (max & (sector_t)((mddev->chunk_size>>9)-1))
3554                                 return -EINVAL;
3555                 }
3556                 mddev->resync_max = max;
3557         }
3558         wake_up(&mddev->recovery_wait);
3559         return len;
3560 }
3561
3562 static struct md_sysfs_entry md_max_sync =
3563 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
3564
3565 static ssize_t
3566 suspend_lo_show(mddev_t *mddev, char *page)
3567 {
3568         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
3569 }
3570
3571 static ssize_t
3572 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
3573 {
3574         char *e;
3575         unsigned long long new = simple_strtoull(buf, &e, 10);
3576
3577         if (mddev->pers->quiesce == NULL)
3578                 return -EINVAL;
3579         if (buf == e || (*e && *e != '\n'))
3580                 return -EINVAL;
3581         if (new >= mddev->suspend_hi ||
3582             (new > mddev->suspend_lo && new < mddev->suspend_hi)) {
3583                 mddev->suspend_lo = new;
3584                 mddev->pers->quiesce(mddev, 2);
3585                 return len;
3586         } else
3587                 return -EINVAL;
3588 }
3589 static struct md_sysfs_entry md_suspend_lo =
3590 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
3591
3592
3593 static ssize_t
3594 suspend_hi_show(mddev_t *mddev, char *page)
3595 {
3596         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
3597 }
3598
3599 static ssize_t
3600 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
3601 {
3602         char *e;
3603         unsigned long long new = simple_strtoull(buf, &e, 10);
3604
3605         if (mddev->pers->quiesce == NULL)
3606                 return -EINVAL;
3607         if (buf == e || (*e && *e != '\n'))
3608                 return -EINVAL;
3609         if ((new <= mddev->suspend_lo && mddev->suspend_lo >= mddev->suspend_hi) ||
3610             (new > mddev->suspend_lo && new > mddev->suspend_hi)) {
3611                 mddev->suspend_hi = new;
3612                 mddev->pers->quiesce(mddev, 1);
3613                 mddev->pers->quiesce(mddev, 0);
3614                 return len;
3615         } else
3616                 return -EINVAL;
3617 }
3618 static struct md_sysfs_entry md_suspend_hi =
3619 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
3620
3621 static ssize_t
3622 reshape_position_show(mddev_t *mddev, char *page)
3623 {
3624         if (mddev->reshape_position != MaxSector)
3625                 return sprintf(page, "%llu\n",
3626                                (unsigned long long)mddev->reshape_position);
3627         strcpy(page, "none\n");
3628         return 5;
3629 }
3630
3631 static ssize_t
3632 reshape_position_store(mddev_t *mddev, const char *buf, size_t len)
3633 {
3634         char *e;
3635         unsigned long long new = simple_strtoull(buf, &e, 10);
3636         if (mddev->pers)
3637                 return -EBUSY;
3638         if (buf == e || (*e && *e != '\n'))
3639                 return -EINVAL;
3640         mddev->reshape_position = new;
3641         mddev->delta_disks = 0;
3642         mddev->new_level = mddev->level;
3643         mddev->new_layout = mddev->layout;
3644         mddev->new_chunk = mddev->chunk_size;
3645         return len;
3646 }
3647
3648 static struct md_sysfs_entry md_reshape_position =
3649 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
3650        reshape_position_store);
3651
3652 static ssize_t
3653 array_size_show(mddev_t *mddev, char *page)
3654 {
3655         if (mddev->external_size)
3656                 return sprintf(page, "%llu\n",
3657                                (unsigned long long)mddev->array_sectors/2);
3658         else
3659                 return sprintf(page, "default\n");
3660 }
3661
3662 static ssize_t
3663 array_size_store(mddev_t *mddev, const char *buf, size_t len)
3664 {
3665         sector_t sectors;
3666
3667         if (strncmp(buf, "default", 7) == 0) {
3668                 if (mddev->pers)
3669                         sectors = mddev->pers->size(mddev, 0, 0);
3670                 else
3671                         sectors = mddev->array_sectors;
3672
3673                 mddev->external_size = 0;
3674         } else {
3675                 if (strict_blocks_to_sectors(buf, &sectors) < 0)
3676                         return -EINVAL;
3677                 if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
3678                         return -EINVAL;
3679
3680                 mddev->external_size = 1;
3681         }
3682
3683         mddev->array_sectors = sectors;
3684         set_capacity(mddev->gendisk, mddev->array_sectors);
3685         if (mddev->pers) {
3686                 struct block_device *bdev = bdget_disk(mddev->gendisk, 0);
3687
3688                 if (bdev) {
3689                         mutex_lock(&bdev->bd_inode->i_mutex);
3690                         i_size_write(bdev->bd_inode,
3691                                      (loff_t)mddev->array_sectors << 9);
3692                         mutex_unlock(&bdev->bd_inode->i_mutex);
3693                         bdput(bdev);
3694                 }
3695         }
3696
3697         return len;
3698 }
3699
3700 static struct md_sysfs_entry md_array_size =
3701 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
3702        array_size_store);
3703
3704 static struct attribute *md_default_attrs[] = {
3705         &md_level.attr,
3706         &md_layout.attr,
3707         &md_raid_disks.attr,
3708         &md_chunk_size.attr,
3709         &md_size.attr,
3710         &md_resync_start.attr,
3711         &md_metadata.attr,
3712         &md_new_device.attr,
3713         &md_safe_delay.attr,
3714         &md_array_state.attr,
3715         &md_reshape_position.attr,
3716         &md_array_size.attr,
3717         NULL,
3718 };
3719
3720 static struct attribute *md_redundancy_attrs[] = {
3721         &md_scan_mode.attr,
3722         &md_mismatches.attr,
3723         &md_sync_min.attr,
3724         &md_sync_max.attr,
3725         &md_sync_speed.attr,
3726         &md_sync_force_parallel.attr,
3727         &md_sync_completed.attr,
3728         &md_min_sync.attr,
3729         &md_max_sync.attr,
3730         &md_suspend_lo.attr,
3731         &md_suspend_hi.attr,
3732         &md_bitmap.attr,
3733         &md_degraded.attr,
3734         NULL,
3735 };
3736 static struct attribute_group md_redundancy_group = {
3737         .name = NULL,
3738         .attrs = md_redundancy_attrs,
3739 };
3740
3741
3742 static ssize_t
3743 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3744 {
3745         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3746         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3747         ssize_t rv;
3748
3749         if (!entry->show)
3750                 return -EIO;
3751         rv = mddev_lock(mddev);
3752         if (!rv) {
3753                 rv = entry->show(mddev, page);
3754                 mddev_unlock(mddev);
3755         }
3756         return rv;
3757 }
3758
3759 static ssize_t
3760 md_attr_store(struct kobject *kobj, struct attribute *attr,
3761               const char *page, size_t length)
3762 {
3763         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
3764         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
3765         ssize_t rv;
3766
3767         if (!entry->store)
3768                 return -EIO;
3769         if (!capable(CAP_SYS_ADMIN))
3770                 return -EACCES;
3771         rv = mddev_lock(mddev);
3772         if (mddev->hold_active == UNTIL_IOCTL)
3773                 mddev->hold_active = 0;
3774         if (!rv) {
3775                 rv = entry->store(mddev, page, length);
3776                 mddev_unlock(mddev);
3777         }
3778         return rv;
3779 }
3780
3781 static void md_free(struct kobject *ko)
3782 {
3783         mddev_t *mddev = container_of(ko, mddev_t, kobj);
3784
3785         if (mddev->sysfs_state)
3786                 sysfs_put(mddev->sysfs_state);
3787
3788         if (mddev->gendisk) {
3789                 del_gendisk(mddev->gendisk);
3790                 put_disk(mddev->gendisk);
3791         }
3792         if (mddev->queue)
3793                 blk_cleanup_queue(mddev->queue);
3794
3795         kfree(mddev);
3796 }
3797
3798 static struct sysfs_ops md_sysfs_ops = {
3799         .show   = md_attr_show,
3800         .store  = md_attr_store,
3801 };
3802 static struct kobj_type md_ktype = {
3803         .release        = md_free,
3804         .sysfs_ops      = &md_sysfs_ops,
3805         .default_attrs  = md_default_attrs,
3806 };
3807
3808 int mdp_major = 0;
3809
3810 static int md_alloc(dev_t dev, char *name)
3811 {
3812         static DEFINE_MUTEX(disks_mutex);
3813         mddev_t *mddev = mddev_find(dev);
3814         struct gendisk *disk;
3815         int partitioned;
3816         int shift;
3817         int unit;
3818         int error;
3819
3820         if (!mddev)
3821                 return -ENODEV;
3822
3823         partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
3824         shift = partitioned ? MdpMinorShift : 0;
3825         unit = MINOR(mddev->unit) >> shift;
3826
3827         /* wait for any previous instance if this device
3828          * to be completed removed (mddev_delayed_delete).
3829          */
3830         flush_scheduled_work();
3831
3832         mutex_lock(&disks_mutex);
3833         if (mddev->gendisk) {
3834                 mutex_unlock(&disks_mutex);
3835                 mddev_put(mddev);
3836                 return -EEXIST;
3837         }
3838
3839         if (name) {
3840                 /* Need to ensure that 'name' is not a duplicate.
3841                  */
3842                 mddev_t *mddev2;
3843                 spin_lock(&all_mddevs_lock);
3844
3845                 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
3846                         if (mddev2->gendisk &&
3847                             strcmp(mddev2->gendisk->disk_name, name) == 0) {
3848                                 spin_unlock(&all_mddevs_lock);
3849                                 return -EEXIST;
3850                         }
3851                 spin_unlock(&all_mddevs_lock);
3852         }
3853
3854         mddev->queue = blk_alloc_queue(GFP_KERNEL);
3855         if (!mddev->queue) {
3856                 mutex_unlock(&disks_mutex);
3857                 mddev_put(mddev);
3858                 return -ENOMEM;
3859         }
3860         mddev->queue->queuedata = mddev;
3861
3862         /* Can be unlocked because the queue is new: no concurrency */
3863         queue_flag_set_unlocked(QUEUE_FLAG_CLUSTER, mddev->queue);
3864
3865         blk_queue_make_request(mddev->queue, md_make_request);
3866
3867         disk = alloc_disk(1 << shift);
3868         if (!disk) {
3869                 mutex_unlock(&disks_mutex);
3870                 blk_cleanup_queue(mddev->queue);
3871                 mddev->queue = NULL;
3872                 mddev_put(mddev);
3873                 return -ENOMEM;
3874         }
3875         disk->major = MAJOR(mddev->unit);
3876         disk->first_minor = unit << shift;
3877         if (name)
3878                 strcpy(disk->disk_name, name);
3879         else if (partitioned)
3880                 sprintf(disk->disk_name, "md_d%d", unit);
3881         else
3882                 sprintf(disk->disk_name, "md%d", unit);
3883         disk->fops = &md_fops;
3884         disk->private_data = mddev;
3885         disk->queue = mddev->queue;
3886         /* Allow extended partitions.  This makes the
3887          * 'mdp' device redundant, but we can't really
3888          * remove it now.
3889          */
3890         disk->flags |= GENHD_FL_EXT_DEVT;
3891         add_disk(disk);
3892         mddev->gendisk = disk;
3893         error = kobject_init_and_add(&mddev->kobj, &md_ktype,
3894                                      &disk_to_dev(disk)->kobj, "%s", "md");
3895         mutex_unlock(&disks_mutex);
3896         if (error)
3897                 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
3898                        disk->disk_name);
3899         else {
3900                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
3901                 mddev->sysfs_state = sysfs_get_dirent(mddev->kobj.sd, "array_state");
3902         }
3903         mddev_put(mddev);
3904         return 0;
3905 }
3906
3907 static struct kobject *md_probe(dev_t dev, int *part, void *data)
3908 {
3909         md_alloc(dev, NULL);
3910         return NULL;
3911 }
3912
3913 static int add_named_array(const char *val, struct kernel_param *kp)
3914 {
3915         /* val must be "md_*" where * is not all digits.
3916          * We allocate an array with a large free minor number, and
3917          * set the name to val.  val must not already be an active name.
3918          */
3919         int len = strlen(val);
3920         char buf[DISK_NAME_LEN];
3921
3922         while (len && val[len-1] == '\n')
3923                 len--;
3924         if (len >= DISK_NAME_LEN)
3925                 return -E2BIG;
3926         strlcpy(buf, val, len+1);
3927         if (strncmp(buf, "md_", 3) != 0)
3928                 return -EINVAL;
3929         return md_alloc(0, buf);
3930 }
3931
3932 static void md_safemode_timeout(unsigned long data)
3933 {
3934         mddev_t *mddev = (mddev_t *) data;
3935
3936         if (!atomic_read(&mddev->writes_pending)) {
3937                 mddev->safemode = 1;
3938                 if (mddev->external)
3939                         sysfs_notify_dirent(mddev->sysfs_state);
3940         }
3941         md_wakeup_thread(mddev->thread);
3942 }
3943
3944 static int start_dirty_degraded;
3945
3946 static int do_md_run(mddev_t * mddev)
3947 {
3948         int err;
3949         int chunk_size;
3950         mdk_rdev_t *rdev;
3951         struct gendisk *disk;
3952         struct mdk_personality *pers;
3953         char b[BDEVNAME_SIZE];
3954
3955         if (list_empty(&mddev->disks))
3956                 /* cannot run an array with no devices.. */
3957                 return -EINVAL;
3958
3959         if (mddev->pers)
3960                 return -EBUSY;
3961
3962         /*
3963          * Analyze all RAID superblock(s)
3964          */
3965         if (!mddev->raid_disks) {
3966                 if (!mddev->persistent)
3967                         return -EINVAL;
3968                 analyze_sbs(mddev);
3969         }
3970
3971         chunk_size = mddev->chunk_size;
3972
3973         if (chunk_size) {
3974                 if (chunk_size > MAX_CHUNK_SIZE) {
3975                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
3976                                 chunk_size, MAX_CHUNK_SIZE);
3977                         return -EINVAL;
3978                 }
3979                 /*
3980                  * chunk-size has to be a power of 2
3981                  */
3982                 if ( (1 << ffz(~chunk_size)) != chunk_size) {
3983                         printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
3984                         return -EINVAL;
3985                 }
3986
3987                 /* devices must have minimum size of one chunk */
3988                 list_for_each_entry(rdev, &mddev->disks, same_set) {
3989                         if (test_bit(Faulty, &rdev->flags))
3990                                 continue;
3991                         if (rdev->sectors < chunk_size / 512) {
3992                                 printk(KERN_WARNING
3993                                         "md: Dev %s smaller than chunk_size:"
3994                                         " %llu < %d\n",
3995                                         bdevname(rdev->bdev,b),
3996                                         (unsigned long long)rdev->sectors,
3997                                         chunk_size / 512);
3998                                 return -EINVAL;
3999                         }
4000                 }
4001         }
4002
4003         if (mddev->level != LEVEL_NONE)
4004                 request_module("md-level-%d", mddev->level);
4005         else if (mddev->clevel[0])
4006                 request_module("md-%s", mddev->clevel);
4007
4008         /*
4009          * Drop all container device buffers, from now on
4010          * the only valid external interface is through the md
4011          * device.
4012          */
4013         list_for_each_entry(rdev, &mddev->disks, same_set) {
4014                 if (test_bit(Faulty, &rdev->flags))
4015                         continue;
4016                 sync_blockdev(rdev->bdev);
4017                 invalidate_bdev(rdev->bdev);
4018
4019                 /* perform some consistency tests on the device.
4020                  * We don't want the data to overlap the metadata,
4021                  * Internal Bitmap issues have been handled elsewhere.
4022                  */
4023                 if (rdev->data_offset < rdev->sb_start) {
4024                         if (mddev->dev_sectors &&
4025                             rdev->data_offset + mddev->dev_sectors
4026                             > rdev->sb_start) {
4027                                 printk("md: %s: data overlaps metadata\n",
4028                                        mdname(mddev));
4029                                 return -EINVAL;
4030                         }
4031                 } else {
4032                         if (rdev->sb_start + rdev->sb_size/512
4033                             > rdev->data_offset) {
4034                                 printk("md: %s: metadata overlaps data\n",
4035                                        mdname(mddev));
4036                                 return -EINVAL;
4037                         }
4038                 }
4039                 sysfs_notify_dirent(rdev->sysfs_state);
4040         }
4041
4042         md_probe(mddev->unit, NULL, NULL);
4043         disk = mddev->gendisk;
4044         if (!disk)
4045                 return -ENOMEM;
4046
4047         spin_lock(&pers_lock);
4048         pers = find_pers(mddev->level, mddev->clevel);
4049         if (!pers || !try_module_get(pers->owner)) {
4050                 spin_unlock(&pers_lock);
4051                 if (mddev->level != LEVEL_NONE)
4052                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
4053                                mddev->level);
4054                 else
4055                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
4056                                mddev->clevel);
4057                 return -EINVAL;
4058         }
4059         mddev->pers = pers;
4060         spin_unlock(&pers_lock);
4061         if (mddev->level != pers->level) {
4062                 mddev->level = pers->level;
4063                 mddev->new_level = pers->level;
4064         }
4065         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
4066
4067         if (pers->level >= 4 && pers->level <= 6)
4068                 /* Cannot support integrity (yet) */
4069                 blk_integrity_unregister(mddev->gendisk);
4070
4071         if (mddev->reshape_position != MaxSector &&
4072             pers->start_reshape == NULL) {
4073                 /* This personality cannot handle reshaping... */
4074                 mddev->pers = NULL;
4075                 module_put(pers->owner);
4076                 return -EINVAL;
4077         }
4078
4079         if (pers->sync_request) {
4080                 /* Warn if this is a potentially silly
4081                  * configuration.
4082                  */
4083                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4084                 mdk_rdev_t *rdev2;
4085                 int warned = 0;
4086
4087                 list_for_each_entry(rdev, &mddev->disks, same_set)
4088                         list_for_each_entry(rdev2, &mddev->disks, same_set) {
4089                                 if (rdev < rdev2 &&
4090                                     rdev->bdev->bd_contains ==
4091                                     rdev2->bdev->bd_contains) {
4092                                         printk(KERN_WARNING
4093                                                "%s: WARNING: %s appears to be"
4094                                                " on the same physical disk as"
4095                                                " %s.\n",
4096                                                mdname(mddev),
4097                                                bdevname(rdev->bdev,b),
4098                                                bdevname(rdev2->bdev,b2));
4099                                         warned = 1;
4100                                 }
4101                         }
4102
4103                 if (warned)
4104                         printk(KERN_WARNING
4105                                "True protection against single-disk"
4106                                " failure might be compromised.\n");
4107         }
4108
4109         mddev->recovery = 0;
4110         /* may be over-ridden by personality */
4111         mddev->resync_max_sectors = mddev->dev_sectors;
4112
4113         mddev->barriers_work = 1;
4114         mddev->ok_start_degraded = start_dirty_degraded;
4115
4116         if (start_readonly)
4117                 mddev->ro = 2; /* read-only, but switch on first write */
4118
4119         err = mddev->pers->run(mddev);
4120         if (err)
4121                 printk(KERN_ERR "md: pers->run() failed ...\n");
4122         else if (mddev->pers->size(mddev, 0, 0) < mddev->array_sectors) {
4123                 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
4124                           " but 'external_size' not in effect?\n", __func__);
4125                 printk(KERN_ERR
4126                        "md: invalid array_size %llu > default size %llu\n",
4127                        (unsigned long long)mddev->array_sectors / 2,
4128                        (unsigned long long)mddev->pers->size(mddev, 0, 0) / 2);
4129                 err = -EINVAL;
4130                 mddev->pers->stop(mddev);
4131         }
4132         if (err == 0 && mddev->pers->sync_request) {
4133                 err = bitmap_create(mddev);
4134                 if (err) {
4135                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
4136                                mdname(mddev), err);
4137                         mddev->pers->stop(mddev);
4138                 }
4139         }
4140         if (err) {
4141                 module_put(mddev->pers->owner);
4142                 mddev->pers = NULL;
4143                 bitmap_destroy(mddev);
4144                 return err;
4145         }
4146         if (mddev->pers->sync_request) {
4147                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
4148                         printk(KERN_WARNING
4149                                "md: cannot register extra attributes for %s\n",
4150                                mdname(mddev));
4151                 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action");
4152         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
4153                 mddev->ro = 0;
4154
4155         atomic_set(&mddev->writes_pending,0);
4156         mddev->safemode = 0;
4157         mddev->safemode_timer.function = md_safemode_timeout;
4158         mddev->safemode_timer.data = (unsigned long) mddev;
4159         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
4160         mddev->in_sync = 1;
4161
4162         list_for_each_entry(rdev, &mddev->disks, same_set)
4163                 if (rdev->raid_disk >= 0) {
4164                         char nm[20];
4165                         sprintf(nm, "rd%d", rdev->raid_disk);
4166                         if (sysfs_create_link(&mddev->kobj, &rdev->kobj, nm))
4167                                 printk("md: cannot register %s for %s\n",
4168                                        nm, mdname(mddev));
4169                 }
4170         
4171         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4172         
4173         if (mddev->flags)
4174                 md_update_sb(mddev, 0);
4175
4176         set_capacity(disk, mddev->array_sectors);
4177
4178         /* If there is a partially-recovered drive we need to
4179          * start recovery here.  If we leave it to md_check_recovery,
4180          * it will remove the drives and not do the right thing
4181          */
4182         if (mddev->degraded && !mddev->sync_thread) {
4183                 int spares = 0;
4184                 list_for_each_entry(rdev, &mddev->disks, same_set)
4185                         if (rdev->raid_disk >= 0 &&
4186                             !test_bit(In_sync, &rdev->flags) &&
4187                             !test_bit(Faulty, &rdev->flags))
4188                                 /* complete an interrupted recovery */
4189                                 spares++;
4190                 if (spares && mddev->pers->sync_request) {
4191                         mddev->recovery = 0;
4192                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4193                         mddev->sync_thread = md_register_thread(md_do_sync,
4194                                                                 mddev,
4195                                                                 "%s_resync");
4196                         if (!mddev->sync_thread) {
4197                                 printk(KERN_ERR "%s: could not start resync"
4198                                        " thread...\n",
4199                                        mdname(mddev));
4200                                 /* leave the spares where they are, it shouldn't hurt */
4201                                 mddev->recovery = 0;
4202                         }
4203                 }
4204         }
4205         md_wakeup_thread(mddev->thread);
4206         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
4207
4208         mddev->changed = 1;
4209         md_new_event(mddev);
4210         sysfs_notify_dirent(mddev->sysfs_state);
4211         if (mddev->sysfs_action)
4212                 sysfs_notify_dirent(mddev->sysfs_action);
4213         sysfs_notify(&mddev->kobj, NULL, "degraded");
4214         kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
4215         return 0;
4216 }
4217
4218 static int restart_array(mddev_t *mddev)
4219 {
4220         struct gendisk *disk = mddev->gendisk;
4221
4222         /* Complain if it has no devices */
4223         if (list_empty(&mddev->disks))
4224                 return -ENXIO;
4225         if (!mddev->pers)
4226                 return -EINVAL;
4227         if (!mddev->ro)
4228                 return -EBUSY;
4229         mddev->safemode = 0;
4230         mddev->ro = 0;
4231         set_disk_ro(disk, 0);
4232         printk(KERN_INFO "md: %s switched to read-write mode.\n",
4233                 mdname(mddev));
4234         /* Kick recovery or resync if necessary */
4235         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4236         md_wakeup_thread(mddev->thread);
4237         md_wakeup_thread(mddev->sync_thread);
4238         sysfs_notify_dirent(mddev->sysfs_state);
4239         return 0;
4240 }
4241
4242 /* similar to deny_write_access, but accounts for our holding a reference
4243  * to the file ourselves */
4244 static int deny_bitmap_write_access(struct file * file)
4245 {
4246         struct inode *inode = file->f_mapping->host;
4247
4248         spin_lock(&inode->i_lock);
4249         if (atomic_read(&inode->i_writecount) > 1) {
4250                 spin_unlock(&inode->i_lock);
4251                 return -ETXTBSY;
4252         }
4253         atomic_set(&inode->i_writecount, -1);
4254         spin_unlock(&inode->i_lock);
4255
4256         return 0;
4257 }
4258
4259 static void restore_bitmap_write_access(struct file *file)
4260 {
4261         struct inode *inode = file->f_mapping->host;
4262
4263         spin_lock(&inode->i_lock);
4264         atomic_set(&inode->i_writecount, 1);
4265         spin_unlock(&inode->i_lock);
4266 }
4267
4268 /* mode:
4269  *   0 - completely stop and dis-assemble array
4270  *   1 - switch to readonly
4271  *   2 - stop but do not disassemble array
4272  */
4273 static int do_md_stop(mddev_t * mddev, int mode, int is_open)
4274 {
4275         int err = 0;
4276         struct gendisk *disk = mddev->gendisk;
4277
4278         if (atomic_read(&mddev->openers) > is_open) {
4279                 printk("md: %s still in use.\n",mdname(mddev));
4280                 return -EBUSY;
4281         }
4282
4283         if (mddev->pers) {
4284
4285                 if (mddev->sync_thread) {
4286                         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4287                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4288                         md_unregister_thread(mddev->sync_thread);
4289                         mddev->sync_thread = NULL;
4290                 }
4291
4292                 del_timer_sync(&mddev->safemode_timer);
4293
4294                 switch(mode) {
4295                 case 1: /* readonly */
4296                         err  = -ENXIO;
4297                         if (mddev->ro==1)
4298                                 goto out;
4299                         mddev->ro = 1;
4300                         break;
4301                 case 0: /* disassemble */
4302                 case 2: /* stop */
4303                         bitmap_flush(mddev);
4304                         md_super_wait(mddev);
4305                         if (mddev->ro)
4306                                 set_disk_ro(disk, 0);
4307
4308                         mddev->pers->stop(mddev);
4309                         mddev->queue->merge_bvec_fn = NULL;
4310                         mddev->queue->unplug_fn = NULL;
4311                         mddev->queue->backing_dev_info.congested_fn = NULL;
4312                         if (mddev->pers->sync_request) {
4313                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
4314                                 if (mddev->sysfs_action)
4315                                         sysfs_put(mddev->sysfs_action);
4316                                 mddev->sysfs_action = NULL;
4317                         }
4318                         module_put(mddev->pers->owner);
4319                         mddev->pers = NULL;
4320                         /* tell userspace to handle 'inactive' */
4321                         sysfs_notify_dirent(mddev->sysfs_state);
4322
4323                         set_capacity(disk, 0);
4324                         mddev->changed = 1;
4325
4326                         if (mddev->ro)
4327                                 mddev->ro = 0;
4328                 }
4329                 if (!mddev->in_sync || mddev->flags) {
4330                         /* mark array as shutdown cleanly */
4331                         mddev->in_sync = 1;
4332                         md_update_sb(mddev, 1);
4333                 }
4334                 if (mode == 1)
4335                         set_disk_ro(disk, 1);
4336                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4337         }
4338
4339         /*
4340          * Free resources if final stop
4341          */
4342         if (mode == 0) {
4343                 mdk_rdev_t *rdev;
4344
4345                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
4346
4347                 bitmap_destroy(mddev);
4348                 if (mddev->bitmap_file) {
4349                         restore_bitmap_write_access(mddev->bitmap_file);
4350                         fput(mddev->bitmap_file);
4351                         mddev->bitmap_file = NULL;
4352                 }
4353                 mddev->bitmap_offset = 0;
4354
4355                 list_for_each_entry(rdev, &mddev->disks, same_set)
4356                         if (rdev->raid_disk >= 0) {
4357                                 char nm[20];
4358                                 sprintf(nm, "rd%d", rdev->raid_disk);
4359                                 sysfs_remove_link(&mddev->kobj, nm);
4360                         }
4361
4362                 /* make sure all md_delayed_delete calls have finished */
4363                 flush_scheduled_work();
4364
4365                 export_array(mddev);
4366
4367                 mddev->array_sectors = 0;
4368                 mddev->external_size = 0;
4369                 mddev->dev_sectors = 0;
4370                 mddev->raid_disks = 0;
4371                 mddev->recovery_cp = 0;
4372                 mddev->resync_min = 0;
4373                 mddev->resync_max = MaxSector;
4374                 mddev->reshape_position = MaxSector;
4375                 mddev->external = 0;
4376                 mddev->persistent = 0;
4377                 mddev->level = LEVEL_NONE;
4378                 mddev->clevel[0] = 0;
4379                 mddev->flags = 0;
4380                 mddev->ro = 0;
4381                 mddev->metadata_type[0] = 0;
4382                 mddev->chunk_size = 0;
4383                 mddev->ctime = mddev->utime = 0;
4384                 mddev->layout = 0;
4385                 mddev->max_disks = 0;
4386                 mddev->events = 0;
4387                 mddev->delta_disks = 0;
4388                 mddev->new_level = LEVEL_NONE;
4389                 mddev->new_layout = 0;
4390                 mddev->new_chunk = 0;
4391                 mddev->curr_resync = 0;
4392                 mddev->resync_mismatches = 0;
4393                 mddev->suspend_lo = mddev->suspend_hi = 0;
4394                 mddev->sync_speed_min = mddev->sync_speed_max = 0;
4395                 mddev->recovery = 0;
4396                 mddev->in_sync = 0;
4397                 mddev->changed = 0;
4398                 mddev->degraded = 0;
4399                 mddev->barriers_work = 0;
4400                 mddev->safemode = 0;
4401                 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
4402                 if (mddev->hold_active == UNTIL_STOP)
4403                         mddev->hold_active = 0;
4404
4405         } else if (mddev->pers)
4406                 printk(KERN_INFO "md: %s switched to read-only mode.\n",
4407                         mdname(mddev));
4408         err = 0;
4409         blk_integrity_unregister(disk);
4410         md_new_event(mddev);
4411         sysfs_notify_dirent(mddev->sysfs_state);
4412 out:
4413         return err;
4414 }
4415
4416 #ifndef MODULE
4417 static void autorun_array(mddev_t *mddev)
4418 {
4419         mdk_rdev_t *rdev;
4420         int err;
4421
4422         if (list_empty(&mddev->disks))
4423                 return;
4424
4425         printk(KERN_INFO "md: running: ");
4426
4427         list_for_each_entry(rdev, &mddev->disks, same_set) {
4428                 char b[BDEVNAME_SIZE];
4429                 printk("<%s>", bdevname(rdev->bdev,b));
4430         }
4431         printk("\n");
4432
4433         err = do_md_run(mddev);
4434         if (err) {
4435                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
4436                 do_md_stop(mddev, 0, 0);
4437         }
4438 }
4439
4440 /*
4441  * lets try to run arrays based on all disks that have arrived
4442  * until now. (those are in pending_raid_disks)
4443  *
4444  * the method: pick the first pending disk, collect all disks with
4445  * the same UUID, remove all from the pending list and put them into
4446  * the 'same_array' list. Then order this list based on superblock
4447  * update time (freshest comes first), kick out 'old' disks and
4448  * compare superblocks. If everything's fine then run it.
4449  *
4450  * If "unit" is allocated, then bump its reference count
4451  */
4452 static void autorun_devices(int part)
4453 {
4454         mdk_rdev_t *rdev0, *rdev, *tmp;
4455         mddev_t *mddev;
4456         char b[BDEVNAME_SIZE];
4457
4458         printk(KERN_INFO "md: autorun ...\n");
4459         while (!list_empty(&pending_raid_disks)) {
4460                 int unit;
4461                 dev_t dev;
4462                 LIST_HEAD(candidates);
4463                 rdev0 = list_entry(pending_raid_disks.next,
4464                                          mdk_rdev_t, same_set);
4465
4466                 printk(KERN_INFO "md: considering %s ...\n",
4467                         bdevname(rdev0->bdev,b));
4468                 INIT_LIST_HEAD(&candidates);
4469                 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
4470                         if (super_90_load(rdev, rdev0, 0) >= 0) {
4471                                 printk(KERN_INFO "md:  adding %s ...\n",
4472                                         bdevname(rdev->bdev,b));
4473                                 list_move(&rdev->same_set, &candidates);
4474                         }
4475                 /*
4476                  * now we have a set of devices, with all of them having
4477                  * mostly sane superblocks. It's time to allocate the
4478                  * mddev.
4479                  */
4480                 if (part) {
4481                         dev = MKDEV(mdp_major,
4482                                     rdev0->preferred_minor << MdpMinorShift);
4483                         unit = MINOR(dev) >> MdpMinorShift;
4484                 } else {
4485                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
4486                         unit = MINOR(dev);
4487                 }
4488                 if (rdev0->preferred_minor != unit) {
4489                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
4490                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
4491                         break;
4492                 }
4493
4494                 md_probe(dev, NULL, NULL);
4495                 mddev = mddev_find(dev);
4496                 if (!mddev || !mddev->gendisk) {
4497                         if (mddev)
4498                                 mddev_put(mddev);
4499                         printk(KERN_ERR
4500                                 "md: cannot allocate memory for md drive.\n");
4501                         break;
4502                 }
4503                 if (mddev_lock(mddev)) 
4504                         printk(KERN_WARNING "md: %s locked, cannot run\n",
4505                                mdname(mddev));
4506                 else if (mddev->raid_disks || mddev->major_version
4507                          || !list_empty(&mddev->disks)) {
4508                         printk(KERN_WARNING 
4509                                 "md: %s already running, cannot run %s\n",
4510                                 mdname(mddev), bdevname(rdev0->bdev,b));
4511                         mddev_unlock(mddev);
4512                 } else {
4513                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
4514                         mddev->persistent = 1;
4515                         rdev_for_each_list(rdev, tmp, &candidates) {
4516                                 list_del_init(&rdev->same_set);
4517                                 if (bind_rdev_to_array(rdev, mddev))
4518                                         export_rdev(rdev);
4519                         }
4520                         autorun_array(mddev);
4521                         mddev_unlock(mddev);
4522                 }
4523                 /* on success, candidates will be empty, on error
4524                  * it won't...
4525                  */
4526                 rdev_for_each_list(rdev, tmp, &candidates) {
4527                         list_del_init(&rdev->same_set);
4528                         export_rdev(rdev);
4529                 }
4530                 mddev_put(mddev);
4531         }
4532         printk(KERN_INFO "md: ... autorun DONE.\n");
4533 }
4534 #endif /* !MODULE */
4535
4536 static int get_version(void __user * arg)
4537 {
4538         mdu_version_t ver;
4539
4540         ver.major = MD_MAJOR_VERSION;
4541         ver.minor = MD_MINOR_VERSION;
4542         ver.patchlevel = MD_PATCHLEVEL_VERSION;
4543
4544         if (copy_to_user(arg, &ver, sizeof(ver)))
4545                 return -EFAULT;
4546
4547         return 0;
4548 }
4549
4550 static int get_array_info(mddev_t * mddev, void __user * arg)
4551 {
4552         mdu_array_info_t info;
4553         int nr,working,active,failed,spare;
4554         mdk_rdev_t *rdev;
4555
4556         nr=working=active=failed=spare=0;
4557         list_for_each_entry(rdev, &mddev->disks, same_set) {
4558                 nr++;
4559                 if (test_bit(Faulty, &rdev->flags))
4560                         failed++;
4561                 else {
4562                         working++;
4563                         if (test_bit(In_sync, &rdev->flags))
4564                                 active++;       
4565                         else
4566                                 spare++;
4567                 }
4568         }
4569
4570         info.major_version = mddev->major_version;
4571         info.minor_version = mddev->minor_version;
4572         info.patch_version = MD_PATCHLEVEL_VERSION;
4573         info.ctime         = mddev->ctime;
4574         info.level         = mddev->level;
4575         info.size          = mddev->dev_sectors / 2;
4576         if (info.size != mddev->dev_sectors / 2) /* overflow */
4577                 info.size = -1;
4578         info.nr_disks      = nr;
4579         info.raid_disks    = mddev->raid_disks;
4580         info.md_minor      = mddev->md_minor;
4581         info.not_persistent= !mddev->persistent;
4582
4583         info.utime         = mddev->utime;
4584         info.state         = 0;
4585         if (mddev->in_sync)
4586                 info.state = (1<<MD_SB_CLEAN);
4587         if (mddev->bitmap && mddev->bitmap_offset)
4588                 info.state = (1<<MD_SB_BITMAP_PRESENT);
4589         info.active_disks  = active;
4590         info.working_disks = working;
4591         info.failed_disks  = failed;
4592         info.spare_disks   = spare;
4593
4594         info.layout        = mddev->layout;
4595         info.chunk_size    = mddev->chunk_size;
4596
4597         if (copy_to_user(arg, &info, sizeof(info)))
4598                 return -EFAULT;
4599
4600         return 0;
4601 }
4602
4603 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
4604 {
4605         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
4606         char *ptr, *buf = NULL;
4607         int err = -ENOMEM;
4608
4609         if (md_allow_write(mddev))
4610                 file = kmalloc(sizeof(*file), GFP_NOIO);
4611         else
4612                 file = kmalloc(sizeof(*file), GFP_KERNEL);
4613
4614         if (!file)
4615                 goto out;
4616
4617         /* bitmap disabled, zero the first byte and copy out */
4618         if (!mddev->bitmap || !mddev->bitmap->file) {
4619                 file->pathname[0] = '\0';
4620                 goto copy_out;
4621         }
4622
4623         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
4624         if (!buf)
4625                 goto out;
4626
4627         ptr = d_path(&mddev->bitmap->file->f_path, buf, sizeof(file->pathname));
4628         if (IS_ERR(ptr))
4629                 goto out;
4630
4631         strcpy(file->pathname, ptr);
4632
4633 copy_out:
4634         err = 0;
4635         if (copy_to_user(arg, file, sizeof(*file)))
4636                 err = -EFAULT;
4637 out:
4638         kfree(buf);
4639         kfree(file);
4640         return err;
4641 }
4642
4643 static int get_disk_info(mddev_t * mddev, void __user * arg)
4644 {
4645         mdu_disk_info_t info;
4646         mdk_rdev_t *rdev;
4647
4648         if (copy_from_user(&info, arg, sizeof(info)))
4649                 return -EFAULT;
4650
4651         rdev = find_rdev_nr(mddev, info.number);
4652         if (rdev) {
4653                 info.major = MAJOR(rdev->bdev->bd_dev);
4654                 info.minor = MINOR(rdev->bdev->bd_dev);
4655                 info.raid_disk = rdev->raid_disk;
4656                 info.state = 0;
4657                 if (test_bit(Faulty, &rdev->flags))
4658                         info.state |= (1<<MD_DISK_FAULTY);
4659                 else if (test_bit(In_sync, &rdev->flags)) {
4660                         info.state |= (1<<MD_DISK_ACTIVE);
4661                         info.state |= (1<<MD_DISK_SYNC);
4662                 }
4663                 if (test_bit(WriteMostly, &rdev->flags))
4664                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
4665         } else {
4666                 info.major = info.minor = 0;
4667                 info.raid_disk = -1;
4668                 info.state = (1<<MD_DISK_REMOVED);
4669         }
4670
4671         if (copy_to_user(arg, &info, sizeof(info)))
4672                 return -EFAULT;
4673
4674         return 0;
4675 }
4676
4677 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
4678 {
4679         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4680         mdk_rdev_t *rdev;
4681         dev_t dev = MKDEV(info->major,info->minor);
4682
4683         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
4684                 return -EOVERFLOW;
4685
4686         if (!mddev->raid_disks) {
4687                 int err;
4688                 /* expecting a device which has a superblock */
4689                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
4690                 if (IS_ERR(rdev)) {
4691                         printk(KERN_WARNING 
4692                                 "md: md_import_device returned %ld\n",
4693                                 PTR_ERR(rdev));
4694                         return PTR_ERR(rdev);
4695                 }
4696                 if (!list_empty(&mddev->disks)) {
4697                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
4698                                                         mdk_rdev_t, same_set);
4699                         int err = super_types[mddev->major_version]
4700                                 .load_super(rdev, rdev0, mddev->minor_version);
4701                         if (err < 0) {
4702                                 printk(KERN_WARNING 
4703                                         "md: %s has different UUID to %s\n",
4704                                         bdevname(rdev->bdev,b), 
4705                                         bdevname(rdev0->bdev,b2));
4706                                 export_rdev(rdev);
4707                                 return -EINVAL;
4708                         }
4709                 }
4710                 err = bind_rdev_to_array(rdev, mddev);
4711                 if (err)
4712                         export_rdev(rdev);
4713                 return err;
4714         }
4715
4716         /*
4717          * add_new_disk can be used once the array is assembled
4718          * to add "hot spares".  They must already have a superblock
4719          * written
4720          */
4721         if (mddev->pers) {
4722                 int err;
4723                 if (!mddev->pers->hot_add_disk) {
4724                         printk(KERN_WARNING 
4725                                 "%s: personality does not support diskops!\n",
4726                                mdname(mddev));
4727                         return -EINVAL;
4728                 }
4729                 if (mddev->persistent)
4730                         rdev = md_import_device(dev, mddev->major_version,
4731                                                 mddev->minor_version);
4732                 else
4733                         rdev = md_import_device(dev, -1, -1);
4734                 if (IS_ERR(rdev)) {
4735                         printk(KERN_WARNING 
4736                                 "md: md_import_device returned %ld\n",
4737                                 PTR_ERR(rdev));
4738                         return PTR_ERR(rdev);
4739                 }
4740                 /* set save_raid_disk if appropriate */
4741                 if (!mddev->persistent) {
4742                         if (info->state & (1<<MD_DISK_SYNC)  &&
4743                             info->raid_disk < mddev->raid_disks)
4744                                 rdev->raid_disk = info->raid_disk;
4745                         else
4746                                 rdev->raid_disk = -1;
4747                 } else
4748                         super_types[mddev->major_version].
4749                                 validate_super(mddev, rdev);
4750                 rdev->saved_raid_disk = rdev->raid_disk;
4751
4752                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
4753                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
4754                         set_bit(WriteMostly, &rdev->flags);
4755                 else
4756                         clear_bit(WriteMostly, &rdev->flags);
4757
4758                 rdev->raid_disk = -1;
4759                 err = bind_rdev_to_array(rdev, mddev);
4760                 if (!err && !mddev->pers->hot_remove_disk) {
4761                         /* If there is hot_add_disk but no hot_remove_disk
4762                          * then added disks for geometry changes,
4763                          * and should be added immediately.
4764                          */
4765                         super_types[mddev->major_version].
4766                                 validate_super(mddev, rdev);
4767                         err = mddev->pers->hot_add_disk(mddev, rdev);
4768                         if (err)
4769                                 unbind_rdev_from_array(rdev);
4770                 }
4771                 if (err)
4772                         export_rdev(rdev);
4773                 else
4774                         sysfs_notify_dirent(rdev->sysfs_state);
4775
4776                 md_update_sb(mddev, 1);
4777                 if (mddev->degraded)
4778                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4779                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4780                 md_wakeup_thread(mddev->thread);
4781                 return err;
4782         }
4783
4784         /* otherwise, add_new_disk is only allowed
4785          * for major_version==0 superblocks
4786          */
4787         if (mddev->major_version != 0) {
4788                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
4789                        mdname(mddev));
4790                 return -EINVAL;
4791         }
4792
4793         if (!(info->state & (1<<MD_DISK_FAULTY))) {
4794                 int err;
4795                 rdev = md_import_device(dev, -1, 0);
4796                 if (IS_ERR(rdev)) {
4797                         printk(KERN_WARNING 
4798                                 "md: error, md_import_device() returned %ld\n",
4799                                 PTR_ERR(rdev));
4800                         return PTR_ERR(rdev);
4801                 }
4802                 rdev->desc_nr = info->number;
4803                 if (info->raid_disk < mddev->raid_disks)
4804                         rdev->raid_disk = info->raid_disk;
4805                 else
4806                         rdev->raid_disk = -1;
4807
4808                 if (rdev->raid_disk < mddev->raid_disks)
4809                         if (info->state & (1<<MD_DISK_SYNC))
4810                                 set_bit(In_sync, &rdev->flags);
4811
4812                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
4813                         set_bit(WriteMostly, &rdev->flags);
4814
4815                 if (!mddev->persistent) {
4816                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
4817                         rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
4818                 } else 
4819                         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
4820                 rdev->sectors = calc_num_sectors(rdev, mddev->chunk_size);
4821
4822                 err = bind_rdev_to_array(rdev, mddev);
4823                 if (err) {
4824                         export_rdev(rdev);
4825                         return err;
4826                 }
4827         }
4828
4829         return 0;
4830 }
4831
4832 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
4833 {
4834         char b[BDEVNAME_SIZE];
4835         mdk_rdev_t *rdev;
4836
4837         rdev = find_rdev(mddev, dev);
4838         if (!rdev)
4839                 return -ENXIO;
4840
4841         if (rdev->raid_disk >= 0)
4842                 goto busy;
4843
4844         kick_rdev_from_array(rdev);
4845         md_update_sb(mddev, 1);
4846         md_new_event(mddev);
4847
4848         return 0;
4849 busy:
4850         printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
4851                 bdevname(rdev->bdev,b), mdname(mddev));
4852         return -EBUSY;
4853 }
4854
4855 static int hot_add_disk(mddev_t * mddev, dev_t dev)
4856 {
4857         char b[BDEVNAME_SIZE];
4858         int err;
4859         mdk_rdev_t *rdev;
4860
4861         if (!mddev->pers)
4862                 return -ENODEV;
4863
4864         if (mddev->major_version != 0) {
4865                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
4866                         " version-0 superblocks.\n",
4867                         mdname(mddev));
4868                 return -EINVAL;
4869         }
4870         if (!mddev->pers->hot_add_disk) {
4871                 printk(KERN_WARNING 
4872                         "%s: personality does not support diskops!\n",
4873                         mdname(mddev));
4874                 return -EINVAL;
4875         }
4876
4877         rdev = md_import_device(dev, -1, 0);
4878         if (IS_ERR(rdev)) {
4879                 printk(KERN_WARNING 
4880                         "md: error, md_import_device() returned %ld\n",
4881                         PTR_ERR(rdev));
4882                 return -EINVAL;
4883         }
4884
4885         if (mddev->persistent)
4886                 rdev->sb_start = calc_dev_sboffset(rdev->bdev);
4887         else
4888                 rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
4889
4890         rdev->sectors = calc_num_sectors(rdev, mddev->chunk_size);
4891
4892         if (test_bit(Faulty, &rdev->flags)) {
4893                 printk(KERN_WARNING 
4894                         "md: can not hot-add faulty %s disk to %s!\n",
4895                         bdevname(rdev->bdev,b), mdname(mddev));
4896                 err = -EINVAL;
4897                 goto abort_export;
4898         }
4899         clear_bit(In_sync, &rdev->flags);
4900         rdev->desc_nr = -1;
4901         rdev->saved_raid_disk = -1;
4902         err = bind_rdev_to_array(rdev, mddev);
4903         if (err)
4904                 goto abort_export;
4905
4906         /*
4907          * The rest should better be atomic, we can have disk failures
4908          * noticed in interrupt contexts ...
4909          */
4910
4911         rdev->raid_disk = -1;
4912
4913         md_update_sb(mddev, 1);
4914
4915         /*
4916          * Kick recovery, maybe this spare has to be added to the
4917          * array immediately.
4918          */
4919         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4920         md_wakeup_thread(mddev->thread);
4921         md_new_event(mddev);
4922         return 0;
4923
4924 abort_export:
4925         export_rdev(rdev);
4926         return err;
4927 }
4928
4929 static int set_bitmap_file(mddev_t *mddev, int fd)
4930 {
4931         int err;
4932
4933         if (mddev->pers) {
4934                 if (!mddev->pers->quiesce)
4935                         return -EBUSY;
4936                 if (mddev->recovery || mddev->sync_thread)
4937                         return -EBUSY;
4938                 /* we should be able to change the bitmap.. */
4939         }
4940
4941
4942         if (fd >= 0) {
4943                 if (mddev->bitmap)
4944                         return -EEXIST; /* cannot add when bitmap is present */
4945                 mddev->bitmap_file = fget(fd);
4946
4947                 if (mddev->bitmap_file == NULL) {
4948                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
4949                                mdname(mddev));
4950                         return -EBADF;
4951                 }
4952
4953                 err = deny_bitmap_write_access(mddev->bitmap_file);
4954                 if (err) {
4955                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
4956                                mdname(mddev));
4957                         fput(mddev->bitmap_file);
4958                         mddev->bitmap_file = NULL;
4959                         return err;
4960                 }
4961                 mddev->bitmap_offset = 0; /* file overrides offset */
4962         } else if (mddev->bitmap == NULL)
4963                 return -ENOENT; /* cannot remove what isn't there */
4964         err = 0;
4965         if (mddev->pers) {
4966                 mddev->pers->quiesce(mddev, 1);
4967                 if (fd >= 0)
4968                         err = bitmap_create(mddev);
4969                 if (fd < 0 || err) {
4970                         bitmap_destroy(mddev);
4971                         fd = -1; /* make sure to put the file */
4972                 }
4973                 mddev->pers->quiesce(mddev, 0);
4974         }
4975         if (fd < 0) {
4976                 if (mddev->bitmap_file) {
4977                         restore_bitmap_write_access(mddev->bitmap_file);
4978                         fput(mddev->bitmap_file);
4979                 }
4980                 mddev->bitmap_file = NULL;
4981         }
4982
4983         return err;
4984 }
4985
4986 /*
4987  * set_array_info is used two different ways
4988  * The original usage is when creating a new array.
4989  * In this usage, raid_disks is > 0 and it together with
4990  *  level, size, not_persistent,layout,chunksize determine the
4991  *  shape of the array.
4992  *  This will always create an array with a type-0.90.0 superblock.
4993  * The newer usage is when assembling an array.
4994  *  In this case raid_disks will be 0, and the major_version field is
4995  *  use to determine which style super-blocks are to be found on the devices.
4996  *  The minor and patch _version numbers are also kept incase the
4997  *  super_block handler wishes to interpret them.
4998  */
4999 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
5000 {
5001
5002         if (info->raid_disks == 0) {
5003                 /* just setting version number for superblock loading */
5004                 if (info->major_version < 0 ||
5005                     info->major_version >= ARRAY_SIZE(super_types) ||
5006                     super_types[info->major_version].name == NULL) {
5007                         /* maybe try to auto-load a module? */
5008                         printk(KERN_INFO 
5009                                 "md: superblock version %d not known\n",
5010                                 info->major_version);
5011                         return -EINVAL;
5012                 }
5013                 mddev->major_version = info->major_version;
5014                 mddev->minor_version = info->minor_version;
5015                 mddev->patch_version = info->patch_version;
5016                 mddev->persistent = !info->not_persistent;
5017                 return 0;
5018         }
5019         mddev->major_version = MD_MAJOR_VERSION;
5020         mddev->minor_version = MD_MINOR_VERSION;
5021         mddev->patch_version = MD_PATCHLEVEL_VERSION;
5022         mddev->ctime         = get_seconds();
5023
5024         mddev->level         = info->level;
5025         mddev->clevel[0]     = 0;
5026         mddev->dev_sectors   = 2 * (sector_t)info->size;
5027         mddev->raid_disks    = info->raid_disks;
5028         /* don't set md_minor, it is determined by which /dev/md* was
5029          * openned
5030          */
5031         if (info->state & (1<<MD_SB_CLEAN))
5032                 mddev->recovery_cp = MaxSector;
5033         else
5034                 mddev->recovery_cp = 0;
5035         mddev->persistent    = ! info->not_persistent;
5036         mddev->external      = 0;
5037
5038         mddev->layout        = info->layout;
5039         mddev->chunk_size    = info->chunk_size;
5040
5041         mddev->max_disks     = MD_SB_DISKS;
5042
5043         if (mddev->persistent)
5044                 mddev->flags         = 0;
5045         set_bit(MD_CHANGE_DEVS, &mddev->flags);
5046
5047         mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
5048         mddev->bitmap_offset = 0;
5049
5050         mddev->reshape_position = MaxSector;
5051
5052         /*
5053          * Generate a 128 bit UUID
5054          */
5055         get_random_bytes(mddev->uuid, 16);
5056
5057         mddev->new_level = mddev->level;
5058         mddev->new_chunk = mddev->chunk_size;
5059         mddev->new_layout = mddev->layout;
5060         mddev->delta_disks = 0;
5061
5062         return 0;
5063 }
5064
5065 void md_set_array_sectors(mddev_t *mddev, sector_t array_sectors)
5066 {
5067         WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
5068
5069         if (mddev->external_size)
5070                 return;
5071
5072         mddev->array_sectors = array_sectors;
5073 }
5074 EXPORT_SYMBOL(md_set_array_sectors);
5075
5076 void md_set_array_sectors_lock(mddev_t *mddev, sector_t array_sectors)
5077 {
5078         mddev_lock(mddev);
5079         md_set_array_sectors(mddev, array_sectors);
5080         mddev_unlock(mddev);
5081 }
5082 EXPORT_SYMBOL(md_set_array_sectors_lock);
5083
5084 static int update_size(mddev_t *mddev, sector_t num_sectors)
5085 {
5086         mdk_rdev_t *rdev;
5087         int rv;
5088         int fit = (num_sectors == 0);
5089
5090         if (mddev->pers->resize == NULL)
5091                 return -EINVAL;
5092         /* The "num_sectors" is the number of sectors of each device that
5093          * is used.  This can only make sense for arrays with redundancy.
5094          * linear and raid0 always use whatever space is available. We can only
5095          * consider changing this number if no resync or reconstruction is
5096          * happening, and if the new size is acceptable. It must fit before the
5097          * sb_start or, if that is <data_offset, it must fit before the size
5098          * of each device.  If num_sectors is zero, we find the largest size
5099          * that fits.
5100
5101          */
5102         if (mddev->sync_thread)
5103                 return -EBUSY;
5104         if (mddev->bitmap)
5105                 /* Sorry, cannot grow a bitmap yet, just remove it,
5106                  * grow, and re-add.
5107                  */
5108                 return -EBUSY;
5109         list_for_each_entry(rdev, &mddev->disks, same_set) {
5110                 sector_t avail = rdev->sectors;
5111
5112                 if (fit && (num_sectors == 0 || num_sectors > avail))
5113                         num_sectors = avail;
5114                 if (avail < num_sectors)
5115                         return -ENOSPC;
5116         }
5117         rv = mddev->pers->resize(mddev, num_sectors);
5118         if (!rv) {
5119                 struct block_device *bdev;
5120
5121                 bdev = bdget_disk(mddev->gendisk, 0);
5122                 if (bdev) {
5123                         mutex_lock(&bdev->bd_inode->i_mutex);
5124                         i_size_write(bdev->bd_inode,
5125                                      (loff_t)mddev->array_sectors << 9);
5126                         mutex_unlock(&bdev->bd_inode->i_mutex);
5127                         bdput(bdev);
5128                 }
5129         }
5130         return rv;
5131 }
5132
5133 static int update_raid_disks(mddev_t *mddev, int raid_disks)
5134 {
5135         int rv;
5136         /* change the number of raid disks */
5137         if (mddev->pers->check_reshape == NULL)
5138                 return -EINVAL;
5139         if (raid_disks <= 0 ||
5140             raid_disks >= mddev->max_disks)
5141                 return -EINVAL;
5142         if (mddev->sync_thread || mddev->reshape_position != MaxSector)
5143                 return -EBUSY;
5144         mddev->delta_disks = raid_disks - mddev->raid_disks;
5145
5146         rv = mddev->pers->check_reshape(mddev);
5147         return rv;
5148 }
5149
5150
5151 /*
5152  * update_array_info is used to change the configuration of an
5153  * on-line array.
5154  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
5155  * fields in the info are checked against the array.
5156  * Any differences that cannot be handled will cause an error.
5157  * Normally, only one change can be managed at a time.
5158  */
5159 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
5160 {
5161         int rv = 0;
5162         int cnt = 0;
5163         int state = 0;
5164
5165         /* calculate expected state,ignoring low bits */
5166         if (mddev->bitmap && mddev->bitmap_offset)
5167                 state |= (1 << MD_SB_BITMAP_PRESENT);
5168
5169         if (mddev->major_version != info->major_version ||
5170             mddev->minor_version != info->minor_version ||
5171 /*          mddev->patch_version != info->patch_version || */
5172             mddev->ctime         != info->ctime         ||
5173             mddev->level         != info->level         ||
5174 /*          mddev->layout        != info->layout        || */
5175             !mddev->persistent   != info->not_persistent||
5176             mddev->chunk_size    != info->chunk_size    ||
5177             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
5178             ((state^info->state) & 0xfffffe00)
5179                 )
5180                 return -EINVAL;
5181         /* Check there is only one change */
5182         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5183                 cnt++;
5184         if (mddev->raid_disks != info->raid_disks)
5185                 cnt++;
5186         if (mddev->layout != info->layout)
5187                 cnt++;
5188         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
5189                 cnt++;
5190         if (cnt == 0)
5191                 return 0;
5192         if (cnt > 1)
5193                 return -EINVAL;
5194
5195         if (mddev->layout != info->layout) {
5196                 /* Change layout
5197                  * we don't need to do anything at the md level, the
5198                  * personality will take care of it all.
5199                  */
5200                 if (mddev->pers->reconfig == NULL)
5201                         return -EINVAL;
5202                 else
5203                         return mddev->pers->reconfig(mddev, info->layout, -1);
5204         }
5205         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5206                 rv = update_size(mddev, (sector_t)info->size * 2);
5207
5208         if (mddev->raid_disks    != info->raid_disks)
5209                 rv = update_raid_disks(mddev, info->raid_disks);
5210
5211         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
5212                 if (mddev->pers->quiesce == NULL)
5213                         return -EINVAL;
5214                 if (mddev->recovery || mddev->sync_thread)
5215                         return -EBUSY;
5216                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
5217                         /* add the bitmap */
5218                         if (mddev->bitmap)
5219                                 return -EEXIST;
5220                         if (mddev->default_bitmap_offset == 0)
5221                                 return -EINVAL;
5222                         mddev->bitmap_offset = mddev->default_bitmap_offset;
5223                         mddev->pers->quiesce(mddev, 1);
5224                         rv = bitmap_create(mddev);
5225                         if (rv)
5226                                 bitmap_destroy(mddev);
5227                         mddev->pers->quiesce(mddev, 0);
5228                 } else {
5229                         /* remove the bitmap */
5230                         if (!mddev->bitmap)
5231                                 return -ENOENT;
5232                         if (mddev->bitmap->file)
5233                                 return -EINVAL;
5234                         mddev->pers->quiesce(mddev, 1);
5235                         bitmap_destroy(mddev);
5236                         mddev->pers->quiesce(mddev, 0);
5237                         mddev->bitmap_offset = 0;
5238                 }
5239         }
5240         md_update_sb(mddev, 1);
5241         return rv;
5242 }
5243
5244 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
5245 {
5246         mdk_rdev_t *rdev;
5247
5248         if (mddev->pers == NULL)
5249                 return -ENODEV;
5250
5251         rdev = find_rdev(mddev, dev);
5252         if (!rdev)
5253                 return -ENODEV;
5254
5255         md_error(mddev, rdev);
5256         return 0;
5257 }
5258
5259 /*
5260  * We have a problem here : there is no easy way to give a CHS
5261  * virtual geometry. We currently pretend that we have a 2 heads
5262  * 4 sectors (with a BIG number of cylinders...). This drives
5263  * dosfs just mad... ;-)
5264  */
5265 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
5266 {
5267         mddev_t *mddev = bdev->bd_disk->private_data;
5268
5269         geo->heads = 2;
5270         geo->sectors = 4;
5271         geo->cylinders = get_capacity(mddev->gendisk) / 8;
5272         return 0;
5273 }
5274
5275 static int md_ioctl(struct block_device *bdev, fmode_t mode,
5276                         unsigned int cmd, unsigned long arg)
5277 {
5278         int err = 0;
5279         void __user *argp = (void __user *)arg;
5280         mddev_t *mddev = NULL;
5281
5282         if (!capable(CAP_SYS_ADMIN))
5283                 return -EACCES;
5284
5285         /*
5286          * Commands dealing with the RAID driver but not any
5287          * particular array:
5288          */
5289         switch (cmd)
5290         {
5291                 case RAID_VERSION:
5292                         err = get_version(argp);
5293                         goto done;
5294
5295                 case PRINT_RAID_DEBUG:
5296                         err = 0;
5297                         md_print_devices();
5298                         goto done;
5299
5300 #ifndef MODULE
5301                 case RAID_AUTORUN:
5302                         err = 0;
5303                         autostart_arrays(arg);
5304                         goto done;
5305 #endif
5306                 default:;
5307         }
5308
5309         /*
5310          * Commands creating/starting a new array:
5311          */
5312
5313         mddev = bdev->bd_disk->private_data;
5314
5315         if (!mddev) {
5316                 BUG();
5317                 goto abort;
5318         }
5319
5320         err = mddev_lock(mddev);
5321         if (err) {
5322                 printk(KERN_INFO 
5323                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
5324                         err, cmd);
5325                 goto abort;
5326         }
5327
5328         switch (cmd)
5329         {
5330                 case SET_ARRAY_INFO:
5331                         {
5332                                 mdu_array_info_t info;
5333                                 if (!arg)
5334                                         memset(&info, 0, sizeof(info));
5335                                 else if (copy_from_user(&info, argp, sizeof(info))) {
5336                                         err = -EFAULT;
5337                                         goto abort_unlock;
5338                                 }
5339                                 if (mddev->pers) {
5340                                         err = update_array_info(mddev, &info);
5341                                         if (err) {
5342                                                 printk(KERN_WARNING "md: couldn't update"
5343                                                        " array info. %d\n", err);
5344                                                 goto abort_unlock;
5345                                         }
5346                                         goto done_unlock;
5347                                 }
5348                                 if (!list_empty(&mddev->disks)) {
5349                                         printk(KERN_WARNING
5350                                                "md: array %s already has disks!\n",
5351                                                mdname(mddev));
5352                                         err = -EBUSY;
5353                                         goto abort_unlock;
5354                                 }
5355                                 if (mddev->raid_disks) {
5356                                         printk(KERN_WARNING
5357                                                "md: array %s already initialised!\n",
5358                                                mdname(mddev));
5359                                         err = -EBUSY;
5360                                         goto abort_unlock;
5361                                 }
5362                                 err = set_array_info(mddev, &info);
5363                                 if (err) {
5364                                         printk(KERN_WARNING "md: couldn't set"
5365                                                " array info. %d\n", err);
5366                                         goto abort_unlock;
5367                                 }
5368                         }
5369                         goto done_unlock;
5370
5371                 default:;
5372         }
5373
5374         /*
5375          * Commands querying/configuring an existing array:
5376          */
5377         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
5378          * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
5379         if ((!mddev->raid_disks && !mddev->external)
5380             && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
5381             && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
5382             && cmd != GET_BITMAP_FILE) {
5383                 err = -ENODEV;
5384                 goto abort_unlock;
5385         }
5386
5387         /*
5388          * Commands even a read-only array can execute:
5389          */
5390         switch (cmd)
5391         {
5392                 case GET_ARRAY_INFO:
5393                         err = get_array_info(mddev, argp);
5394                         goto done_unlock;
5395
5396                 case GET_BITMAP_FILE:
5397                         err = get_bitmap_file(mddev, argp);
5398                         goto done_unlock;
5399
5400                 case GET_DISK_INFO:
5401                         err = get_disk_info(mddev, argp);
5402                         goto done_unlock;
5403
5404                 case RESTART_ARRAY_RW:
5405                         err = restart_array(mddev);
5406                         goto done_unlock;
5407
5408                 case STOP_ARRAY:
5409                         err = do_md_stop(mddev, 0, 1);
5410                         goto done_unlock;
5411
5412                 case STOP_ARRAY_RO:
5413                         err = do_md_stop(mddev, 1, 1);
5414                         goto done_unlock;
5415
5416         }
5417
5418         /*
5419          * The remaining ioctls are changing the state of the
5420          * superblock, so we do not allow them on read-only arrays.
5421          * However non-MD ioctls (e.g. get-size) will still come through
5422          * here and hit the 'default' below, so only disallow
5423          * 'md' ioctls, and switch to rw mode if started auto-readonly.
5424          */
5425         if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
5426                 if (mddev->ro == 2) {
5427                         mddev->ro = 0;
5428                         sysfs_notify_dirent(mddev->sysfs_state);
5429                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5430                         md_wakeup_thread(mddev->thread);
5431                 } else {
5432                         err = -EROFS;
5433                         goto abort_unlock;
5434                 }
5435         }
5436
5437         switch (cmd)
5438         {
5439                 case ADD_NEW_DISK:
5440                 {
5441                         mdu_disk_info_t info;
5442                         if (copy_from_user(&info, argp, sizeof(info)))
5443                                 err = -EFAULT;
5444                         else
5445                                 err = add_new_disk(mddev, &info);
5446                         goto done_unlock;
5447                 }
5448
5449                 case HOT_REMOVE_DISK:
5450                         err = hot_remove_disk(mddev, new_decode_dev(arg));
5451                         goto done_unlock;
5452
5453                 case HOT_ADD_DISK:
5454                         err = hot_add_disk(mddev, new_decode_dev(arg));
5455                         goto done_unlock;
5456
5457                 case SET_DISK_FAULTY:
5458                         err = set_disk_faulty(mddev, new_decode_dev(arg));
5459                         goto done_unlock;
5460
5461                 case RUN_ARRAY:
5462                         err = do_md_run(mddev);
5463                         goto done_unlock;
5464
5465                 case SET_BITMAP_FILE:
5466                         err = set_bitmap_file(mddev, (int)arg);
5467                         goto done_unlock;
5468
5469                 default:
5470                         err = -EINVAL;
5471                         goto abort_unlock;
5472         }
5473
5474 done_unlock:
5475 abort_unlock:
5476         if (mddev->hold_active == UNTIL_IOCTL &&
5477             err != -EINVAL)
5478                 mddev->hold_active = 0;
5479         mddev_unlock(mddev);
5480
5481         return err;
5482 done:
5483         if (err)
5484                 MD_BUG();
5485 abort:
5486         return err;
5487 }
5488
5489 static int md_open(struct block_device *bdev, fmode_t mode)
5490 {
5491         /*
5492          * Succeed if we can lock the mddev, which confirms that
5493          * it isn't being stopped right now.
5494          */
5495         mddev_t *mddev = mddev_find(bdev->bd_dev);
5496         int err;
5497
5498         if (mddev->gendisk != bdev->bd_disk) {
5499                 /* we are racing with mddev_put which is discarding this
5500                  * bd_disk.
5501                  */
5502                 mddev_put(mddev);
5503                 /* Wait until bdev->bd_disk is definitely gone */
5504                 flush_scheduled_work();
5505                 /* Then retry the open from the top */
5506                 return -ERESTARTSYS;
5507         }
5508         BUG_ON(mddev != bdev->bd_disk->private_data);
5509
5510         if ((err = mutex_lock_interruptible_nested(&mddev->reconfig_mutex, 1)))
5511                 goto out;
5512
5513         err = 0;
5514         atomic_inc(&mddev->openers);
5515         mddev_unlock(mddev);
5516
5517         check_disk_change(bdev);
5518  out:
5519         return err;
5520 }
5521
5522 static int md_release(struct gendisk *disk, fmode_t mode)
5523 {
5524         mddev_t *mddev = disk->private_data;
5525
5526         BUG_ON(!mddev);
5527         atomic_dec(&mddev->openers);
5528         mddev_put(mddev);
5529
5530         return 0;
5531 }
5532
5533 static int md_media_changed(struct gendisk *disk)
5534 {
5535         mddev_t *mddev = disk->private_data;
5536
5537         return mddev->changed;
5538 }
5539
5540 static int md_revalidate(struct gendisk *disk)
5541 {
5542         mddev_t *mddev = disk->private_data;
5543
5544         mddev->changed = 0;
5545         return 0;
5546 }
5547 static struct block_device_operations md_fops =
5548 {
5549         .owner          = THIS_MODULE,
5550         .open           = md_open,
5551         .release        = md_release,
5552         .locked_ioctl   = md_ioctl,
5553         .getgeo         = md_getgeo,
5554         .media_changed  = md_media_changed,
5555         .revalidate_disk= md_revalidate,
5556 };
5557
5558 static int md_thread(void * arg)
5559 {
5560         mdk_thread_t *thread = arg;
5561
5562         /*
5563          * md_thread is a 'system-thread', it's priority should be very
5564          * high. We avoid resource deadlocks individually in each
5565          * raid personality. (RAID5 does preallocation) We also use RR and
5566          * the very same RT priority as kswapd, thus we will never get
5567          * into a priority inversion deadlock.
5568          *
5569          * we definitely have to have equal or higher priority than
5570          * bdflush, otherwise bdflush will deadlock if there are too
5571          * many dirty RAID5 blocks.
5572          */
5573
5574         allow_signal(SIGKILL);
5575         while (!kthread_should_stop()) {
5576
5577                 /* We need to wait INTERRUPTIBLE so that
5578                  * we don't add to the load-average.
5579                  * That means we need to be sure no signals are
5580                  * pending
5581                  */
5582                 if (signal_pending(current))
5583                         flush_signals(current);
5584
5585                 wait_event_interruptible_timeout
5586                         (thread->wqueue,
5587                          test_bit(THREAD_WAKEUP, &thread->flags)
5588                          || kthread_should_stop(),
5589                          thread->timeout);
5590
5591                 clear_bit(THREAD_WAKEUP, &thread->flags);
5592
5593                 thread->run(thread->mddev);
5594         }
5595
5596         return 0;
5597 }
5598
5599 void md_wakeup_thread(mdk_thread_t *thread)
5600 {
5601         if (thread) {
5602                 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
5603                 set_bit(THREAD_WAKEUP, &thread->flags);
5604                 wake_up(&thread->wqueue);
5605         }
5606 }
5607
5608 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
5609                                  const char *name)
5610 {
5611         mdk_thread_t *thread;
5612
5613         thread = kzalloc(sizeof(mdk_thread_t), GFP_KERNEL);
5614         if (!thread)
5615                 return NULL;
5616
5617         init_waitqueue_head(&thread->wqueue);
5618
5619         thread->run = run;
5620         thread->mddev = mddev;
5621         thread->timeout = MAX_SCHEDULE_TIMEOUT;
5622         thread->tsk = kthread_run(md_thread, thread, name, mdname(thread->mddev));
5623         if (IS_ERR(thread->tsk)) {
5624                 kfree(thread);
5625                 return NULL;
5626         }
5627         return thread;
5628 }
5629
5630 void md_unregister_thread(mdk_thread_t *thread)
5631 {
5632         if (!thread)
5633                 return;
5634         dprintk("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
5635
5636         kthread_stop(thread->tsk);
5637         kfree(thread);
5638 }
5639
5640 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
5641 {
5642         if (!mddev) {
5643                 MD_BUG();
5644                 return;
5645         }
5646
5647         if (!rdev || test_bit(Faulty, &rdev->flags))
5648                 return;
5649
5650         if (mddev->external)
5651                 set_bit(Blocked, &rdev->flags);
5652 /*
5653         dprintk("md_error dev:%s, rdev:(%d:%d), (caller: %p,%p,%p,%p).\n",
5654                 mdname(mddev),
5655                 MAJOR(rdev->bdev->bd_dev), MINOR(rdev->bdev->bd_dev),
5656                 __builtin_return_address(0),__builtin_return_address(1),
5657                 __builtin_return_address(2),__builtin_return_address(3));
5658 */
5659         if (!mddev->pers)
5660                 return;
5661         if (!mddev->pers->error_handler)
5662                 return;
5663         mddev->pers->error_handler(mddev,rdev);
5664         if (mddev->degraded)
5665                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5666         set_bit(StateChanged, &rdev->flags);
5667         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5668         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5669         md_wakeup_thread(mddev->thread);
5670         md_new_event_inintr(mddev);
5671 }
5672
5673 /* seq_file implementation /proc/mdstat */
5674
5675 static void status_unused(struct seq_file *seq)
5676 {
5677         int i = 0;
5678         mdk_rdev_t *rdev;
5679
5680         seq_printf(seq, "unused devices: ");
5681
5682         list_for_each_entry(rdev, &pending_raid_disks, same_set) {
5683                 char b[BDEVNAME_SIZE];
5684                 i++;
5685                 seq_printf(seq, "%s ",
5686                               bdevname(rdev->bdev,b));
5687         }
5688         if (!i)
5689                 seq_printf(seq, "<none>");
5690
5691         seq_printf(seq, "\n");
5692 }
5693
5694
5695 static void status_resync(struct seq_file *seq, mddev_t * mddev)
5696 {
5697         sector_t max_blocks, resync, res;
5698         unsigned long dt, db, rt;
5699         int scale;
5700         unsigned int per_milli;
5701
5702         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active))/2;
5703
5704         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
5705                 max_blocks = mddev->resync_max_sectors >> 1;
5706         else
5707                 max_blocks = mddev->dev_sectors / 2;
5708
5709         /*
5710          * Should not happen.
5711          */
5712         if (!max_blocks) {
5713                 MD_BUG();
5714                 return;
5715         }
5716         /* Pick 'scale' such that (resync>>scale)*1000 will fit
5717          * in a sector_t, and (max_blocks>>scale) will fit in a
5718          * u32, as those are the requirements for sector_div.
5719          * Thus 'scale' must be at least 10
5720          */
5721         scale = 10;
5722         if (sizeof(sector_t) > sizeof(unsigned long)) {
5723                 while ( max_blocks/2 > (1ULL<<(scale+32)))
5724                         scale++;
5725         }
5726         res = (resync>>scale)*1000;
5727         sector_div(res, (u32)((max_blocks>>scale)+1));
5728
5729         per_milli = res;
5730         {
5731                 int i, x = per_milli/50, y = 20-x;
5732                 seq_printf(seq, "[");
5733                 for (i = 0; i < x; i++)
5734                         seq_printf(seq, "=");
5735                 seq_printf(seq, ">");
5736                 for (i = 0; i < y; i++)
5737                         seq_printf(seq, ".");
5738                 seq_printf(seq, "] ");
5739         }
5740         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
5741                    (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
5742                     "reshape" :
5743                     (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
5744                      "check" :
5745                      (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
5746                       "resync" : "recovery"))),
5747                    per_milli/10, per_milli % 10,
5748                    (unsigned long long) resync,
5749                    (unsigned long long) max_blocks);
5750
5751         /*
5752          * We do not want to overflow, so the order of operands and
5753          * the * 100 / 100 trick are important. We do a +1 to be
5754          * safe against division by zero. We only estimate anyway.
5755          *
5756          * dt: time from mark until now
5757          * db: blocks written from mark until now
5758          * rt: remaining time
5759          */
5760         dt = ((jiffies - mddev->resync_mark) / HZ);
5761         if (!dt) dt++;
5762         db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
5763                 - mddev->resync_mark_cnt;
5764         rt = (dt * ((unsigned long)(max_blocks-resync) / (db/2/100+1)))/100;
5765
5766         seq_printf(seq, " finish=%lu.%lumin", rt / 60, (rt % 60)/6);
5767
5768         seq_printf(seq, " speed=%ldK/sec", db/2/dt);
5769 }
5770
5771 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
5772 {
5773         struct list_head *tmp;
5774         loff_t l = *pos;
5775         mddev_t *mddev;
5776
5777         if (l >= 0x10000)
5778                 return NULL;
5779         if (!l--)
5780                 /* header */
5781                 return (void*)1;
5782
5783         spin_lock(&all_mddevs_lock);
5784         list_for_each(tmp,&all_mddevs)
5785                 if (!l--) {
5786                         mddev = list_entry(tmp, mddev_t, all_mddevs);
5787                         mddev_get(mddev);
5788                         spin_unlock(&all_mddevs_lock);
5789                         return mddev;
5790                 }
5791         spin_unlock(&all_mddevs_lock);
5792         if (!l--)
5793                 return (void*)2;/* tail */
5794         return NULL;
5795 }
5796
5797 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
5798 {
5799         struct list_head *tmp;
5800         mddev_t *next_mddev, *mddev = v;
5801         
5802         ++*pos;
5803         if (v == (void*)2)
5804                 return NULL;
5805
5806         spin_lock(&all_mddevs_lock);
5807         if (v == (void*)1)
5808                 tmp = all_mddevs.next;
5809         else
5810                 tmp = mddev->all_mddevs.next;
5811         if (tmp != &all_mddevs)
5812                 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
5813         else {
5814                 next_mddev = (void*)2;
5815                 *pos = 0x10000;
5816         }               
5817         spin_unlock(&all_mddevs_lock);
5818
5819         if (v != (void*)1)
5820                 mddev_put(mddev);
5821         return next_mddev;
5822
5823 }
5824
5825 static void md_seq_stop(struct seq_file *seq, void *v)
5826 {
5827         mddev_t *mddev = v;
5828
5829         if (mddev && v != (void*)1 && v != (void*)2)
5830                 mddev_put(mddev);
5831 }
5832
5833 struct mdstat_info {
5834         int event;
5835 };
5836
5837 static int md_seq_show(struct seq_file *seq, void *v)
5838 {
5839         mddev_t *mddev = v;
5840         sector_t sectors;
5841         mdk_rdev_t *rdev;
5842         struct mdstat_info *mi = seq->private;
5843         struct bitmap *bitmap;
5844
5845         if (v == (void*)1) {
5846                 struct mdk_personality *pers;
5847                 seq_printf(seq, "Personalities : ");
5848                 spin_lock(&pers_lock);
5849                 list_for_each_entry(pers, &pers_list, list)
5850                         seq_printf(seq, "[%s] ", pers->name);
5851
5852                 spin_unlock(&pers_lock);
5853                 seq_printf(seq, "\n");
5854                 mi->event = atomic_read(&md_event_count);
5855                 return 0;
5856         }
5857         if (v == (void*)2) {
5858                 status_unused(seq);
5859                 return 0;
5860         }
5861
5862         if (mddev_lock(mddev) < 0)
5863                 return -EINTR;
5864
5865         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
5866                 seq_printf(seq, "%s : %sactive", mdname(mddev),
5867                                                 mddev->pers ? "" : "in");
5868                 if (mddev->pers) {
5869                         if (mddev->ro==1)
5870                                 seq_printf(seq, " (read-only)");
5871                         if (mddev->ro==2)
5872                                 seq_printf(seq, " (auto-read-only)");
5873                         seq_printf(seq, " %s", mddev->pers->name);
5874                 }
5875
5876                 sectors = 0;
5877                 list_for_each_entry(rdev, &mddev->disks, same_set) {
5878                         char b[BDEVNAME_SIZE];
5879                         seq_printf(seq, " %s[%d]",
5880                                 bdevname(rdev->bdev,b), rdev->desc_nr);
5881                         if (test_bit(WriteMostly, &rdev->flags))
5882                                 seq_printf(seq, "(W)");
5883                         if (test_bit(Faulty, &rdev->flags)) {
5884                                 seq_printf(seq, "(F)");
5885                                 continue;
5886                         } else if (rdev->raid_disk < 0)
5887                                 seq_printf(seq, "(S)"); /* spare */
5888                         sectors += rdev->sectors;
5889                 }
5890
5891                 if (!list_empty(&mddev->disks)) {
5892                         if (mddev->pers)
5893                                 seq_printf(seq, "\n      %llu blocks",
5894                                            (unsigned long long)
5895                                            mddev->array_sectors / 2);
5896               &