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