8e65986bc63fd06e966de23706c0bc2d7e994d77
[linux-2.6.git] / drivers / md / md.c
1 /*
2    md.c : Multiple Devices driver for Linux
3           Copyright (C) 1998, 1999, 2000 Ingo Molnar
4
5      completely rewritten, based on the MD driver code from Marc Zyngier
6
7    Changes:
8
9    - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
10    - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
11    - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
12    - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
13    - kmod support by: Cyrus Durgin
14    - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
15    - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
16
17    - lots of fixes and improvements to the RAID1/RAID5 and generic
18      RAID code (such as request based resynchronization):
19
20      Neil Brown <neilb@cse.unsw.edu.au>.
21
22    - persistent bitmap code
23      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
24
25    This program is free software; you can redistribute it and/or modify
26    it under the terms of the GNU General Public License as published by
27    the Free Software Foundation; either version 2, or (at your option)
28    any later version.
29
30    You should have received a copy of the GNU General Public License
31    (for example /usr/src/linux/COPYING); if not, write to the Free
32    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 */
34
35 #include <linux/module.h>
36 #include <linux/config.h>
37 #include <linux/kthread.h>
38 #include <linux/linkage.h>
39 #include <linux/raid/md.h>
40 #include <linux/raid/bitmap.h>
41 #include <linux/sysctl.h>
42 #include <linux/devfs_fs_kernel.h>
43 #include <linux/buffer_head.h> /* for invalidate_bdev */
44 #include <linux/suspend.h>
45 #include <linux/poll.h>
46
47 #include <linux/init.h>
48
49 #include <linux/file.h>
50
51 #ifdef CONFIG_KMOD
52 #include <linux/kmod.h>
53 #endif
54
55 #include <asm/unaligned.h>
56
57 #define MAJOR_NR MD_MAJOR
58 #define MD_DRIVER
59
60 /* 63 partitions with the alternate major number (mdp) */
61 #define MdpMinorShift 6
62
63 #define DEBUG 0
64 #define dprintk(x...) ((void)(DEBUG && printk(x)))
65
66
67 #ifndef MODULE
68 static void autostart_arrays (int part);
69 #endif
70
71 static LIST_HEAD(pers_list);
72 static DEFINE_SPINLOCK(pers_lock);
73
74 /*
75  * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
76  * is 1000 KB/sec, so the extra system load does not show up that much.
77  * Increase it if you want to have more _guaranteed_ speed. Note that
78  * the RAID driver will use the maximum available bandwidth if the IO
79  * subsystem is idle. There is also an 'absolute maximum' reconstruction
80  * speed limit - in case reconstruction slows down your system despite
81  * idle IO detection.
82  *
83  * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
84  * or /sys/block/mdX/md/sync_speed_{min,max}
85  */
86
87 static int sysctl_speed_limit_min = 1000;
88 static int sysctl_speed_limit_max = 200000;
89 static inline int speed_min(mddev_t *mddev)
90 {
91         return mddev->sync_speed_min ?
92                 mddev->sync_speed_min : sysctl_speed_limit_min;
93 }
94
95 static inline int speed_max(mddev_t *mddev)
96 {
97         return mddev->sync_speed_max ?
98                 mddev->sync_speed_max : sysctl_speed_limit_max;
99 }
100
101 static struct ctl_table_header *raid_table_header;
102
103 static ctl_table raid_table[] = {
104         {
105                 .ctl_name       = DEV_RAID_SPEED_LIMIT_MIN,
106                 .procname       = "speed_limit_min",
107                 .data           = &sysctl_speed_limit_min,
108                 .maxlen         = sizeof(int),
109                 .mode           = 0644,
110                 .proc_handler   = &proc_dointvec,
111         },
112         {
113                 .ctl_name       = DEV_RAID_SPEED_LIMIT_MAX,
114                 .procname       = "speed_limit_max",
115                 .data           = &sysctl_speed_limit_max,
116                 .maxlen         = sizeof(int),
117                 .mode           = 0644,
118                 .proc_handler   = &proc_dointvec,
119         },
120         { .ctl_name = 0 }
121 };
122
123 static ctl_table raid_dir_table[] = {
124         {
125                 .ctl_name       = DEV_RAID,
126                 .procname       = "raid",
127                 .maxlen         = 0,
128                 .mode           = 0555,
129                 .child          = raid_table,
130         },
131         { .ctl_name = 0 }
132 };
133
134 static ctl_table raid_root_table[] = {
135         {
136                 .ctl_name       = CTL_DEV,
137                 .procname       = "dev",
138                 .maxlen         = 0,
139                 .mode           = 0555,
140                 .child          = raid_dir_table,
141         },
142         { .ctl_name = 0 }
143 };
144
145 static struct block_device_operations md_fops;
146
147 static int start_readonly;
148
149 /*
150  * We have a system wide 'event count' that is incremented
151  * on any 'interesting' event, and readers of /proc/mdstat
152  * can use 'poll' or 'select' to find out when the event
153  * count increases.
154  *
155  * Events are:
156  *  start array, stop array, error, add device, remove device,
157  *  start build, activate spare
158  */
159 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
160 static atomic_t md_event_count;
161 static void md_new_event(mddev_t *mddev)
162 {
163         atomic_inc(&md_event_count);
164         wake_up(&md_event_waiters);
165 }
166
167 /*
168  * Enables to iterate over all existing md arrays
169  * all_mddevs_lock protects this list.
170  */
171 static LIST_HEAD(all_mddevs);
172 static DEFINE_SPINLOCK(all_mddevs_lock);
173
174
175 /*
176  * iterates through all used mddevs in the system.
177  * We take care to grab the all_mddevs_lock whenever navigating
178  * the list, and to always hold a refcount when unlocked.
179  * Any code which breaks out of this loop while own
180  * a reference to the current mddev and must mddev_put it.
181  */
182 #define ITERATE_MDDEV(mddev,tmp)                                        \
183                                                                         \
184         for (({ spin_lock(&all_mddevs_lock);                            \
185                 tmp = all_mddevs.next;                                  \
186                 mddev = NULL;});                                        \
187              ({ if (tmp != &all_mddevs)                                 \
188                         mddev_get(list_entry(tmp, mddev_t, all_mddevs));\
189                 spin_unlock(&all_mddevs_lock);                          \
190                 if (mddev) mddev_put(mddev);                            \
191                 mddev = list_entry(tmp, mddev_t, all_mddevs);           \
192                 tmp != &all_mddevs;});                                  \
193              ({ spin_lock(&all_mddevs_lock);                            \
194                 tmp = tmp->next;})                                      \
195                 )
196
197
198 static int md_fail_request (request_queue_t *q, struct bio *bio)
199 {
200         bio_io_error(bio, bio->bi_size);
201         return 0;
202 }
203
204 static inline mddev_t *mddev_get(mddev_t *mddev)
205 {
206         atomic_inc(&mddev->active);
207         return mddev;
208 }
209
210 static void mddev_put(mddev_t *mddev)
211 {
212         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
213                 return;
214         if (!mddev->raid_disks && list_empty(&mddev->disks)) {
215                 list_del(&mddev->all_mddevs);
216                 /* that blocks */
217                 blk_cleanup_queue(mddev->queue);
218                 /* that also blocks */
219                 kobject_unregister(&mddev->kobj);
220                 /* result blows... */
221         }
222         spin_unlock(&all_mddevs_lock);
223 }
224
225 static mddev_t * mddev_find(dev_t unit)
226 {
227         mddev_t *mddev, *new = NULL;
228
229  retry:
230         spin_lock(&all_mddevs_lock);
231         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
232                 if (mddev->unit == unit) {
233                         mddev_get(mddev);
234                         spin_unlock(&all_mddevs_lock);
235                         kfree(new);
236                         return mddev;
237                 }
238
239         if (new) {
240                 list_add(&new->all_mddevs, &all_mddevs);
241                 spin_unlock(&all_mddevs_lock);
242                 return new;
243         }
244         spin_unlock(&all_mddevs_lock);
245
246         new = kzalloc(sizeof(*new), GFP_KERNEL);
247         if (!new)
248                 return NULL;
249
250         new->unit = unit;
251         if (MAJOR(unit) == MD_MAJOR)
252                 new->md_minor = MINOR(unit);
253         else
254                 new->md_minor = MINOR(unit) >> MdpMinorShift;
255
256         init_MUTEX(&new->reconfig_sem);
257         INIT_LIST_HEAD(&new->disks);
258         INIT_LIST_HEAD(&new->all_mddevs);
259         init_timer(&new->safemode_timer);
260         atomic_set(&new->active, 1);
261         spin_lock_init(&new->write_lock);
262         init_waitqueue_head(&new->sb_wait);
263
264         new->queue = blk_alloc_queue(GFP_KERNEL);
265         if (!new->queue) {
266                 kfree(new);
267                 return NULL;
268         }
269         set_bit(QUEUE_FLAG_CLUSTER, &new->queue->queue_flags);
270
271         blk_queue_make_request(new->queue, md_fail_request);
272
273         goto retry;
274 }
275
276 static inline int mddev_lock(mddev_t * mddev)
277 {
278         return down_interruptible(&mddev->reconfig_sem);
279 }
280
281 static inline void mddev_lock_uninterruptible(mddev_t * mddev)
282 {
283         down(&mddev->reconfig_sem);
284 }
285
286 static inline int mddev_trylock(mddev_t * mddev)
287 {
288         return down_trylock(&mddev->reconfig_sem);
289 }
290
291 static inline void mddev_unlock(mddev_t * mddev)
292 {
293         up(&mddev->reconfig_sem);
294
295         md_wakeup_thread(mddev->thread);
296 }
297
298 static mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
299 {
300         mdk_rdev_t * rdev;
301         struct list_head *tmp;
302
303         ITERATE_RDEV(mddev,rdev,tmp) {
304                 if (rdev->desc_nr == nr)
305                         return rdev;
306         }
307         return NULL;
308 }
309
310 static mdk_rdev_t * find_rdev(mddev_t * mddev, dev_t dev)
311 {
312         struct list_head *tmp;
313         mdk_rdev_t *rdev;
314
315         ITERATE_RDEV(mddev,rdev,tmp) {
316                 if (rdev->bdev->bd_dev == dev)
317                         return rdev;
318         }
319         return NULL;
320 }
321
322 static struct mdk_personality *find_pers(int level, char *clevel)
323 {
324         struct mdk_personality *pers;
325         list_for_each_entry(pers, &pers_list, list) {
326                 if (level != LEVEL_NONE && pers->level == level)
327                         return pers;
328                 if (strcmp(pers->name, clevel)==0)
329                         return pers;
330         }
331         return NULL;
332 }
333
334 static inline sector_t calc_dev_sboffset(struct block_device *bdev)
335 {
336         sector_t size = bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
337         return MD_NEW_SIZE_BLOCKS(size);
338 }
339
340 static sector_t calc_dev_size(mdk_rdev_t *rdev, unsigned chunk_size)
341 {
342         sector_t size;
343
344         size = rdev->sb_offset;
345
346         if (chunk_size)
347                 size &= ~((sector_t)chunk_size/1024 - 1);
348         return size;
349 }
350
351 static int alloc_disk_sb(mdk_rdev_t * rdev)
352 {
353         if (rdev->sb_page)
354                 MD_BUG();
355
356         rdev->sb_page = alloc_page(GFP_KERNEL);
357         if (!rdev->sb_page) {
358                 printk(KERN_ALERT "md: out of memory.\n");
359                 return -EINVAL;
360         }
361
362         return 0;
363 }
364
365 static void free_disk_sb(mdk_rdev_t * rdev)
366 {
367         if (rdev->sb_page) {
368                 put_page(rdev->sb_page);
369                 rdev->sb_loaded = 0;
370                 rdev->sb_page = NULL;
371                 rdev->sb_offset = 0;
372                 rdev->size = 0;
373         }
374 }
375
376
377 static int super_written(struct bio *bio, unsigned int bytes_done, int error)
378 {
379         mdk_rdev_t *rdev = bio->bi_private;
380         mddev_t *mddev = rdev->mddev;
381         if (bio->bi_size)
382                 return 1;
383
384         if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags))
385                 md_error(mddev, rdev);
386
387         if (atomic_dec_and_test(&mddev->pending_writes))
388                 wake_up(&mddev->sb_wait);
389         bio_put(bio);
390         return 0;
391 }
392
393 static int super_written_barrier(struct bio *bio, unsigned int bytes_done, int error)
394 {
395         struct bio *bio2 = bio->bi_private;
396         mdk_rdev_t *rdev = bio2->bi_private;
397         mddev_t *mddev = rdev->mddev;
398         if (bio->bi_size)
399                 return 1;
400
401         if (!test_bit(BIO_UPTODATE, &bio->bi_flags) &&
402             error == -EOPNOTSUPP) {
403                 unsigned long flags;
404                 /* barriers don't appear to be supported :-( */
405                 set_bit(BarriersNotsupp, &rdev->flags);
406                 mddev->barriers_work = 0;
407                 spin_lock_irqsave(&mddev->write_lock, flags);
408                 bio2->bi_next = mddev->biolist;
409                 mddev->biolist = bio2;
410                 spin_unlock_irqrestore(&mddev->write_lock, flags);
411                 wake_up(&mddev->sb_wait);
412                 bio_put(bio);
413                 return 0;
414         }
415         bio_put(bio2);
416         bio->bi_private = rdev;
417         return super_written(bio, bytes_done, error);
418 }
419
420 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
421                    sector_t sector, int size, struct page *page)
422 {
423         /* write first size bytes of page to sector of rdev
424          * Increment mddev->pending_writes before returning
425          * and decrement it on completion, waking up sb_wait
426          * if zero is reached.
427          * If an error occurred, call md_error
428          *
429          * As we might need to resubmit the request if BIO_RW_BARRIER
430          * causes ENOTSUPP, we allocate a spare bio...
431          */
432         struct bio *bio = bio_alloc(GFP_NOIO, 1);
433         int rw = (1<<BIO_RW) | (1<<BIO_RW_SYNC);
434
435         bio->bi_bdev = rdev->bdev;
436         bio->bi_sector = sector;
437         bio_add_page(bio, page, size, 0);
438         bio->bi_private = rdev;
439         bio->bi_end_io = super_written;
440         bio->bi_rw = rw;
441
442         atomic_inc(&mddev->pending_writes);
443         if (!test_bit(BarriersNotsupp, &rdev->flags)) {
444                 struct bio *rbio;
445                 rw |= (1<<BIO_RW_BARRIER);
446                 rbio = bio_clone(bio, GFP_NOIO);
447                 rbio->bi_private = bio;
448                 rbio->bi_end_io = super_written_barrier;
449                 submit_bio(rw, rbio);
450         } else
451                 submit_bio(rw, bio);
452 }
453
454 void md_super_wait(mddev_t *mddev)
455 {
456         /* wait for all superblock writes that were scheduled to complete.
457          * if any had to be retried (due to BARRIER problems), retry them
458          */
459         DEFINE_WAIT(wq);
460         for(;;) {
461                 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
462                 if (atomic_read(&mddev->pending_writes)==0)
463                         break;
464                 while (mddev->biolist) {
465                         struct bio *bio;
466                         spin_lock_irq(&mddev->write_lock);
467                         bio = mddev->biolist;
468                         mddev->biolist = bio->bi_next ;
469                         bio->bi_next = NULL;
470                         spin_unlock_irq(&mddev->write_lock);
471                         submit_bio(bio->bi_rw, bio);
472                 }
473                 schedule();
474         }
475         finish_wait(&mddev->sb_wait, &wq);
476 }
477
478 static int bi_complete(struct bio *bio, unsigned int bytes_done, int error)
479 {
480         if (bio->bi_size)
481                 return 1;
482
483         complete((struct completion*)bio->bi_private);
484         return 0;
485 }
486
487 int sync_page_io(struct block_device *bdev, sector_t sector, int size,
488                    struct page *page, int rw)
489 {
490         struct bio *bio = bio_alloc(GFP_NOIO, 1);
491         struct completion event;
492         int ret;
493
494         rw |= (1 << BIO_RW_SYNC);
495
496         bio->bi_bdev = bdev;
497         bio->bi_sector = sector;
498         bio_add_page(bio, page, size, 0);
499         init_completion(&event);
500         bio->bi_private = &event;
501         bio->bi_end_io = bi_complete;
502         submit_bio(rw, bio);
503         wait_for_completion(&event);
504
505         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
506         bio_put(bio);
507         return ret;
508 }
509 EXPORT_SYMBOL_GPL(sync_page_io);
510
511 static int read_disk_sb(mdk_rdev_t * rdev, int size)
512 {
513         char b[BDEVNAME_SIZE];
514         if (!rdev->sb_page) {
515                 MD_BUG();
516                 return -EINVAL;
517         }
518         if (rdev->sb_loaded)
519                 return 0;
520
521
522         if (!sync_page_io(rdev->bdev, rdev->sb_offset<<1, size, rdev->sb_page, READ))
523                 goto fail;
524         rdev->sb_loaded = 1;
525         return 0;
526
527 fail:
528         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
529                 bdevname(rdev->bdev,b));
530         return -EINVAL;
531 }
532
533 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
534 {
535         if (    (sb1->set_uuid0 == sb2->set_uuid0) &&
536                 (sb1->set_uuid1 == sb2->set_uuid1) &&
537                 (sb1->set_uuid2 == sb2->set_uuid2) &&
538                 (sb1->set_uuid3 == sb2->set_uuid3))
539
540                 return 1;
541
542         return 0;
543 }
544
545
546 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
547 {
548         int ret;
549         mdp_super_t *tmp1, *tmp2;
550
551         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
552         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
553
554         if (!tmp1 || !tmp2) {
555                 ret = 0;
556                 printk(KERN_INFO "md.c: sb1 is not equal to sb2!\n");
557                 goto abort;
558         }
559
560         *tmp1 = *sb1;
561         *tmp2 = *sb2;
562
563         /*
564          * nr_disks is not constant
565          */
566         tmp1->nr_disks = 0;
567         tmp2->nr_disks = 0;
568
569         if (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4))
570                 ret = 0;
571         else
572                 ret = 1;
573
574 abort:
575         kfree(tmp1);
576         kfree(tmp2);
577         return ret;
578 }
579
580 static unsigned int calc_sb_csum(mdp_super_t * sb)
581 {
582         unsigned int disk_csum, csum;
583
584         disk_csum = sb->sb_csum;
585         sb->sb_csum = 0;
586         csum = csum_partial((void *)sb, MD_SB_BYTES, 0);
587         sb->sb_csum = disk_csum;
588         return csum;
589 }
590
591
592 /*
593  * Handle superblock details.
594  * We want to be able to handle multiple superblock formats
595  * so we have a common interface to them all, and an array of
596  * different handlers.
597  * We rely on user-space to write the initial superblock, and support
598  * reading and updating of superblocks.
599  * Interface methods are:
600  *   int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
601  *      loads and validates a superblock on dev.
602  *      if refdev != NULL, compare superblocks on both devices
603  *    Return:
604  *      0 - dev has a superblock that is compatible with refdev
605  *      1 - dev has a superblock that is compatible and newer than refdev
606  *          so dev should be used as the refdev in future
607  *     -EINVAL superblock incompatible or invalid
608  *     -othererror e.g. -EIO
609  *
610  *   int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
611  *      Verify that dev is acceptable into mddev.
612  *       The first time, mddev->raid_disks will be 0, and data from
613  *       dev should be merged in.  Subsequent calls check that dev
614  *       is new enough.  Return 0 or -EINVAL
615  *
616  *   void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
617  *     Update the superblock for rdev with data in mddev
618  *     This does not write to disc.
619  *
620  */
621
622 struct super_type  {
623         char            *name;
624         struct module   *owner;
625         int             (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version);
626         int             (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
627         void            (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
628 };
629
630 /*
631  * load_super for 0.90.0 
632  */
633 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
634 {
635         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
636         mdp_super_t *sb;
637         int ret;
638         sector_t sb_offset;
639
640         /*
641          * Calculate the position of the superblock,
642          * it's at the end of the disk.
643          *
644          * It also happens to be a multiple of 4Kb.
645          */
646         sb_offset = calc_dev_sboffset(rdev->bdev);
647         rdev->sb_offset = sb_offset;
648
649         ret = read_disk_sb(rdev, MD_SB_BYTES);
650         if (ret) return ret;
651
652         ret = -EINVAL;
653
654         bdevname(rdev->bdev, b);
655         sb = (mdp_super_t*)page_address(rdev->sb_page);
656
657         if (sb->md_magic != MD_SB_MAGIC) {
658                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
659                        b);
660                 goto abort;
661         }
662
663         if (sb->major_version != 0 ||
664             sb->minor_version != 90) {
665                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
666                         sb->major_version, sb->minor_version,
667                         b);
668                 goto abort;
669         }
670
671         if (sb->raid_disks <= 0)
672                 goto abort;
673
674         if (csum_fold(calc_sb_csum(sb)) != csum_fold(sb->sb_csum)) {
675                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
676                         b);
677                 goto abort;
678         }
679
680         rdev->preferred_minor = sb->md_minor;
681         rdev->data_offset = 0;
682         rdev->sb_size = MD_SB_BYTES;
683
684         if (sb->level == LEVEL_MULTIPATH)
685                 rdev->desc_nr = -1;
686         else
687                 rdev->desc_nr = sb->this_disk.number;
688
689         if (refdev == 0)
690                 ret = 1;
691         else {
692                 __u64 ev1, ev2;
693                 mdp_super_t *refsb = (mdp_super_t*)page_address(refdev->sb_page);
694                 if (!uuid_equal(refsb, sb)) {
695                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
696                                 b, bdevname(refdev->bdev,b2));
697                         goto abort;
698                 }
699                 if (!sb_equal(refsb, sb)) {
700                         printk(KERN_WARNING "md: %s has same UUID"
701                                " but different superblock to %s\n",
702                                b, bdevname(refdev->bdev, b2));
703                         goto abort;
704                 }
705                 ev1 = md_event(sb);
706                 ev2 = md_event(refsb);
707                 if (ev1 > ev2)
708                         ret = 1;
709                 else 
710                         ret = 0;
711         }
712         rdev->size = calc_dev_size(rdev, sb->chunk_size);
713
714         if (rdev->size < sb->size && sb->level > 1)
715                 /* "this cannot possibly happen" ... */
716                 ret = -EINVAL;
717
718  abort:
719         return ret;
720 }
721
722 /*
723  * validate_super for 0.90.0
724  */
725 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
726 {
727         mdp_disk_t *desc;
728         mdp_super_t *sb = (mdp_super_t *)page_address(rdev->sb_page);
729
730         rdev->raid_disk = -1;
731         rdev->flags = 0;
732         if (mddev->raid_disks == 0) {
733                 mddev->major_version = 0;
734                 mddev->minor_version = sb->minor_version;
735                 mddev->patch_version = sb->patch_version;
736                 mddev->persistent = ! sb->not_persistent;
737                 mddev->chunk_size = sb->chunk_size;
738                 mddev->ctime = sb->ctime;
739                 mddev->utime = sb->utime;
740                 mddev->level = sb->level;
741                 mddev->clevel[0] = 0;
742                 mddev->layout = sb->layout;
743                 mddev->raid_disks = sb->raid_disks;
744                 mddev->size = sb->size;
745                 mddev->events = md_event(sb);
746                 mddev->bitmap_offset = 0;
747                 mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
748
749                 if (sb->state & (1<<MD_SB_CLEAN))
750                         mddev->recovery_cp = MaxSector;
751                 else {
752                         if (sb->events_hi == sb->cp_events_hi && 
753                                 sb->events_lo == sb->cp_events_lo) {
754                                 mddev->recovery_cp = sb->recovery_cp;
755                         } else
756                                 mddev->recovery_cp = 0;
757                 }
758
759                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
760                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
761                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
762                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
763
764                 mddev->max_disks = MD_SB_DISKS;
765
766                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
767                     mddev->bitmap_file == NULL) {
768                         if (mddev->level != 1 && mddev->level != 4
769                             && mddev->level != 5 && mddev->level != 6
770                             && mddev->level != 10) {
771                                 /* FIXME use a better test */
772                                 printk(KERN_WARNING "md: bitmaps not supported for this level.\n");
773                                 return -EINVAL;
774                         }
775                         mddev->bitmap_offset = mddev->default_bitmap_offset;
776                 }
777
778         } else if (mddev->pers == NULL) {
779                 /* Insist on good event counter while assembling */
780                 __u64 ev1 = md_event(sb);
781                 ++ev1;
782                 if (ev1 < mddev->events) 
783                         return -EINVAL;
784         } else if (mddev->bitmap) {
785                 /* if adding to array with a bitmap, then we can accept an
786                  * older device ... but not too old.
787                  */
788                 __u64 ev1 = md_event(sb);
789                 if (ev1 < mddev->bitmap->events_cleared)
790                         return 0;
791         } else /* just a hot-add of a new device, leave raid_disk at -1 */
792                 return 0;
793
794         if (mddev->level != LEVEL_MULTIPATH) {
795                 desc = sb->disks + rdev->desc_nr;
796
797                 if (desc->state & (1<<MD_DISK_FAULTY))
798                         set_bit(Faulty, &rdev->flags);
799                 else if (desc->state & (1<<MD_DISK_SYNC) &&
800                          desc->raid_disk < mddev->raid_disks) {
801                         set_bit(In_sync, &rdev->flags);
802                         rdev->raid_disk = desc->raid_disk;
803                 }
804                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
805                         set_bit(WriteMostly, &rdev->flags);
806         } else /* MULTIPATH are always insync */
807                 set_bit(In_sync, &rdev->flags);
808         return 0;
809 }
810
811 /*
812  * sync_super for 0.90.0
813  */
814 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
815 {
816         mdp_super_t *sb;
817         struct list_head *tmp;
818         mdk_rdev_t *rdev2;
819         int next_spare = mddev->raid_disks;
820
821
822         /* make rdev->sb match mddev data..
823          *
824          * 1/ zero out disks
825          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
826          * 3/ any empty disks < next_spare become removed
827          *
828          * disks[0] gets initialised to REMOVED because
829          * we cannot be sure from other fields if it has
830          * been initialised or not.
831          */
832         int i;
833         int active=0, working=0,failed=0,spare=0,nr_disks=0;
834
835         rdev->sb_size = MD_SB_BYTES;
836
837         sb = (mdp_super_t*)page_address(rdev->sb_page);
838
839         memset(sb, 0, sizeof(*sb));
840
841         sb->md_magic = MD_SB_MAGIC;
842         sb->major_version = mddev->major_version;
843         sb->minor_version = mddev->minor_version;
844         sb->patch_version = mddev->patch_version;
845         sb->gvalid_words  = 0; /* ignored */
846         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
847         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
848         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
849         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
850
851         sb->ctime = mddev->ctime;
852         sb->level = mddev->level;
853         sb->size  = mddev->size;
854         sb->raid_disks = mddev->raid_disks;
855         sb->md_minor = mddev->md_minor;
856         sb->not_persistent = !mddev->persistent;
857         sb->utime = mddev->utime;
858         sb->state = 0;
859         sb->events_hi = (mddev->events>>32);
860         sb->events_lo = (u32)mddev->events;
861
862         if (mddev->in_sync)
863         {
864                 sb->recovery_cp = mddev->recovery_cp;
865                 sb->cp_events_hi = (mddev->events>>32);
866                 sb->cp_events_lo = (u32)mddev->events;
867                 if (mddev->recovery_cp == MaxSector)
868                         sb->state = (1<< MD_SB_CLEAN);
869         } else
870                 sb->recovery_cp = 0;
871
872         sb->layout = mddev->layout;
873         sb->chunk_size = mddev->chunk_size;
874
875         if (mddev->bitmap && mddev->bitmap_file == NULL)
876                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
877
878         sb->disks[0].state = (1<<MD_DISK_REMOVED);
879         ITERATE_RDEV(mddev,rdev2,tmp) {
880                 mdp_disk_t *d;
881                 int desc_nr;
882                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
883                     && !test_bit(Faulty, &rdev2->flags))
884                         desc_nr = rdev2->raid_disk;
885                 else
886                         desc_nr = next_spare++;
887                 rdev2->desc_nr = desc_nr;
888                 d = &sb->disks[rdev2->desc_nr];
889                 nr_disks++;
890                 d->number = rdev2->desc_nr;
891                 d->major = MAJOR(rdev2->bdev->bd_dev);
892                 d->minor = MINOR(rdev2->bdev->bd_dev);
893                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
894                     && !test_bit(Faulty, &rdev2->flags))
895                         d->raid_disk = rdev2->raid_disk;
896                 else
897                         d->raid_disk = rdev2->desc_nr; /* compatibility */
898                 if (test_bit(Faulty, &rdev2->flags))
899                         d->state = (1<<MD_DISK_FAULTY);
900                 else if (test_bit(In_sync, &rdev2->flags)) {
901                         d->state = (1<<MD_DISK_ACTIVE);
902                         d->state |= (1<<MD_DISK_SYNC);
903                         active++;
904                         working++;
905                 } else {
906                         d->state = 0;
907                         spare++;
908                         working++;
909                 }
910                 if (test_bit(WriteMostly, &rdev2->flags))
911                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
912         }
913         /* now set the "removed" and "faulty" bits on any missing devices */
914         for (i=0 ; i < mddev->raid_disks ; i++) {
915                 mdp_disk_t *d = &sb->disks[i];
916                 if (d->state == 0 && d->number == 0) {
917                         d->number = i;
918                         d->raid_disk = i;
919                         d->state = (1<<MD_DISK_REMOVED);
920                         d->state |= (1<<MD_DISK_FAULTY);
921                         failed++;
922                 }
923         }
924         sb->nr_disks = nr_disks;
925         sb->active_disks = active;
926         sb->working_disks = working;
927         sb->failed_disks = failed;
928         sb->spare_disks = spare;
929
930         sb->this_disk = sb->disks[rdev->desc_nr];
931         sb->sb_csum = calc_sb_csum(sb);
932 }
933
934 /*
935  * version 1 superblock
936  */
937
938 static unsigned int calc_sb_1_csum(struct mdp_superblock_1 * sb)
939 {
940         unsigned int disk_csum, csum;
941         unsigned long long newcsum;
942         int size = 256 + le32_to_cpu(sb->max_dev)*2;
943         unsigned int *isuper = (unsigned int*)sb;
944         int i;
945
946         disk_csum = sb->sb_csum;
947         sb->sb_csum = 0;
948         newcsum = 0;
949         for (i=0; size>=4; size -= 4 )
950                 newcsum += le32_to_cpu(*isuper++);
951
952         if (size == 2)
953                 newcsum += le16_to_cpu(*(unsigned short*) isuper);
954
955         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
956         sb->sb_csum = disk_csum;
957         return cpu_to_le32(csum);
958 }
959
960 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
961 {
962         struct mdp_superblock_1 *sb;
963         int ret;
964         sector_t sb_offset;
965         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
966         int bmask;
967
968         /*
969          * Calculate the position of the superblock.
970          * It is always aligned to a 4K boundary and
971          * depeding on minor_version, it can be:
972          * 0: At least 8K, but less than 12K, from end of device
973          * 1: At start of device
974          * 2: 4K from start of device.
975          */
976         switch(minor_version) {
977         case 0:
978                 sb_offset = rdev->bdev->bd_inode->i_size >> 9;
979                 sb_offset -= 8*2;
980                 sb_offset &= ~(sector_t)(4*2-1);
981                 /* convert from sectors to K */
982                 sb_offset /= 2;
983                 break;
984         case 1:
985                 sb_offset = 0;
986                 break;
987         case 2:
988                 sb_offset = 4;
989                 break;
990         default:
991                 return -EINVAL;
992         }
993         rdev->sb_offset = sb_offset;
994
995         /* superblock is rarely larger than 1K, but it can be larger,
996          * and it is safe to read 4k, so we do that
997          */
998         ret = read_disk_sb(rdev, 4096);
999         if (ret) return ret;
1000
1001
1002         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1003
1004         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1005             sb->major_version != cpu_to_le32(1) ||
1006             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1007             le64_to_cpu(sb->super_offset) != (rdev->sb_offset<<1) ||
1008             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1009                 return -EINVAL;
1010
1011         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1012                 printk("md: invalid superblock checksum on %s\n",
1013                         bdevname(rdev->bdev,b));
1014                 return -EINVAL;
1015         }
1016         if (le64_to_cpu(sb->data_size) < 10) {
1017                 printk("md: data_size too small on %s\n",
1018                        bdevname(rdev->bdev,b));
1019                 return -EINVAL;
1020         }
1021         rdev->preferred_minor = 0xffff;
1022         rdev->data_offset = le64_to_cpu(sb->data_offset);
1023         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1024
1025         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1026         bmask = queue_hardsect_size(rdev->bdev->bd_disk->queue)-1;
1027         if (rdev->sb_size & bmask)
1028                 rdev-> sb_size = (rdev->sb_size | bmask)+1;
1029
1030         if (refdev == 0)
1031                 ret = 1;
1032         else {
1033                 __u64 ev1, ev2;
1034                 struct mdp_superblock_1 *refsb = 
1035                         (struct mdp_superblock_1*)page_address(refdev->sb_page);
1036
1037                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1038                     sb->level != refsb->level ||
1039                     sb->layout != refsb->layout ||
1040                     sb->chunksize != refsb->chunksize) {
1041                         printk(KERN_WARNING "md: %s has strangely different"
1042                                 " superblock to %s\n",
1043                                 bdevname(rdev->bdev,b),
1044                                 bdevname(refdev->bdev,b2));
1045                         return -EINVAL;
1046                 }
1047                 ev1 = le64_to_cpu(sb->events);
1048                 ev2 = le64_to_cpu(refsb->events);
1049
1050                 if (ev1 > ev2)
1051                         ret = 1;
1052                 else
1053                         ret = 0;
1054         }
1055         if (minor_version) 
1056                 rdev->size = ((rdev->bdev->bd_inode->i_size>>9) - le64_to_cpu(sb->data_offset)) / 2;
1057         else
1058                 rdev->size = rdev->sb_offset;
1059         if (rdev->size < le64_to_cpu(sb->data_size)/2)
1060                 return -EINVAL;
1061         rdev->size = le64_to_cpu(sb->data_size)/2;
1062         if (le32_to_cpu(sb->chunksize))
1063                 rdev->size &= ~((sector_t)le32_to_cpu(sb->chunksize)/2 - 1);
1064
1065         if (le32_to_cpu(sb->size) > rdev->size*2)
1066                 return -EINVAL;
1067         return ret;
1068 }
1069
1070 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1071 {
1072         struct mdp_superblock_1 *sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1073
1074         rdev->raid_disk = -1;
1075         rdev->flags = 0;
1076         if (mddev->raid_disks == 0) {
1077                 mddev->major_version = 1;
1078                 mddev->patch_version = 0;
1079                 mddev->persistent = 1;
1080                 mddev->chunk_size = le32_to_cpu(sb->chunksize) << 9;
1081                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1082                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1083                 mddev->level = le32_to_cpu(sb->level);
1084                 mddev->clevel[0] = 0;
1085                 mddev->layout = le32_to_cpu(sb->layout);
1086                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1087                 mddev->size = le64_to_cpu(sb->size)/2;
1088                 mddev->events = le64_to_cpu(sb->events);
1089                 mddev->bitmap_offset = 0;
1090                 mddev->default_bitmap_offset = 1024 >> 9;
1091                 
1092                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1093                 memcpy(mddev->uuid, sb->set_uuid, 16);
1094
1095                 mddev->max_disks =  (4096-256)/2;
1096
1097                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1098                     mddev->bitmap_file == NULL ) {
1099                         if (mddev->level != 1 && mddev->level != 5 && mddev->level != 6
1100                             && mddev->level != 10) {
1101                                 printk(KERN_WARNING "md: bitmaps not supported for this level.\n");
1102                                 return -EINVAL;
1103                         }
1104                         mddev->bitmap_offset = (__s32)le32_to_cpu(sb->bitmap_offset);
1105                 }
1106         } else if (mddev->pers == NULL) {
1107                 /* Insist of good event counter while assembling */
1108                 __u64 ev1 = le64_to_cpu(sb->events);
1109                 ++ev1;
1110                 if (ev1 < mddev->events)
1111                         return -EINVAL;
1112         } else if (mddev->bitmap) {
1113                 /* If adding to array with a bitmap, then we can accept an
1114                  * older device, but not too old.
1115                  */
1116                 __u64 ev1 = le64_to_cpu(sb->events);
1117                 if (ev1 < mddev->bitmap->events_cleared)
1118                         return 0;
1119         } else /* just a hot-add of a new device, leave raid_disk at -1 */
1120                 return 0;
1121
1122         if (mddev->level != LEVEL_MULTIPATH) {
1123                 int role;
1124                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1125                 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1126                 switch(role) {
1127                 case 0xffff: /* spare */
1128                         break;
1129                 case 0xfffe: /* faulty */
1130                         set_bit(Faulty, &rdev->flags);
1131                         break;
1132                 default:
1133                         set_bit(In_sync, &rdev->flags);
1134                         rdev->raid_disk = role;
1135                         break;
1136                 }
1137                 if (sb->devflags & WriteMostly1)
1138                         set_bit(WriteMostly, &rdev->flags);
1139         } else /* MULTIPATH are always insync */
1140                 set_bit(In_sync, &rdev->flags);
1141
1142         return 0;
1143 }
1144
1145 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1146 {
1147         struct mdp_superblock_1 *sb;
1148         struct list_head *tmp;
1149         mdk_rdev_t *rdev2;
1150         int max_dev, i;
1151         /* make rdev->sb match mddev and rdev data. */
1152
1153         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1154
1155         sb->feature_map = 0;
1156         sb->pad0 = 0;
1157         memset(sb->pad1, 0, sizeof(sb->pad1));
1158         memset(sb->pad2, 0, sizeof(sb->pad2));
1159         memset(sb->pad3, 0, sizeof(sb->pad3));
1160
1161         sb->utime = cpu_to_le64((__u64)mddev->utime);
1162         sb->events = cpu_to_le64(mddev->events);
1163         if (mddev->in_sync)
1164                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1165         else
1166                 sb->resync_offset = cpu_to_le64(0);
1167
1168         sb->cnt_corrected_read = atomic_read(&rdev->corrected_errors);
1169
1170         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1171         sb->size = cpu_to_le64(mddev->size<<1);
1172
1173         if (mddev->bitmap && mddev->bitmap_file == NULL) {
1174                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_offset);
1175                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1176         }
1177
1178         max_dev = 0;
1179         ITERATE_RDEV(mddev,rdev2,tmp)
1180                 if (rdev2->desc_nr+1 > max_dev)
1181                         max_dev = rdev2->desc_nr+1;
1182         
1183         sb->max_dev = cpu_to_le32(max_dev);
1184         for (i=0; i<max_dev;i++)
1185                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1186         
1187         ITERATE_RDEV(mddev,rdev2,tmp) {
1188                 i = rdev2->desc_nr;
1189                 if (test_bit(Faulty, &rdev2->flags))
1190                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1191                 else if (test_bit(In_sync, &rdev2->flags))
1192                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1193                 else
1194                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1195         }
1196
1197         sb->recovery_offset = cpu_to_le64(0); /* not supported yet */
1198         sb->sb_csum = calc_sb_1_csum(sb);
1199 }
1200
1201
1202 static struct super_type super_types[] = {
1203         [0] = {
1204                 .name   = "0.90.0",
1205                 .owner  = THIS_MODULE,
1206                 .load_super     = super_90_load,
1207                 .validate_super = super_90_validate,
1208                 .sync_super     = super_90_sync,
1209         },
1210         [1] = {
1211                 .name   = "md-1",
1212                 .owner  = THIS_MODULE,
1213                 .load_super     = super_1_load,
1214                 .validate_super = super_1_validate,
1215                 .sync_super     = super_1_sync,
1216         },
1217 };
1218         
1219 static mdk_rdev_t * match_dev_unit(mddev_t *mddev, mdk_rdev_t *dev)
1220 {
1221         struct list_head *tmp;
1222         mdk_rdev_t *rdev;
1223
1224         ITERATE_RDEV(mddev,rdev,tmp)
1225                 if (rdev->bdev->bd_contains == dev->bdev->bd_contains)
1226                         return rdev;
1227
1228         return NULL;
1229 }
1230
1231 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1232 {
1233         struct list_head *tmp;
1234         mdk_rdev_t *rdev;
1235
1236         ITERATE_RDEV(mddev1,rdev,tmp)
1237                 if (match_dev_unit(mddev2, rdev))
1238                         return 1;
1239
1240         return 0;
1241 }
1242
1243 static LIST_HEAD(pending_raid_disks);
1244
1245 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1246 {
1247         mdk_rdev_t *same_pdev;
1248         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1249         struct kobject *ko;
1250         char *s;
1251
1252         if (rdev->mddev) {
1253                 MD_BUG();
1254                 return -EINVAL;
1255         }
1256         /* make sure rdev->size exceeds mddev->size */
1257         if (rdev->size && (mddev->size == 0 || rdev->size < mddev->size)) {
1258                 if (mddev->pers)
1259                         /* Cannot change size, so fail */
1260                         return -ENOSPC;
1261                 else
1262                         mddev->size = rdev->size;
1263         }
1264         same_pdev = match_dev_unit(mddev, rdev);
1265         if (same_pdev)
1266                 printk(KERN_WARNING
1267                         "%s: WARNING: %s appears to be on the same physical"
1268                         " disk as %s. True\n     protection against single-disk"
1269                         " failure might be compromised.\n",
1270                         mdname(mddev), bdevname(rdev->bdev,b),
1271                         bdevname(same_pdev->bdev,b2));
1272
1273         /* Verify rdev->desc_nr is unique.
1274          * If it is -1, assign a free number, else
1275          * check number is not in use
1276          */
1277         if (rdev->desc_nr < 0) {
1278                 int choice = 0;
1279                 if (mddev->pers) choice = mddev->raid_disks;
1280                 while (find_rdev_nr(mddev, choice))
1281                         choice++;
1282                 rdev->desc_nr = choice;
1283         } else {
1284                 if (find_rdev_nr(mddev, rdev->desc_nr))
1285                         return -EBUSY;
1286         }
1287         bdevname(rdev->bdev,b);
1288         if (kobject_set_name(&rdev->kobj, "dev-%s", b) < 0)
1289                 return -ENOMEM;
1290         while ( (s=strchr(rdev->kobj.k_name, '/')) != NULL)
1291                 *s = '!';
1292                         
1293         list_add(&rdev->same_set, &mddev->disks);
1294         rdev->mddev = mddev;
1295         printk(KERN_INFO "md: bind<%s>\n", b);
1296
1297         rdev->kobj.parent = &mddev->kobj;
1298         kobject_add(&rdev->kobj);
1299
1300         if (rdev->bdev->bd_part)
1301                 ko = &rdev->bdev->bd_part->kobj;
1302         else
1303                 ko = &rdev->bdev->bd_disk->kobj;
1304         sysfs_create_link(&rdev->kobj, ko, "block");
1305         bd_claim_by_disk(rdev->bdev, rdev, mddev->gendisk);
1306         return 0;
1307 }
1308
1309 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
1310 {
1311         char b[BDEVNAME_SIZE];
1312         if (!rdev->mddev) {
1313                 MD_BUG();
1314                 return;
1315         }
1316         bd_release_from_disk(rdev->bdev, rdev->mddev->gendisk);
1317         list_del_init(&rdev->same_set);
1318         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
1319         rdev->mddev = NULL;
1320         sysfs_remove_link(&rdev->kobj, "block");
1321         kobject_del(&rdev->kobj);
1322 }
1323
1324 /*
1325  * prevent the device from being mounted, repartitioned or
1326  * otherwise reused by a RAID array (or any other kernel
1327  * subsystem), by bd_claiming the device.
1328  */
1329 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev)
1330 {
1331         int err = 0;
1332         struct block_device *bdev;
1333         char b[BDEVNAME_SIZE];
1334
1335         bdev = open_by_devnum(dev, FMODE_READ|FMODE_WRITE);
1336         if (IS_ERR(bdev)) {
1337                 printk(KERN_ERR "md: could not open %s.\n",
1338                         __bdevname(dev, b));
1339                 return PTR_ERR(bdev);
1340         }
1341         err = bd_claim(bdev, rdev);
1342         if (err) {
1343                 printk(KERN_ERR "md: could not bd_claim %s.\n",
1344                         bdevname(bdev, b));
1345                 blkdev_put(bdev);
1346                 return err;
1347         }
1348         rdev->bdev = bdev;
1349         return err;
1350 }
1351
1352 static void unlock_rdev(mdk_rdev_t *rdev)
1353 {
1354         struct block_device *bdev = rdev->bdev;
1355         rdev->bdev = NULL;
1356         if (!bdev)
1357                 MD_BUG();
1358         bd_release(bdev);
1359         blkdev_put(bdev);
1360 }
1361
1362 void md_autodetect_dev(dev_t dev);
1363
1364 static void export_rdev(mdk_rdev_t * rdev)
1365 {
1366         char b[BDEVNAME_SIZE];
1367         printk(KERN_INFO "md: export_rdev(%s)\n",
1368                 bdevname(rdev->bdev,b));
1369         if (rdev->mddev)
1370                 MD_BUG();
1371         free_disk_sb(rdev);
1372         list_del_init(&rdev->same_set);
1373 #ifndef MODULE
1374         md_autodetect_dev(rdev->bdev->bd_dev);
1375 #endif
1376         unlock_rdev(rdev);
1377         kobject_put(&rdev->kobj);
1378 }
1379
1380 static void kick_rdev_from_array(mdk_rdev_t * rdev)
1381 {
1382         unbind_rdev_from_array(rdev);
1383         export_rdev(rdev);
1384 }
1385
1386 static void export_array(mddev_t *mddev)
1387 {
1388         struct list_head *tmp;
1389         mdk_rdev_t *rdev;
1390
1391         ITERATE_RDEV(mddev,rdev,tmp) {
1392                 if (!rdev->mddev) {
1393                         MD_BUG();
1394                         continue;
1395                 }
1396                 kick_rdev_from_array(rdev);
1397         }
1398         if (!list_empty(&mddev->disks))
1399                 MD_BUG();
1400         mddev->raid_disks = 0;
1401         mddev->major_version = 0;
1402 }
1403
1404 static void print_desc(mdp_disk_t *desc)
1405 {
1406         printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
1407                 desc->major,desc->minor,desc->raid_disk,desc->state);
1408 }
1409
1410 static void print_sb(mdp_super_t *sb)
1411 {
1412         int i;
1413
1414         printk(KERN_INFO 
1415                 "md:  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
1416                 sb->major_version, sb->minor_version, sb->patch_version,
1417                 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
1418                 sb->ctime);
1419         printk(KERN_INFO "md:     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
1420                 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
1421                 sb->md_minor, sb->layout, sb->chunk_size);
1422         printk(KERN_INFO "md:     UT:%08x ST:%d AD:%d WD:%d"
1423                 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
1424                 sb->utime, sb->state, sb->active_disks, sb->working_disks,
1425                 sb->failed_disks, sb->spare_disks,
1426                 sb->sb_csum, (unsigned long)sb->events_lo);
1427
1428         printk(KERN_INFO);
1429         for (i = 0; i < MD_SB_DISKS; i++) {
1430                 mdp_disk_t *desc;
1431
1432                 desc = sb->disks + i;
1433                 if (desc->number || desc->major || desc->minor ||
1434                     desc->raid_disk || (desc->state && (desc->state != 4))) {
1435                         printk("     D %2d: ", i);
1436                         print_desc(desc);
1437                 }
1438         }
1439         printk(KERN_INFO "md:     THIS: ");
1440         print_desc(&sb->this_disk);
1441
1442 }
1443
1444 static void print_rdev(mdk_rdev_t *rdev)
1445 {
1446         char b[BDEVNAME_SIZE];
1447         printk(KERN_INFO "md: rdev %s, SZ:%08llu F:%d S:%d DN:%u\n",
1448                 bdevname(rdev->bdev,b), (unsigned long long)rdev->size,
1449                 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
1450                 rdev->desc_nr);
1451         if (rdev->sb_loaded) {
1452                 printk(KERN_INFO "md: rdev superblock:\n");
1453                 print_sb((mdp_super_t*)page_address(rdev->sb_page));
1454         } else
1455                 printk(KERN_INFO "md: no rdev superblock!\n");
1456 }
1457
1458 void md_print_devices(void)
1459 {
1460         struct list_head *tmp, *tmp2;
1461         mdk_rdev_t *rdev;
1462         mddev_t *mddev;
1463         char b[BDEVNAME_SIZE];
1464
1465         printk("\n");
1466         printk("md:     **********************************\n");
1467         printk("md:     * <COMPLETE RAID STATE PRINTOUT> *\n");
1468         printk("md:     **********************************\n");
1469         ITERATE_MDDEV(mddev,tmp) {
1470
1471                 if (mddev->bitmap)
1472                         bitmap_print_sb(mddev->bitmap);
1473                 else
1474                         printk("%s: ", mdname(mddev));
1475                 ITERATE_RDEV(mddev,rdev,tmp2)
1476                         printk("<%s>", bdevname(rdev->bdev,b));
1477                 printk("\n");
1478
1479                 ITERATE_RDEV(mddev,rdev,tmp2)
1480                         print_rdev(rdev);
1481         }
1482         printk("md:     **********************************\n");
1483         printk("\n");
1484 }
1485
1486
1487 static void sync_sbs(mddev_t * mddev)
1488 {
1489         mdk_rdev_t *rdev;
1490         struct list_head *tmp;
1491
1492         ITERATE_RDEV(mddev,rdev,tmp) {
1493                 super_types[mddev->major_version].
1494                         sync_super(mddev, rdev);
1495                 rdev->sb_loaded = 1;
1496         }
1497 }
1498
1499 static void md_update_sb(mddev_t * mddev)
1500 {
1501         int err;
1502         struct list_head *tmp;
1503         mdk_rdev_t *rdev;
1504         int sync_req;
1505
1506 repeat:
1507         spin_lock_irq(&mddev->write_lock);
1508         sync_req = mddev->in_sync;
1509         mddev->utime = get_seconds();
1510         mddev->events ++;
1511
1512         if (!mddev->events) {
1513                 /*
1514                  * oops, this 64-bit counter should never wrap.
1515                  * Either we are in around ~1 trillion A.C., assuming
1516                  * 1 reboot per second, or we have a bug:
1517                  */
1518                 MD_BUG();
1519                 mddev->events --;
1520         }
1521         mddev->sb_dirty = 2;
1522         sync_sbs(mddev);
1523
1524         /*
1525          * do not write anything to disk if using
1526          * nonpersistent superblocks
1527          */
1528         if (!mddev->persistent) {
1529                 mddev->sb_dirty = 0;
1530                 spin_unlock_irq(&mddev->write_lock);
1531                 wake_up(&mddev->sb_wait);
1532                 return;
1533         }
1534         spin_unlock_irq(&mddev->write_lock);
1535
1536         dprintk(KERN_INFO 
1537                 "md: updating %s RAID superblock on device (in sync %d)\n",
1538                 mdname(mddev),mddev->in_sync);
1539
1540         err = bitmap_update_sb(mddev->bitmap);
1541         ITERATE_RDEV(mddev,rdev,tmp) {
1542                 char b[BDEVNAME_SIZE];
1543                 dprintk(KERN_INFO "md: ");
1544                 if (test_bit(Faulty, &rdev->flags))
1545                         dprintk("(skipping faulty ");
1546
1547                 dprintk("%s ", bdevname(rdev->bdev,b));
1548                 if (!test_bit(Faulty, &rdev->flags)) {
1549                         md_super_write(mddev,rdev,
1550                                        rdev->sb_offset<<1, rdev->sb_size,
1551                                        rdev->sb_page);
1552                         dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
1553                                 bdevname(rdev->bdev,b),
1554                                 (unsigned long long)rdev->sb_offset);
1555
1556                 } else
1557                         dprintk(")\n");
1558                 if (mddev->level == LEVEL_MULTIPATH)
1559                         /* only need to write one superblock... */
1560                         break;
1561         }
1562         md_super_wait(mddev);
1563         /* if there was a failure, sb_dirty was set to 1, and we re-write super */
1564
1565         spin_lock_irq(&mddev->write_lock);
1566         if (mddev->in_sync != sync_req|| mddev->sb_dirty == 1) {
1567                 /* have to write it out again */
1568                 spin_unlock_irq(&mddev->write_lock);
1569                 goto repeat;
1570         }
1571         mddev->sb_dirty = 0;
1572         spin_unlock_irq(&mddev->write_lock);
1573         wake_up(&mddev->sb_wait);
1574
1575 }
1576
1577 /* words written to sysfs files may, or my not, be \n terminated.
1578  * We want to accept with case. For this we use cmd_match.
1579  */
1580 static int cmd_match(const char *cmd, const char *str)
1581 {
1582         /* See if cmd, written into a sysfs file, matches
1583          * str.  They must either be the same, or cmd can
1584          * have a trailing newline
1585          */
1586         while (*cmd && *str && *cmd == *str) {
1587                 cmd++;
1588                 str++;
1589         }
1590         if (*cmd == '\n')
1591                 cmd++;
1592         if (*str || *cmd)
1593                 return 0;
1594         return 1;
1595 }
1596
1597 struct rdev_sysfs_entry {
1598         struct attribute attr;
1599         ssize_t (*show)(mdk_rdev_t *, char *);
1600         ssize_t (*store)(mdk_rdev_t *, const char *, size_t);
1601 };
1602
1603 static ssize_t
1604 state_show(mdk_rdev_t *rdev, char *page)
1605 {
1606         char *sep = "";
1607         int len=0;
1608
1609         if (test_bit(Faulty, &rdev->flags)) {
1610                 len+= sprintf(page+len, "%sfaulty",sep);
1611                 sep = ",";
1612         }
1613         if (test_bit(In_sync, &rdev->flags)) {
1614                 len += sprintf(page+len, "%sin_sync",sep);
1615                 sep = ",";
1616         }
1617         if (!test_bit(Faulty, &rdev->flags) &&
1618             !test_bit(In_sync, &rdev->flags)) {
1619                 len += sprintf(page+len, "%sspare", sep);
1620                 sep = ",";
1621         }
1622         return len+sprintf(page+len, "\n");
1623 }
1624
1625 static struct rdev_sysfs_entry
1626 rdev_state = __ATTR_RO(state);
1627
1628 static ssize_t
1629 super_show(mdk_rdev_t *rdev, char *page)
1630 {
1631         if (rdev->sb_loaded && rdev->sb_size) {
1632                 memcpy(page, page_address(rdev->sb_page), rdev->sb_size);
1633                 return rdev->sb_size;
1634         } else
1635                 return 0;
1636 }
1637 static struct rdev_sysfs_entry rdev_super = __ATTR_RO(super);
1638
1639 static ssize_t
1640 errors_show(mdk_rdev_t *rdev, char *page)
1641 {
1642         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
1643 }
1644
1645 static ssize_t
1646 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1647 {
1648         char *e;
1649         unsigned long n = simple_strtoul(buf, &e, 10);
1650         if (*buf && (*e == 0 || *e == '\n')) {
1651                 atomic_set(&rdev->corrected_errors, n);
1652                 return len;
1653         }
1654         return -EINVAL;
1655 }
1656 static struct rdev_sysfs_entry rdev_errors =
1657 __ATTR(errors, 0644, errors_show, errors_store);
1658
1659 static ssize_t
1660 slot_show(mdk_rdev_t *rdev, char *page)
1661 {
1662         if (rdev->raid_disk < 0)
1663                 return sprintf(page, "none\n");
1664         else
1665                 return sprintf(page, "%d\n", rdev->raid_disk);
1666 }
1667
1668 static ssize_t
1669 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1670 {
1671         char *e;
1672         int slot = simple_strtoul(buf, &e, 10);
1673         if (strncmp(buf, "none", 4)==0)
1674                 slot = -1;
1675         else if (e==buf || (*e && *e!= '\n'))
1676                 return -EINVAL;
1677         if (rdev->mddev->pers)
1678                 /* Cannot set slot in active array (yet) */
1679                 return -EBUSY;
1680         if (slot >= rdev->mddev->raid_disks)
1681                 return -ENOSPC;
1682         rdev->raid_disk = slot;
1683         /* assume it is working */
1684         rdev->flags = 0;
1685         set_bit(In_sync, &rdev->flags);
1686         return len;
1687 }
1688
1689
1690 static struct rdev_sysfs_entry rdev_slot =
1691 __ATTR(slot, 0644, slot_show, slot_store);
1692
1693 static ssize_t
1694 offset_show(mdk_rdev_t *rdev, char *page)
1695 {
1696         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
1697 }
1698
1699 static ssize_t
1700 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1701 {
1702         char *e;
1703         unsigned long long offset = simple_strtoull(buf, &e, 10);
1704         if (e==buf || (*e && *e != '\n'))
1705                 return -EINVAL;
1706         if (rdev->mddev->pers)
1707                 return -EBUSY;
1708         rdev->data_offset = offset;
1709         return len;
1710 }
1711
1712 static struct rdev_sysfs_entry rdev_offset =
1713 __ATTR(offset, 0644, offset_show, offset_store);
1714
1715 static ssize_t
1716 rdev_size_show(mdk_rdev_t *rdev, char *page)
1717 {
1718         return sprintf(page, "%llu\n", (unsigned long long)rdev->size);
1719 }
1720
1721 static ssize_t
1722 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1723 {
1724         char *e;
1725         unsigned long long size = simple_strtoull(buf, &e, 10);
1726         if (e==buf || (*e && *e != '\n'))
1727                 return -EINVAL;
1728         if (rdev->mddev->pers)
1729                 return -EBUSY;
1730         rdev->size = size;
1731         if (size < rdev->mddev->size || rdev->mddev->size == 0)
1732                 rdev->mddev->size = size;
1733         return len;
1734 }
1735
1736 static struct rdev_sysfs_entry rdev_size =
1737 __ATTR(size, 0644, rdev_size_show, rdev_size_store);
1738
1739 static struct attribute *rdev_default_attrs[] = {
1740         &rdev_state.attr,
1741         &rdev_super.attr,
1742         &rdev_errors.attr,
1743         &rdev_slot.attr,
1744         &rdev_offset.attr,
1745         &rdev_size.attr,
1746         NULL,
1747 };
1748 static ssize_t
1749 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
1750 {
1751         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
1752         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
1753
1754         if (!entry->show)
1755                 return -EIO;
1756         return entry->show(rdev, page);
1757 }
1758
1759 static ssize_t
1760 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
1761               const char *page, size_t length)
1762 {
1763         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
1764         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
1765
1766         if (!entry->store)
1767                 return -EIO;
1768         return entry->store(rdev, page, length);
1769 }
1770
1771 static void rdev_free(struct kobject *ko)
1772 {
1773         mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
1774         kfree(rdev);
1775 }
1776 static struct sysfs_ops rdev_sysfs_ops = {
1777         .show           = rdev_attr_show,
1778         .store          = rdev_attr_store,
1779 };
1780 static struct kobj_type rdev_ktype = {
1781         .release        = rdev_free,
1782         .sysfs_ops      = &rdev_sysfs_ops,
1783         .default_attrs  = rdev_default_attrs,
1784 };
1785
1786 /*
1787  * Import a device. If 'super_format' >= 0, then sanity check the superblock
1788  *
1789  * mark the device faulty if:
1790  *
1791  *   - the device is nonexistent (zero size)
1792  *   - the device has no valid superblock
1793  *
1794  * a faulty rdev _never_ has rdev->sb set.
1795  */
1796 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
1797 {
1798         char b[BDEVNAME_SIZE];
1799         int err;
1800         mdk_rdev_t *rdev;
1801         sector_t size;
1802
1803         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
1804         if (!rdev) {
1805                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
1806                 return ERR_PTR(-ENOMEM);
1807         }
1808
1809         if ((err = alloc_disk_sb(rdev)))
1810                 goto abort_free;
1811
1812         err = lock_rdev(rdev, newdev);
1813         if (err)
1814                 goto abort_free;
1815
1816         rdev->kobj.parent = NULL;
1817         rdev->kobj.ktype = &rdev_ktype;
1818         kobject_init(&rdev->kobj);
1819
1820         rdev->desc_nr = -1;
1821         rdev->flags = 0;
1822         rdev->data_offset = 0;
1823         atomic_set(&rdev->nr_pending, 0);
1824         atomic_set(&rdev->read_errors, 0);
1825         atomic_set(&rdev->corrected_errors, 0);
1826
1827         size = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
1828         if (!size) {
1829                 printk(KERN_WARNING 
1830                         "md: %s has zero or unknown size, marking faulty!\n",
1831                         bdevname(rdev->bdev,b));
1832                 err = -EINVAL;
1833                 goto abort_free;
1834         }
1835
1836         if (super_format >= 0) {
1837                 err = super_types[super_format].
1838                         load_super(rdev, NULL, super_minor);
1839                 if (err == -EINVAL) {
1840                         printk(KERN_WARNING 
1841                                 "md: %s has invalid sb, not importing!\n",
1842                                 bdevname(rdev->bdev,b));
1843                         goto abort_free;
1844                 }
1845                 if (err < 0) {
1846                         printk(KERN_WARNING 
1847                                 "md: could not read %s's sb, not importing!\n",
1848                                 bdevname(rdev->bdev,b));
1849                         goto abort_free;
1850                 }
1851         }
1852         INIT_LIST_HEAD(&rdev->same_set);
1853
1854         return rdev;
1855
1856 abort_free:
1857         if (rdev->sb_page) {
1858                 if (rdev->bdev)
1859                         unlock_rdev(rdev);
1860                 free_disk_sb(rdev);
1861         }
1862         kfree(rdev);
1863         return ERR_PTR(err);
1864 }
1865
1866 /*
1867  * Check a full RAID array for plausibility
1868  */
1869
1870
1871 static void analyze_sbs(mddev_t * mddev)
1872 {
1873         int i;
1874         struct list_head *tmp;
1875         mdk_rdev_t *rdev, *freshest;
1876         char b[BDEVNAME_SIZE];
1877
1878         freshest = NULL;
1879         ITERATE_RDEV(mddev,rdev,tmp)
1880                 switch (super_types[mddev->major_version].
1881                         load_super(rdev, freshest, mddev->minor_version)) {
1882                 case 1:
1883                         freshest = rdev;
1884                         break;
1885                 case 0:
1886                         break;
1887                 default:
1888                         printk( KERN_ERR \
1889                                 "md: fatal superblock inconsistency in %s"
1890                                 " -- removing from array\n", 
1891                                 bdevname(rdev->bdev,b));
1892                         kick_rdev_from_array(rdev);
1893                 }
1894
1895
1896         super_types[mddev->major_version].
1897                 validate_super(mddev, freshest);
1898
1899         i = 0;
1900         ITERATE_RDEV(mddev,rdev,tmp) {
1901                 if (rdev != freshest)
1902                         if (super_types[mddev->major_version].
1903                             validate_super(mddev, rdev)) {
1904                                 printk(KERN_WARNING "md: kicking non-fresh %s"
1905                                         " from array!\n",
1906                                         bdevname(rdev->bdev,b));
1907                                 kick_rdev_from_array(rdev);
1908                                 continue;
1909                         }
1910                 if (mddev->level == LEVEL_MULTIPATH) {
1911                         rdev->desc_nr = i++;
1912                         rdev->raid_disk = rdev->desc_nr;
1913                         set_bit(In_sync, &rdev->flags);
1914                 }
1915         }
1916
1917
1918
1919         if (mddev->recovery_cp != MaxSector &&
1920             mddev->level >= 1)
1921                 printk(KERN_ERR "md: %s: raid array is not clean"
1922                        " -- starting background reconstruction\n",
1923                        mdname(mddev));
1924
1925 }
1926
1927 static ssize_t
1928 level_show(mddev_t *mddev, char *page)
1929 {
1930         struct mdk_personality *p = mddev->pers;
1931         if (p)
1932                 return sprintf(page, "%s\n", p->name);
1933         else if (mddev->clevel[0])
1934                 return sprintf(page, "%s\n", mddev->clevel);
1935         else if (mddev->level != LEVEL_NONE)
1936                 return sprintf(page, "%d\n", mddev->level);
1937         else
1938                 return 0;
1939 }
1940
1941 static ssize_t
1942 level_store(mddev_t *mddev, const char *buf, size_t len)
1943 {
1944         int rv = len;
1945         if (mddev->pers)
1946                 return -EBUSY;
1947         if (len == 0)
1948                 return 0;
1949         if (len >= sizeof(mddev->clevel))
1950                 return -ENOSPC;
1951         strncpy(mddev->clevel, buf, len);
1952         if (mddev->clevel[len-1] == '\n')
1953                 len--;
1954         mddev->clevel[len] = 0;
1955         mddev->level = LEVEL_NONE;
1956         return rv;
1957 }
1958
1959 static struct md_sysfs_entry md_level =
1960 __ATTR(level, 0644, level_show, level_store);
1961
1962 static ssize_t
1963 raid_disks_show(mddev_t *mddev, char *page)
1964 {
1965         if (mddev->raid_disks == 0)
1966                 return 0;
1967         return sprintf(page, "%d\n", mddev->raid_disks);
1968 }
1969
1970 static int update_raid_disks(mddev_t *mddev, int raid_disks);
1971
1972 static ssize_t
1973 raid_disks_store(mddev_t *mddev, const char *buf, size_t len)
1974 {
1975         /* can only set raid_disks if array is not yet active */
1976         char *e;
1977         int rv = 0;
1978         unsigned long n = simple_strtoul(buf, &e, 10);
1979
1980         if (!*buf || (*e && *e != '\n'))
1981                 return -EINVAL;
1982
1983         if (mddev->pers)
1984                 rv = update_raid_disks(mddev, n);
1985         else
1986                 mddev->raid_disks = n;
1987         return rv ? rv : len;
1988 }
1989 static struct md_sysfs_entry md_raid_disks =
1990 __ATTR(raid_disks, 0644, raid_disks_show, raid_disks_store);
1991
1992 static ssize_t
1993 chunk_size_show(mddev_t *mddev, char *page)
1994 {
1995         return sprintf(page, "%d\n", mddev->chunk_size);
1996 }
1997
1998 static ssize_t
1999 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
2000 {
2001         /* can only set chunk_size if array is not yet active */
2002         char *e;
2003         unsigned long n = simple_strtoul(buf, &e, 10);
2004
2005         if (mddev->pers)
2006                 return -EBUSY;
2007         if (!*buf || (*e && *e != '\n'))
2008                 return -EINVAL;
2009
2010         mddev->chunk_size = n;
2011         return len;
2012 }
2013 static struct md_sysfs_entry md_chunk_size =
2014 __ATTR(chunk_size, 0644, chunk_size_show, chunk_size_store);
2015
2016 static ssize_t
2017 null_show(mddev_t *mddev, char *page)
2018 {
2019         return -EINVAL;
2020 }
2021
2022 static ssize_t
2023 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
2024 {
2025         /* buf must be %d:%d\n? giving major and minor numbers */
2026         /* The new device is added to the array.
2027          * If the array has a persistent superblock, we read the
2028          * superblock to initialise info and check validity.
2029          * Otherwise, only checking done is that in bind_rdev_to_array,
2030          * which mainly checks size.
2031          */
2032         char *e;
2033         int major = simple_strtoul(buf, &e, 10);
2034         int minor;
2035         dev_t dev;
2036         mdk_rdev_t *rdev;
2037         int err;
2038
2039         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
2040                 return -EINVAL;
2041         minor = simple_strtoul(e+1, &e, 10);
2042         if (*e && *e != '\n')
2043                 return -EINVAL;
2044         dev = MKDEV(major, minor);
2045         if (major != MAJOR(dev) ||
2046             minor != MINOR(dev))
2047                 return -EOVERFLOW;
2048
2049
2050         if (mddev->persistent) {
2051                 rdev = md_import_device(dev, mddev->major_version,
2052                                         mddev->minor_version);
2053                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
2054                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
2055                                                        mdk_rdev_t, same_set);
2056                         err = super_types[mddev->major_version]
2057                                 .load_super(rdev, rdev0, mddev->minor_version);
2058                         if (err < 0)
2059                                 goto out;
2060                 }
2061         } else
2062                 rdev = md_import_device(dev, -1, -1);
2063
2064         if (IS_ERR(rdev))
2065                 return PTR_ERR(rdev);
2066         err = bind_rdev_to_array(rdev, mddev);
2067  out:
2068         if (err)
2069                 export_rdev(rdev);
2070         return err ? err : len;
2071 }
2072
2073 static struct md_sysfs_entry md_new_device =
2074 __ATTR(new_dev, 0200, null_show, new_dev_store);
2075
2076 static ssize_t
2077 size_show(mddev_t *mddev, char *page)
2078 {
2079         return sprintf(page, "%llu\n", (unsigned long long)mddev->size);
2080 }
2081
2082 static int update_size(mddev_t *mddev, unsigned long size);
2083
2084 static ssize_t
2085 size_store(mddev_t *mddev, const char *buf, size_t len)
2086 {
2087         /* If array is inactive, we can reduce the component size, but
2088          * not increase it (except from 0).
2089          * If array is active, we can try an on-line resize
2090          */
2091         char *e;
2092         int err = 0;
2093         unsigned long long size = simple_strtoull(buf, &e, 10);
2094         if (!*buf || *buf == '\n' ||
2095             (*e && *e != '\n'))
2096                 return -EINVAL;
2097
2098         if (mddev->pers) {
2099                 err = update_size(mddev, size);
2100                 md_update_sb(mddev);
2101         } else {
2102                 if (mddev->size == 0 ||
2103                     mddev->size > size)
2104                         mddev->size = size;
2105                 else
2106                         err = -ENOSPC;
2107         }
2108         return err ? err : len;
2109 }
2110
2111 static struct md_sysfs_entry md_size =
2112 __ATTR(component_size, 0644, size_show, size_store);
2113
2114
2115 /* Metdata version.
2116  * This is either 'none' for arrays with externally managed metadata,
2117  * or N.M for internally known formats
2118  */
2119 static ssize_t
2120 metadata_show(mddev_t *mddev, char *page)
2121 {
2122         if (mddev->persistent)
2123                 return sprintf(page, "%d.%d\n",
2124                                mddev->major_version, mddev->minor_version);
2125         else
2126                 return sprintf(page, "none\n");
2127 }
2128
2129 static ssize_t
2130 metadata_store(mddev_t *mddev, const char *buf, size_t len)
2131 {
2132         int major, minor;
2133         char *e;
2134         if (!list_empty(&mddev->disks))
2135                 return -EBUSY;
2136
2137         if (cmd_match(buf, "none")) {
2138                 mddev->persistent = 0;
2139                 mddev->major_version = 0;
2140                 mddev->minor_version = 90;
2141                 return len;
2142         }
2143         major = simple_strtoul(buf, &e, 10);
2144         if (e==buf || *e != '.')
2145                 return -EINVAL;
2146         buf = e+1;
2147         minor = simple_strtoul(buf, &e, 10);
2148         if (e==buf || *e != '\n')
2149                 return -EINVAL;
2150         if (major >= sizeof(super_types)/sizeof(super_types[0]) ||
2151             super_types[major].name == NULL)
2152                 return -ENOENT;
2153         mddev->major_version = major;
2154         mddev->minor_version = minor;
2155         mddev->persistent = 1;
2156         return len;
2157 }
2158
2159 static struct md_sysfs_entry md_metadata =
2160 __ATTR(metadata_version, 0644, metadata_show, metadata_store);
2161
2162 static ssize_t
2163 action_show(mddev_t *mddev, char *page)
2164 {
2165         char *type = "idle";
2166         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2167             test_bit(MD_RECOVERY_NEEDED, &mddev->recovery)) {
2168                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2169                         type = "reshape";
2170                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2171                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2172                                 type = "resync";
2173                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2174                                 type = "check";
2175                         else
2176                                 type = "repair";
2177                 } else
2178                         type = "recover";
2179         }
2180         return sprintf(page, "%s\n", type);
2181 }
2182
2183 static ssize_t
2184 action_store(mddev_t *mddev, const char *page, size_t len)
2185 {
2186         if (!mddev->pers || !mddev->pers->sync_request)
2187                 return -EINVAL;
2188
2189         if (cmd_match(page, "idle")) {
2190                 if (mddev->sync_thread) {
2191                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2192                         md_unregister_thread(mddev->sync_thread);
2193                         mddev->sync_thread = NULL;
2194                         mddev->recovery = 0;
2195                 }
2196         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2197                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
2198                 return -EBUSY;
2199         else if (cmd_match(page, "resync") || cmd_match(page, "recover"))
2200                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2201         else {
2202                 if (cmd_match(page, "check"))
2203                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
2204                 else if (cmd_match(page, "repair"))
2205                         return -EINVAL;
2206                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
2207                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
2208         }
2209         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2210         md_wakeup_thread(mddev->thread);
2211         return len;
2212 }
2213
2214 static ssize_t
2215 mismatch_cnt_show(mddev_t *mddev, char *page)
2216 {
2217         return sprintf(page, "%llu\n",
2218                        (unsigned long long) mddev->resync_mismatches);
2219 }
2220
2221 static struct md_sysfs_entry
2222 md_scan_mode = __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
2223
2224
2225 static struct md_sysfs_entry
2226 md_mismatches = __ATTR_RO(mismatch_cnt);
2227
2228 static ssize_t
2229 sync_min_show(mddev_t *mddev, char *page)
2230 {
2231         return sprintf(page, "%d (%s)\n", speed_min(mddev),
2232                        mddev->sync_speed_min ? "local": "system");
2233 }
2234
2235 static ssize_t
2236 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
2237 {
2238         int min;
2239         char *e;
2240         if (strncmp(buf, "system", 6)==0) {
2241                 mddev->sync_speed_min = 0;
2242                 return len;
2243         }
2244         min = simple_strtoul(buf, &e, 10);
2245         if (buf == e || (*e && *e != '\n') || min <= 0)
2246                 return -EINVAL;
2247         mddev->sync_speed_min = min;
2248         return len;
2249 }
2250
2251 static struct md_sysfs_entry md_sync_min =
2252 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
2253
2254 static ssize_t
2255 sync_max_show(mddev_t *mddev, char *page)
2256 {
2257         return sprintf(page, "%d (%s)\n", speed_max(mddev),
2258                        mddev->sync_speed_max ? "local": "system");
2259 }
2260
2261 static ssize_t
2262 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
2263 {
2264         int max;
2265         char *e;
2266         if (strncmp(buf, "system", 6)==0) {
2267                 mddev->sync_speed_max = 0;
2268                 return len;
2269         }
2270         max = simple_strtoul(buf, &e, 10);
2271         if (buf == e || (*e && *e != '\n') || max <= 0)
2272                 return -EINVAL;
2273         mddev->sync_speed_max = max;
2274         return len;
2275 }
2276
2277 static struct md_sysfs_entry md_sync_max =
2278 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
2279
2280
2281 static ssize_t
2282 sync_speed_show(mddev_t *mddev, char *page)
2283 {
2284         unsigned long resync, dt, db;
2285         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
2286         dt = ((jiffies - mddev->resync_mark) / HZ);
2287         if (!dt) dt++;
2288         db = resync - (mddev->resync_mark_cnt);
2289         return sprintf(page, "%ld\n", db/dt/2); /* K/sec */
2290 }
2291
2292 static struct md_sysfs_entry
2293 md_sync_speed = __ATTR_RO(sync_speed);
2294
2295 static ssize_t
2296 sync_completed_show(mddev_t *mddev, char *page)
2297 {
2298         unsigned long max_blocks, resync;
2299
2300         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2301                 max_blocks = mddev->resync_max_sectors;
2302         else
2303                 max_blocks = mddev->size << 1;
2304
2305         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
2306         return sprintf(page, "%lu / %lu\n", resync, max_blocks);
2307 }
2308
2309 static struct md_sysfs_entry
2310 md_sync_completed = __ATTR_RO(sync_completed);
2311
2312 static struct attribute *md_default_attrs[] = {
2313         &md_level.attr,
2314         &md_raid_disks.attr,
2315         &md_chunk_size.attr,
2316         &md_size.attr,
2317         &md_metadata.attr,
2318         &md_new_device.attr,
2319         NULL,
2320 };
2321
2322 static struct attribute *md_redundancy_attrs[] = {
2323         &md_scan_mode.attr,
2324         &md_mismatches.attr,
2325         &md_sync_min.attr,
2326         &md_sync_max.attr,
2327         &md_sync_speed.attr,
2328         &md_sync_completed.attr,
2329         NULL,
2330 };
2331 static struct attribute_group md_redundancy_group = {
2332         .name = NULL,
2333         .attrs = md_redundancy_attrs,
2334 };
2335
2336
2337 static ssize_t
2338 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2339 {
2340         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
2341         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
2342         ssize_t rv;
2343
2344         if (!entry->show)
2345                 return -EIO;
2346         mddev_lock(mddev);
2347         rv = entry->show(mddev, page);
2348         mddev_unlock(mddev);
2349         return rv;
2350 }
2351
2352 static ssize_t
2353 md_attr_store(struct kobject *kobj, struct attribute *attr,
2354               const char *page, size_t length)
2355 {
2356         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
2357         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
2358         ssize_t rv;
2359
2360         if (!entry->store)
2361                 return -EIO;
2362         mddev_lock(mddev);
2363         rv = entry->store(mddev, page, length);
2364         mddev_unlock(mddev);
2365         return rv;
2366 }
2367
2368 static void md_free(struct kobject *ko)
2369 {
2370         mddev_t *mddev = container_of(ko, mddev_t, kobj);
2371         kfree(mddev);
2372 }
2373
2374 static struct sysfs_ops md_sysfs_ops = {
2375         .show   = md_attr_show,
2376         .store  = md_attr_store,
2377 };
2378 static struct kobj_type md_ktype = {
2379         .release        = md_free,
2380         .sysfs_ops      = &md_sysfs_ops,
2381         .default_attrs  = md_default_attrs,
2382 };
2383
2384 int mdp_major = 0;
2385
2386 static struct kobject *md_probe(dev_t dev, int *part, void *data)
2387 {
2388         static DECLARE_MUTEX(disks_sem);
2389         mddev_t *mddev = mddev_find(dev);
2390         struct gendisk *disk;
2391         int partitioned = (MAJOR(dev) != MD_MAJOR);
2392         int shift = partitioned ? MdpMinorShift : 0;
2393         int unit = MINOR(dev) >> shift;
2394
2395         if (!mddev)
2396                 return NULL;
2397
2398         down(&disks_sem);
2399         if (mddev->gendisk) {
2400                 up(&disks_sem);
2401                 mddev_put(mddev);
2402                 return NULL;
2403         }
2404         disk = alloc_disk(1 << shift);
2405         if (!disk) {
2406                 up(&disks_sem);
2407                 mddev_put(mddev);
2408                 return NULL;
2409         }
2410         disk->major = MAJOR(dev);
2411         disk->first_minor = unit << shift;
2412         if (partitioned) {
2413                 sprintf(disk->disk_name, "md_d%d", unit);
2414                 sprintf(disk->devfs_name, "md/d%d", unit);
2415         } else {
2416                 sprintf(disk->disk_name, "md%d", unit);
2417                 sprintf(disk->devfs_name, "md/%d", unit);
2418         }
2419         disk->fops = &md_fops;
2420         disk->private_data = mddev;
2421         disk->queue = mddev->queue;
2422         add_disk(disk);
2423         mddev->gendisk = disk;
2424         up(&disks_sem);
2425         mddev->kobj.parent = &disk->kobj;
2426         mddev->kobj.k_name = NULL;
2427         snprintf(mddev->kobj.name, KOBJ_NAME_LEN, "%s", "md");
2428         mddev->kobj.ktype = &md_ktype;
2429         kobject_register(&mddev->kobj);
2430         return NULL;
2431 }
2432
2433 void md_wakeup_thread(mdk_thread_t *thread);
2434
2435 static void md_safemode_timeout(unsigned long data)
2436 {
2437         mddev_t *mddev = (mddev_t *) data;
2438
2439         mddev->safemode = 1;
2440         md_wakeup_thread(mddev->thread);
2441 }
2442
2443 static int start_dirty_degraded;
2444
2445 static int do_md_run(mddev_t * mddev)
2446 {
2447         int err;
2448         int chunk_size;
2449         struct list_head *tmp;
2450         mdk_rdev_t *rdev;
2451         struct gendisk *disk;
2452         struct mdk_personality *pers;
2453         char b[BDEVNAME_SIZE];
2454
2455         if (list_empty(&mddev->disks))
2456                 /* cannot run an array with no devices.. */
2457                 return -EINVAL;
2458
2459         if (mddev->pers)
2460                 return -EBUSY;
2461
2462         /*
2463          * Analyze all RAID superblock(s)
2464          */
2465         if (!mddev->raid_disks)
2466                 analyze_sbs(mddev);
2467
2468         chunk_size = mddev->chunk_size;
2469
2470         if (chunk_size) {
2471                 if (chunk_size > MAX_CHUNK_SIZE) {
2472                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
2473                                 chunk_size, MAX_CHUNK_SIZE);
2474                         return -EINVAL;
2475                 }
2476                 /*
2477                  * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
2478                  */
2479                 if ( (1 << ffz(~chunk_size)) != chunk_size) {
2480                         printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
2481                         return -EINVAL;
2482                 }
2483                 if (chunk_size < PAGE_SIZE) {
2484                         printk(KERN_ERR "too small chunk_size: %d < %ld\n",
2485                                 chunk_size, PAGE_SIZE);
2486                         return -EINVAL;
2487                 }
2488
2489                 /* devices must have minimum size of one chunk */
2490                 ITERATE_RDEV(mddev,rdev,tmp) {
2491                         if (test_bit(Faulty, &rdev->flags))
2492                                 continue;
2493                         if (rdev->size < chunk_size / 1024) {
2494                                 printk(KERN_WARNING
2495                                         "md: Dev %s smaller than chunk_size:"
2496                                         " %lluk < %dk\n",
2497                                         bdevname(rdev->bdev,b),
2498                                         (unsigned long long)rdev->size,
2499                                         chunk_size / 1024);
2500                                 return -EINVAL;
2501                         }
2502                 }
2503         }
2504
2505 #ifdef CONFIG_KMOD
2506         if (mddev->level != LEVEL_NONE)
2507                 request_module("md-level-%d", mddev->level);
2508         else if (mddev->clevel[0])
2509                 request_module("md-%s", mddev->clevel);
2510 #endif
2511
2512         /*
2513          * Drop all container device buffers, from now on
2514          * the only valid external interface is through the md
2515          * device.
2516          * Also find largest hardsector size
2517          */
2518         ITERATE_RDEV(mddev,rdev,tmp) {
2519                 if (test_bit(Faulty, &rdev->flags))
2520                         continue;
2521                 sync_blockdev(rdev->bdev);
2522                 invalidate_bdev(rdev->bdev, 0);
2523         }
2524
2525         md_probe(mddev->unit, NULL, NULL);
2526         disk = mddev->gendisk;
2527         if (!disk)
2528                 return -ENOMEM;
2529
2530         spin_lock(&pers_lock);
2531         pers = find_pers(mddev->level, mddev->clevel);
2532         if (!pers || !try_module_get(pers->owner)) {
2533                 spin_unlock(&pers_lock);
2534                 if (mddev->level != LEVEL_NONE)
2535                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
2536                                mddev->level);
2537                 else
2538                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
2539                                mddev->clevel);
2540                 return -EINVAL;
2541         }
2542         mddev->pers = pers;
2543         spin_unlock(&pers_lock);
2544         mddev->level = pers->level;
2545         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
2546
2547         mddev->recovery = 0;
2548         mddev->resync_max_sectors = mddev->size << 1; /* may be over-ridden by personality */
2549         mddev->barriers_work = 1;
2550         mddev->ok_start_degraded = start_dirty_degraded;
2551
2552         if (start_readonly)
2553                 mddev->ro = 2; /* read-only, but switch on first write */
2554
2555         err = mddev->pers->run(mddev);
2556         if (!err && mddev->pers->sync_request) {
2557                 err = bitmap_create(mddev);
2558                 if (err) {
2559                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
2560                                mdname(mddev), err);
2561                         mddev->pers->stop(mddev);
2562                 }
2563         }
2564         if (err) {
2565                 printk(KERN_ERR "md: pers->run() failed ...\n");
2566                 module_put(mddev->pers->owner);
2567                 mddev->pers = NULL;
2568                 bitmap_destroy(mddev);
2569                 return err;
2570         }
2571         if (mddev->pers->sync_request)
2572                 sysfs_create_group(&mddev->kobj, &md_redundancy_group);
2573         else if (mddev->ro == 2) /* auto-readonly not meaningful */
2574                 mddev->ro = 0;
2575
2576         atomic_set(&mddev->writes_pending,0);
2577         mddev->safemode = 0;
2578         mddev->safemode_timer.function = md_safemode_timeout;
2579         mddev->safemode_timer.data = (unsigned long) mddev;
2580         mddev->safemode_delay = (20 * HZ)/1000 +1; /* 20 msec delay */
2581         mddev->in_sync = 1;
2582
2583         ITERATE_RDEV(mddev,rdev,tmp)
2584                 if (rdev->raid_disk >= 0) {
2585                         char nm[20];
2586                         sprintf(nm, "rd%d", rdev->raid_disk);
2587                         sysfs_create_link(&mddev->kobj, &rdev->kobj, nm);
2588                 }
2589         
2590         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2591         md_wakeup_thread(mddev->thread);
2592         
2593         if (mddev->sb_dirty)
2594                 md_update_sb(mddev);
2595
2596         set_capacity(disk, mddev->array_size<<1);
2597
2598         /* If we call blk_queue_make_request here, it will
2599          * re-initialise max_sectors etc which may have been
2600          * refined inside -> run.  So just set the bits we need to set.
2601          * Most initialisation happended when we called
2602          * blk_queue_make_request(..., md_fail_request)
2603          * earlier.
2604          */
2605         mddev->queue->queuedata = mddev;
2606         mddev->queue->make_request_fn = mddev->pers->make_request;
2607
2608         mddev->changed = 1;
2609         md_new_event(mddev);
2610         return 0;
2611 }
2612
2613 static int restart_array(mddev_t *mddev)
2614 {
2615         struct gendisk *disk = mddev->gendisk;
2616         int err;
2617
2618         /*
2619          * Complain if it has no devices
2620          */
2621         err = -ENXIO;
2622         if (list_empty(&mddev->disks))
2623                 goto out;
2624
2625         if (mddev->pers) {
2626                 err = -EBUSY;
2627                 if (!mddev->ro)
2628                         goto out;
2629
2630                 mddev->safemode = 0;
2631                 mddev->ro = 0;
2632                 set_disk_ro(disk, 0);
2633
2634                 printk(KERN_INFO "md: %s switched to read-write mode.\n",
2635                         mdname(mddev));
2636                 /*
2637                  * Kick recovery or resync if necessary
2638                  */
2639                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2640                 md_wakeup_thread(mddev->thread);
2641                 err = 0;
2642         } else {
2643                 printk(KERN_ERR "md: %s has no personality assigned.\n",
2644                         mdname(mddev));
2645                 err = -EINVAL;
2646         }
2647
2648 out:
2649         return err;
2650 }
2651
2652 static int do_md_stop(mddev_t * mddev, int ro)
2653 {
2654         int err = 0;
2655         struct gendisk *disk = mddev->gendisk;
2656
2657         if (mddev->pers) {
2658                 if (atomic_read(&mddev->active)>2) {
2659                         printk("md: %s still in use.\n",mdname(mddev));
2660                         return -EBUSY;
2661                 }
2662
2663                 if (mddev->sync_thread) {
2664                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2665                         md_unregister_thread(mddev->sync_thread);
2666                         mddev->sync_thread = NULL;
2667                 }
2668
2669                 del_timer_sync(&mddev->safemode_timer);
2670
2671                 invalidate_partition(disk, 0);
2672
2673                 if (ro) {
2674                         err  = -ENXIO;
2675                         if (mddev->ro==1)
2676                                 goto out;
2677                         mddev->ro = 1;
2678                 } else {
2679                         bitmap_flush(mddev);
2680                         md_super_wait(mddev);
2681                         if (mddev->ro)
2682                                 set_disk_ro(disk, 0);
2683                         blk_queue_make_request(mddev->queue, md_fail_request);
2684                         mddev->pers->stop(mddev);
2685                         if (mddev->pers->sync_request)
2686                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
2687
2688                         module_put(mddev->pers->owner);
2689                         mddev->pers = NULL;
2690                         if (mddev->ro)
2691                                 mddev->ro = 0;
2692                 }
2693                 if (!mddev->in_sync) {
2694                         /* mark array as shutdown cleanly */
2695                         mddev->in_sync = 1;
2696                         md_update_sb(mddev);
2697                 }
2698                 if (ro)
2699                         set_disk_ro(disk, 1);
2700         }
2701
2702         /*
2703          * Free resources if final stop
2704          */
2705         if (!ro) {
2706                 mdk_rdev_t *rdev;
2707                 struct list_head *tmp;
2708                 struct gendisk *disk;
2709                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
2710
2711                 bitmap_destroy(mddev);
2712                 if (mddev->bitmap_file) {
2713                         atomic_set(&mddev->bitmap_file->f_dentry->d_inode->i_writecount, 1);
2714                         fput(mddev->bitmap_file);
2715                         mddev->bitmap_file = NULL;
2716                 }
2717                 mddev->bitmap_offset = 0;
2718
2719                 ITERATE_RDEV(mddev,rdev,tmp)
2720                         if (rdev->raid_disk >= 0) {
2721                                 char nm[20];
2722                                 sprintf(nm, "rd%d", rdev->raid_disk);
2723                                 sysfs_remove_link(&mddev->kobj, nm);
2724                         }
2725
2726                 export_array(mddev);
2727
2728                 mddev->array_size = 0;
2729                 disk = mddev->gendisk;
2730                 if (disk)
2731                         set_capacity(disk, 0);
2732                 mddev->changed = 1;
2733         } else
2734                 printk(KERN_INFO "md: %s switched to read-only mode.\n",
2735                         mdname(mddev));
2736         err = 0;
2737         md_new_event(mddev);
2738 out:
2739         return err;
2740 }
2741
2742 static void autorun_array(mddev_t *mddev)
2743 {
2744         mdk_rdev_t *rdev;
2745         struct list_head *tmp;
2746         int err;
2747
2748         if (list_empty(&mddev->disks))
2749                 return;
2750
2751         printk(KERN_INFO "md: running: ");
2752
2753         ITERATE_RDEV(mddev,rdev,tmp) {
2754                 char b[BDEVNAME_SIZE];
2755                 printk("<%s>", bdevname(rdev->bdev,b));
2756         }
2757         printk("\n");
2758
2759         err = do_md_run (mddev);
2760         if (err) {
2761                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
2762                 do_md_stop (mddev, 0);
2763         }
2764 }
2765
2766 /*
2767  * lets try to run arrays based on all disks that have arrived
2768  * until now. (those are in pending_raid_disks)
2769  *
2770  * the method: pick the first pending disk, collect all disks with
2771  * the same UUID, remove all from the pending list and put them into
2772  * the 'same_array' list. Then order this list based on superblock
2773  * update time (freshest comes first), kick out 'old' disks and
2774  * compare superblocks. If everything's fine then run it.
2775  *
2776  * If "unit" is allocated, then bump its reference count
2777  */
2778 static void autorun_devices(int part)
2779 {
2780         struct list_head *tmp;
2781         mdk_rdev_t *rdev0, *rdev;
2782         mddev_t *mddev;
2783         char b[BDEVNAME_SIZE];
2784
2785         printk(KERN_INFO "md: autorun ...\n");
2786         while (!list_empty(&pending_raid_disks)) {
2787                 dev_t dev;
2788                 LIST_HEAD(candidates);
2789                 rdev0 = list_entry(pending_raid_disks.next,
2790                                          mdk_rdev_t, same_set);
2791
2792                 printk(KERN_INFO "md: considering %s ...\n",
2793                         bdevname(rdev0->bdev,b));
2794                 INIT_LIST_HEAD(&candidates);
2795                 ITERATE_RDEV_PENDING(rdev,tmp)
2796                         if (super_90_load(rdev, rdev0, 0) >= 0) {
2797                                 printk(KERN_INFO "md:  adding %s ...\n",
2798                                         bdevname(rdev->bdev,b));
2799                                 list_move(&rdev->same_set, &candidates);
2800                         }
2801                 /*
2802                  * now we have a set of devices, with all of them having
2803                  * mostly sane superblocks. It's time to allocate the
2804                  * mddev.
2805                  */
2806                 if (rdev0->preferred_minor < 0 || rdev0->preferred_minor >= MAX_MD_DEVS) {
2807                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
2808                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
2809                         break;
2810                 }
2811                 if (part)
2812                         dev = MKDEV(mdp_major,
2813                                     rdev0->preferred_minor << MdpMinorShift);
2814                 else
2815                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
2816
2817                 md_probe(dev, NULL, NULL);
2818                 mddev = mddev_find(dev);
2819                 if (!mddev) {
2820                         printk(KERN_ERR 
2821                                 "md: cannot allocate memory for md drive.\n");
2822                         break;
2823                 }
2824                 if (mddev_lock(mddev)) 
2825                         printk(KERN_WARNING "md: %s locked, cannot run\n",
2826                                mdname(mddev));
2827                 else if (mddev->raid_disks || mddev->major_version
2828                          || !list_empty(&mddev->disks)) {
2829                         printk(KERN_WARNING 
2830                                 "md: %s already running, cannot run %s\n",
2831                                 mdname(mddev), bdevname(rdev0->bdev,b));
2832                         mddev_unlock(mddev);
2833                 } else {
2834                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
2835                         ITERATE_RDEV_GENERIC(candidates,rdev,tmp) {
2836                                 list_del_init(&rdev->same_set);
2837                                 if (bind_rdev_to_array(rdev, mddev))
2838                                         export_rdev(rdev);
2839                         }
2840                         autorun_array(mddev);
2841                         mddev_unlock(mddev);
2842                 }
2843                 /* on success, candidates will be empty, on error
2844                  * it won't...
2845                  */
2846                 ITERATE_RDEV_GENERIC(candidates,rdev,tmp)
2847                         export_rdev(rdev);
2848                 mddev_put(mddev);
2849         }
2850         printk(KERN_INFO "md: ... autorun DONE.\n");
2851 }
2852
2853 /*
2854  * import RAID devices based on one partition
2855  * if possible, the array gets run as well.
2856  */
2857
2858 static int autostart_array(dev_t startdev)
2859 {
2860         char b[BDEVNAME_SIZE];
2861         int err = -EINVAL, i;
2862         mdp_super_t *sb = NULL;
2863         mdk_rdev_t *start_rdev = NULL, *rdev;
2864
2865         start_rdev = md_import_device(startdev, 0, 0);
2866         if (IS_ERR(start_rdev))
2867                 return err;
2868
2869
2870         /* NOTE: this can only work for 0.90.0 superblocks */
2871         sb = (mdp_super_t*)page_address(start_rdev->sb_page);
2872         if (sb->major_version != 0 ||
2873             sb->minor_version != 90 ) {
2874                 printk(KERN_WARNING "md: can only autostart 0.90.0 arrays\n");
2875                 export_rdev(start_rdev);
2876                 return err;
2877         }
2878
2879         if (test_bit(Faulty, &start_rdev->flags)) {
2880                 printk(KERN_WARNING 
2881                         "md: can not autostart based on faulty %s!\n",
2882                         bdevname(start_rdev->bdev,b));
2883                 export_rdev(start_rdev);
2884                 return err;
2885         }
2886         list_add(&start_rdev->same_set, &pending_raid_disks);
2887
2888         for (i = 0; i < MD_SB_DISKS; i++) {
2889                 mdp_disk_t *desc = sb->disks + i;
2890                 dev_t dev = MKDEV(desc->major, desc->minor);
2891
2892                 if (!dev)
2893                         continue;
2894                 if (dev == startdev)
2895                         continue;
2896                 if (MAJOR(dev) != desc->major || MINOR(dev) != desc->minor)
2897                         continue;
2898                 rdev = md_import_device(dev, 0, 0);
2899                 if (IS_ERR(rdev))
2900                         continue;
2901
2902                 list_add(&rdev->same_set, &pending_raid_disks);
2903         }
2904
2905         /*
2906          * possibly return codes
2907          */
2908         autorun_devices(0);
2909         return 0;
2910
2911 }
2912
2913
2914 static int get_version(void __user * arg)
2915 {
2916         mdu_version_t ver;
2917
2918         ver.major = MD_MAJOR_VERSION;
2919         ver.minor = MD_MINOR_VERSION;
2920         ver.patchlevel = MD_PATCHLEVEL_VERSION;
2921
2922         if (copy_to_user(arg, &ver, sizeof(ver)))
2923                 return -EFAULT;
2924
2925         return 0;
2926 }
2927
2928 static int get_array_info(mddev_t * mddev, void __user * arg)
2929 {
2930         mdu_array_info_t info;
2931         int nr,working,active,failed,spare;
2932         mdk_rdev_t *rdev;
2933         struct list_head *tmp;
2934
2935         nr=working=active=failed=spare=0;
2936         ITERATE_RDEV(mddev,rdev,tmp) {
2937                 nr++;
2938                 if (test_bit(Faulty, &rdev->flags))
2939                         failed++;
2940                 else {
2941                         working++;
2942                         if (test_bit(In_sync, &rdev->flags))
2943                                 active++;       
2944                         else
2945                                 spare++;
2946                 }
2947         }
2948
2949         info.major_version = mddev->major_version;
2950         info.minor_version = mddev->minor_version;
2951         info.patch_version = MD_PATCHLEVEL_VERSION;
2952         info.ctime         = mddev->ctime;
2953         info.level         = mddev->level;
2954         info.size          = mddev->size;
2955         if (info.size != mddev->size) /* overflow */
2956                 info.size = -1;
2957         info.nr_disks      = nr;
2958         info.raid_disks    = mddev->raid_disks;
2959         info.md_minor      = mddev->md_minor;
2960         info.not_persistent= !mddev->persistent;
2961
2962         info.utime         = mddev->utime;
2963         info.state         = 0;
2964         if (mddev->in_sync)
2965                 info.state = (1<<MD_SB_CLEAN);
2966         if (mddev->bitmap && mddev->bitmap_offset)
2967                 info.state = (1<<MD_SB_BITMAP_PRESENT);
2968         info.active_disks  = active;
2969         info.working_disks = working;
2970         info.failed_disks  = failed;
2971         info.spare_disks   = spare;
2972
2973         info.layout        = mddev->layout;
2974         info.chunk_size    = mddev->chunk_size;
2975
2976         if (copy_to_user(arg, &info, sizeof(info)))
2977                 return -EFAULT;
2978
2979         return 0;
2980 }
2981
2982 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
2983 {
2984         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
2985         char *ptr, *buf = NULL;
2986         int err = -ENOMEM;
2987
2988         file = kmalloc(sizeof(*file), GFP_KERNEL);
2989         if (!file)
2990                 goto out;
2991
2992         /* bitmap disabled, zero the first byte and copy out */
2993         if (!mddev->bitmap || !mddev->bitmap->file) {
2994                 file->pathname[0] = '\0';
2995                 goto copy_out;
2996         }
2997
2998         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
2999         if (!buf)
3000                 goto out;
3001
3002         ptr = file_path(mddev->bitmap->file, buf, sizeof(file->pathname));
3003         if (!ptr)
3004                 goto out;
3005
3006         strcpy(file->pathname, ptr);
3007
3008 copy_out:
3009         err = 0;
3010         if (copy_to_user(arg, file, sizeof(*file)))
3011                 err = -EFAULT;
3012 out:
3013         kfree(buf);
3014         kfree(file);
3015         return err;
3016 }
3017
3018 static int get_disk_info(mddev_t * mddev, void __user * arg)
3019 {
3020         mdu_disk_info_t info;
3021         unsigned int nr;
3022         mdk_rdev_t *rdev;
3023
3024         if (copy_from_user(&info, arg, sizeof(info)))
3025                 return -EFAULT;
3026
3027         nr = info.number;
3028
3029         rdev = find_rdev_nr(mddev, nr);
3030         if (rdev) {
3031                 info.major = MAJOR(rdev->bdev->bd_dev);
3032                 info.minor = MINOR(rdev->bdev->bd_dev);
3033                 info.raid_disk = rdev->raid_disk;
3034                 info.state = 0;
3035                 if (test_bit(Faulty, &rdev->flags))
3036                         info.state |= (1<<MD_DISK_FAULTY);
3037                 else if (test_bit(In_sync, &rdev->flags)) {
3038                         info.state |= (1<<MD_DISK_ACTIVE);
3039                         info.state |= (1<<MD_DISK_SYNC);
3040                 }
3041                 if (test_bit(WriteMostly, &rdev->flags))
3042                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
3043         } else {
3044                 info.major = info.minor = 0;
3045                 info.raid_disk = -1;
3046                 info.state = (1<<MD_DISK_REMOVED);
3047         }
3048
3049         if (copy_to_user(arg, &info, sizeof(info)))
3050                 return -EFAULT;
3051
3052         return 0;
3053 }
3054
3055 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
3056 {
3057         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
3058         mdk_rdev_t *rdev;
3059         dev_t dev = MKDEV(info->major,info->minor);
3060
3061         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
3062                 return -EOVERFLOW;
3063
3064         if (!mddev->raid_disks) {
3065                 int err;
3066                 /* expecting a device which has a superblock */
3067                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
3068                 if (IS_ERR(rdev)) {
3069                         printk(KERN_WARNING 
3070                                 "md: md_import_device returned %ld\n",
3071                                 PTR_ERR(rdev));
3072                         return PTR_ERR(rdev);
3073                 }
3074                 if (!list_empty(&mddev->disks)) {
3075                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
3076                                                         mdk_rdev_t, same_set);
3077                         int err = super_types[mddev->major_version]
3078                                 .load_super(rdev, rdev0, mddev->minor_version);
3079                         if (err < 0) {
3080                                 printk(KERN_WARNING 
3081                                         "md: %s has different UUID to %s\n",
3082                                         bdevname(rdev->bdev,b), 
3083                                         bdevname(rdev0->bdev,b2));
3084                                 export_rdev(rdev);
3085                                 return -EINVAL;
3086                         }
3087                 }
3088                 err = bind_rdev_to_array(rdev, mddev);
3089                 if (err)
3090                         export_rdev(rdev);
3091                 return err;
3092         }
3093
3094         /*
3095          * add_new_disk can be used once the array is assembled
3096          * to add "hot spares".  They must already have a superblock
3097          * written
3098          */
3099         if (mddev->pers) {
3100                 int err;
3101                 if (!mddev->pers->hot_add_disk) {
3102                         printk(KERN_WARNING 
3103                                 "%s: personality does not support diskops!\n",
3104                                mdname(mddev));
3105                         return -EINVAL;
3106                 }
3107                 if (mddev->persistent)
3108                         rdev = md_import_device(dev, mddev->major_version,
3109                                                 mddev->minor_version);
3110                 else
3111                         rdev = md_import_device(dev, -1, -1);
3112                 if (IS_ERR(rdev)) {
3113                         printk(KERN_WARNING 
3114                                 "md: md_import_device returned %ld\n",
3115                                 PTR_ERR(rdev));
3116                         return PTR_ERR(rdev);
3117                 }
3118                 /* set save_raid_disk if appropriate */
3119                 if (!mddev->persistent) {
3120                         if (info->state & (1<<MD_DISK_SYNC)  &&
3121                             info->raid_disk < mddev->raid_disks)
3122                                 rdev->raid_disk = info->raid_disk;
3123                         else
3124                                 rdev->raid_disk = -1;
3125                 } else
3126                         super_types[mddev->major_version].
3127                                 validate_super(mddev, rdev);
3128                 rdev->saved_raid_disk = rdev->raid_disk;
3129
3130                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
3131                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
3132                         set_bit(WriteMostly, &rdev->flags);
3133
3134                 rdev->raid_disk = -1;
3135                 err = bind_rdev_to_array(rdev, mddev);
3136                 if (err)
3137                         export_rdev(rdev);
3138
3139                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3140                 md_wakeup_thread(mddev->thread);
3141                 return err;
3142         }
3143
3144         /* otherwise, add_new_disk is only allowed
3145          * for major_version==0 superblocks
3146          */
3147         if (mddev->major_version != 0) {
3148                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
3149                        mdname(mddev));
3150                 return -EINVAL;
3151         }
3152
3153         if (!(info->state & (1<<MD_DISK_FAULTY))) {
3154                 int err;
3155                 rdev = md_import_device (dev, -1, 0);
3156                 if (IS_ERR(rdev)) {
3157                         printk(KERN_WARNING 
3158                                 "md: error, md_import_device() returned %ld\n",
3159                                 PTR_ERR(rdev));
3160                         return PTR_ERR(rdev);
3161                 }
3162                 rdev->desc_nr = info->number;
3163                 if (info->raid_disk < mddev->raid_disks)
3164                         rdev->raid_disk = info->raid_disk;
3165                 else
3166                         rdev->raid_disk = -1;
3167
3168                 rdev->flags = 0;
3169
3170                 if (rdev->raid_disk < mddev->raid_disks)
3171                         if (info->state & (1<<MD_DISK_SYNC))
3172                                 set_bit(In_sync, &rdev->flags);
3173
3174                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
3175                         set_bit(WriteMostly, &rdev->flags);
3176
3177                 if (!mddev->persistent) {
3178                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
3179                         rdev->sb_offset = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
3180                 } else 
3181                         rdev->sb_offset = calc_dev_sboffset(rdev->bdev);
3182                 rdev->size = calc_dev_size(rdev, mddev->chunk_size);
3183
3184                 err = bind_rdev_to_array(rdev, mddev);
3185                 if (err) {
3186                         export_rdev(rdev);
3187                         return err;
3188                 }
3189         }
3190
3191         return 0;
3192 }
3193
3194 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
3195 {
3196         char b[BDEVNAME_SIZE];
3197         mdk_rdev_t *rdev;
3198
3199         if (!mddev->pers)
3200                 return -ENODEV;
3201
3202         rdev = find_rdev(mddev, dev);
3203         if (!rdev)
3204                 return -ENXIO;
3205
3206         if (rdev->raid_disk >= 0)
3207                 goto busy;
3208
3209         kick_rdev_from_array(rdev);
3210         md_update_sb(mddev);
3211         md_new_event(mddev);
3212
3213         return 0;
3214 busy:
3215         printk(KERN_WARNING "md: cannot remove active disk %s from %s ... \n",
3216                 bdevname(rdev->bdev,b), mdname(mddev));
3217         return -EBUSY;
3218 }
3219
3220 static int hot_add_disk(mddev_t * mddev, dev_t dev)
3221 {
3222         char b[BDEVNAME_SIZE];
3223         int err;
3224         unsigned int size;
3225         mdk_rdev_t *rdev;
3226
3227         if (!mddev->pers)
3228                 return -ENODEV;
3229
3230         if (mddev->major_version != 0) {
3231                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
3232                         " version-0 superblocks.\n",
3233                         mdname(mddev));
3234                 return -EINVAL;
3235         }
3236         if (!mddev->pers->hot_add_disk) {
3237                 printk(KERN_WARNING 
3238                         "%s: personality does not support diskops!\n",
3239                         mdname(mddev));
3240                 return -EINVAL;
3241         }
3242
3243         rdev = md_import_device (dev, -1, 0);
3244         if (IS_ERR(rdev)) {
3245                 printk(KERN_WARNING 
3246                         "md: error, md_import_device() returned %ld\n",
3247                         PTR_ERR(rdev));
3248                 return -EINVAL;
3249         }
3250
3251         if (mddev->persistent)
3252                 rdev->sb_offset = calc_dev_sboffset(rdev->bdev);
3253         else
3254                 rdev->sb_offset =
3255                         rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
3256
3257         size = calc_dev_size(rdev, mddev->chunk_size);
3258         rdev->size = size;
3259
3260         if (test_bit(Faulty, &rdev->flags)) {
3261                 printk(KERN_WARNING 
3262                         "md: can not hot-add faulty %s disk to %s!\n",
3263                         bdevname(rdev->bdev,b), mdname(mddev));
3264                 err = -EINVAL;
3265                 goto abort_export;
3266         }
3267         clear_bit(In_sync, &rdev->flags);
3268         rdev->desc_nr = -1;
3269         err = bind_rdev_to_array(rdev, mddev);
3270         if (err)
3271                 goto abort_export;
3272
3273         /*
3274          * The rest should better be atomic, we can have disk failures
3275          * noticed in interrupt contexts ...
3276          */
3277
3278         if (rdev->desc_nr == mddev->max_disks) {
3279                 printk(KERN_WARNING "%s: can not hot-add to full array!\n",
3280                         mdname(mddev));
3281                 err = -EBUSY;
3282                 goto abort_unbind_export;
3283         }
3284
3285         rdev->raid_disk = -1;
3286
3287         md_update_sb(mddev);
3288
3289         /*
3290          * Kick recovery, maybe this spare has to be added to the
3291          * array immediately.
3292          */
3293         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3294         md_wakeup_thread(mddev->thread);
3295         md_new_event(mddev);
3296         return 0;
3297
3298 abort_unbind_export:
3299         unbind_rdev_from_array(rdev);
3300
3301 abort_export:
3302         export_rdev(rdev);
3303         return err;
3304 }
3305
3306 /* similar to deny_write_access, but accounts for our holding a reference
3307  * to the file ourselves */
3308 static int deny_bitmap_write_access(struct file * file)
3309 {
3310         struct inode *inode = file->f_mapping->host;
3311
3312         spin_lock(&inode->i_lock);
3313         if (atomic_read(&inode->i_writecount) > 1) {
3314                 spin_unlock(&inode->i_lock);
3315                 return -ETXTBSY;
3316         }
3317         atomic_set(&inode->i_writecount, -1);
3318         spin_unlock(&inode->i_lock);
3319
3320         return 0;
3321 }
3322
3323 static int set_bitmap_file(mddev_t *mddev, int fd)
3324 {
3325         int err;
3326
3327         if (mddev->pers) {
3328                 if (!mddev->pers->quiesce)
3329                         return -EBUSY;
3330                 if (mddev->recovery || mddev->sync_thread)
3331                         return -EBUSY;
3332                 /* we should be able to change the bitmap.. */
3333         }
3334
3335
3336         if (fd >= 0) {
3337                 if (mddev->bitmap)
3338                         return -EEXIST; /* cannot add when bitmap is present */
3339                 mddev->bitmap_file = fget(fd);
3340
3341                 if (mddev->bitmap_file == NULL) {
3342                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
3343                                mdname(mddev));
3344                         return -EBADF;
3345                 }
3346
3347                 err = deny_bitmap_write_access(mddev->bitmap_file);
3348                 if (err) {
3349                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
3350                                mdname(mddev));
3351                         fput(mddev->bitmap_file);
3352                         mddev->bitmap_file = NULL;
3353                         return err;
3354                 }
3355                 mddev->bitmap_offset = 0; /* file overrides offset */
3356         } else if (mddev->bitmap == NULL)
3357                 return -ENOENT; /* cannot remove what isn't there */
3358         err = 0;
3359         if (mddev->pers) {
3360                 mddev->pers->quiesce(mddev, 1);
3361                 if (fd >= 0)
3362                         err = bitmap_create(mddev);
3363                 if (fd < 0 || err)
3364                         bitmap_destroy(mddev);
3365                 mddev->pers->quiesce(mddev, 0);
3366         } else if (fd < 0) {
3367                 if (mddev->bitmap_file)
3368                         fput(mddev->bitmap_file);
3369                 mddev->bitmap_file = NULL;
3370         }
3371
3372         return err;
3373 }
3374
3375 /*
3376  * set_array_info is used two different ways
3377  * The original usage is when creating a new array.
3378  * In this usage, raid_disks is > 0 and it together with
3379  *  level, size, not_persistent,layout,chunksize determine the
3380  *  shape of the array.
3381  *  This will always create an array with a type-0.90.0 superblock.
3382  * The newer usage is when assembling an array.
3383  *  In this case raid_disks will be 0, and the major_version field is
3384  *  use to determine which style super-blocks are to be found on the devices.
3385  *  The minor and patch _version numbers are also kept incase the
3386  *  super_block handler wishes to interpret them.
3387  */
3388 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
3389 {
3390
3391         if (info->raid_disks == 0) {
3392                 /* just setting version number for superblock loading */
3393                 if (info->major_version < 0 ||
3394                     info->major_version >= sizeof(super_types)/sizeof(super_types[0]) ||
3395                     super_types[info->major_version].name == NULL) {
3396                         /* maybe try to auto-load a module? */
3397                         printk(KERN_INFO 
3398                                 "md: superblock version %d not known\n",
3399                                 info->major_version);
3400                         return -EINVAL;
3401                 }
3402                 mddev->major_version = info->major_version;
3403                 mddev->minor_version = info->minor_version;
3404                 mddev->patch_version = info->patch_version;
3405                 return 0;
3406         }
3407         mddev->major_version = MD_MAJOR_VERSION;
3408         mddev->minor_version = MD_MINOR_VERSION;
3409         mddev->patch_version = MD_PATCHLEVEL_VERSION;
3410         mddev->ctime         = get_seconds();
3411
3412         mddev->level         = info->level;
3413         mddev->clevel[0]     = 0;
3414         mddev->size          = info->size;
3415         mddev->raid_disks    = info->raid_disks;
3416         /* don't set md_minor, it is determined by which /dev/md* was
3417          * openned
3418          */
3419         if (info->state & (1<<MD_SB_CLEAN))
3420                 mddev->recovery_cp = MaxSector;
3421         else
3422                 mddev->recovery_cp = 0;
3423         mddev->persistent    = ! info->not_persistent;
3424
3425         mddev->layout        = info->layout;
3426         mddev->chunk_size    = info->chunk_size;
3427
3428         mddev->max_disks     = MD_SB_DISKS;
3429
3430         mddev->sb_dirty      = 1;
3431
3432         mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
3433         mddev->bitmap_offset = 0;
3434
3435         /*
3436          * Generate a 128 bit UUID
3437          */
3438         get_random_bytes(mddev->uuid, 16);
3439
3440         return 0;
3441 }
3442
3443 static int update_size(mddev_t *mddev, unsigned long size)
3444 {
3445         mdk_rdev_t * rdev;
3446         int rv;
3447         struct list_head *tmp;
3448
3449         if (mddev->pers->resize == NULL)
3450                 return -EINVAL;
3451         /* The "size" is the amount of each device that is used.
3452          * This can only make sense for arrays with redundancy.
3453          * linear and raid0 always use whatever space is available
3454          * We can only consider changing the size if no resync
3455          * or reconstruction is happening, and if the new size
3456          * is acceptable. It must fit before the sb_offset or,
3457          * if that is <data_offset, it must fit before the
3458          * size of each device.
3459          * If size is zero, we find the largest size that fits.
3460          */
3461         if (mddev->sync_thread)
3462                 return -EBUSY;
3463         ITERATE_RDEV(mddev,rdev,tmp) {
3464                 sector_t avail;
3465                 int fit = (size == 0);
3466                 if (rdev->sb_offset > rdev->data_offset)
3467                         avail = (rdev->sb_offset*2) - rdev->data_offset;
3468                 else
3469                         avail = get_capacity(rdev->bdev->bd_disk)
3470                                 - rdev->data_offset;
3471                 if (fit && (size == 0 || size > avail/2))
3472                         size = avail/2;
3473                 if (avail < ((sector_t)size << 1))
3474                         return -ENOSPC;
3475         }
3476         rv = mddev->pers->resize(mddev, (sector_t)size *2);
3477         if (!rv) {
3478                 struct block_device *bdev;
3479
3480                 bdev = bdget_disk(mddev->gendisk, 0);
3481                 if (bdev) {
3482                         mutex_lock(&bdev->bd_inode->i_mutex);
3483                         i_size_write(bdev->bd_inode, (loff_t)mddev->array_size << 10);
3484                         mutex_unlock(&bdev->bd_inode->i_mutex);
3485                         bdput(bdev);
3486                 }
3487         }
3488         return rv;
3489 }
3490
3491 static int update_raid_disks(mddev_t *mddev, int raid_disks)
3492 {
3493         int rv;
3494         /* change the number of raid disks */
3495         if (mddev->pers->reshape == NULL)
3496                 return -EINVAL;
3497         if (raid_disks <= 0 ||
3498             raid_disks >= mddev->max_disks)
3499                 return -EINVAL;
3500         if (mddev->sync_thread)
3501                 return -EBUSY;
3502         rv = mddev->pers->reshape(mddev, raid_disks);
3503         return rv;
3504 }
3505
3506
3507 /*
3508  * update_array_info is used to change the configuration of an
3509  * on-line array.
3510  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
3511  * fields in the info are checked against the array.
3512  * Any differences that cannot be handled will cause an error.
3513  * Normally, only one change can be managed at a time.
3514  */
3515 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
3516 {
3517         int rv = 0;
3518         int cnt = 0;
3519         int state = 0;
3520
3521         /* calculate expected state,ignoring low bits */
3522         if (mddev->bitmap && mddev->bitmap_offset)
3523                 state |= (1 << MD_SB_BITMAP_PRESENT);
3524
3525         if (mddev->major_version != info->major_version ||
3526             mddev->minor_version != info->minor_version ||
3527 /*          mddev->patch_version != info->patch_version || */
3528             mddev->ctime         != info->ctime         ||
3529             mddev->level         != info->level         ||
3530 /*          mddev->layout        != info->layout        || */
3531             !mddev->persistent   != info->not_persistent||
3532             mddev->chunk_size    != info->chunk_size    ||
3533             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
3534             ((state^info->state) & 0xfffffe00)
3535                 )
3536                 return -EINVAL;
3537         /* Check there is only one change */
3538         if (info->size >= 0 && mddev->size != info->size) cnt++;
3539         if (mddev->raid_disks != info->raid_disks) cnt++;
3540         if (mddev->layout != info->layout) cnt++;
3541         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) cnt++;
3542         if (cnt == 0) return 0;
3543         if (cnt > 1) return -EINVAL;
3544
3545         if (mddev->layout != info->layout) {
3546                 /* Change layout
3547                  * we don't need to do anything at the md level, the
3548                  * personality will take care of it all.
3549                  */
3550                 if (mddev->pers->reconfig == NULL)
3551                         return -EINVAL;
3552                 else
3553                         return mddev->pers->reconfig(mddev, info->layout, -1);
3554         }
3555         if (info->size >= 0 && mddev->size != info->size)
3556                 rv = update_size(mddev, info->size);
3557
3558         if (mddev->raid_disks    != info->raid_disks)
3559                 rv = update_raid_disks(mddev, info->raid_disks);
3560
3561         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
3562                 if (mddev->pers->quiesce == NULL)
3563                         return -EINVAL;
3564                 if (mddev->recovery || mddev->sync_thread)
3565                         return -EBUSY;
3566                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
3567                         /* add the bitmap */
3568                         if (mddev->bitmap)
3569                                 return -EEXIST;
3570                         if (mddev->default_bitmap_offset == 0)
3571                                 return -EINVAL;
3572                         mddev->bitmap_offset = mddev->default_bitmap_offset;
3573                         mddev->pers->quiesce(mddev, 1);
3574                         rv = bitmap_create(mddev);
3575                         if (rv)
3576                                 bitmap_destroy(mddev);
3577                         mddev->pers->quiesce(mddev, 0);
3578                 } else {
3579                         /* remove the bitmap */
3580                         if (!mddev->bitmap)
3581                                 return -ENOENT;
3582                         if (mddev->bitmap->file)
3583                                 return -EINVAL;
3584                         mddev->pers->quiesce(mddev, 1);
3585                         bitmap_destroy(mddev);
3586                         mddev->pers->quiesce(mddev, 0);
3587                         mddev->bitmap_offset = 0;
3588                 }
3589         }
3590         md_update_sb(mddev);
3591         return rv;
3592 }
3593
3594 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
3595 {
3596         mdk_rdev_t *rdev;
3597
3598         if (mddev->pers == NULL)
3599                 return -ENODEV;
3600
3601         rdev = find_rdev(mddev, dev);
3602         if (!rdev)
3603                 return -ENODEV;
3604
3605         md_error(mddev, rdev);
3606         return 0;
3607 }
3608
3609 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
3610 {
3611         mddev_t *mddev = bdev->bd_disk->private_data;
3612
3613         geo->heads = 2;
3614         geo->sectors = 4;
3615         geo->cylinders = get_capacity(mddev->gendisk) / 8;
3616         return 0;
3617 }
3618
3619 static int md_ioctl(struct inode *inode, struct file *file,
3620                         unsigned int cmd, unsigned long arg)
3621 {
3622         int err = 0;
3623         void __user *argp = (void __user *)arg;
3624         mddev_t *mddev = NULL;
3625
3626         if (!capable(CAP_SYS_ADMIN))
3627                 return -EACCES;
3628
3629         /*
3630          * Commands dealing with the RAID driver but not any
3631          * particular array:
3632          */
3633         switch (cmd)
3634         {
3635                 case RAID_VERSION:
3636                         err = get_version(argp);
3637                         goto done;
3638
3639                 case PRINT_RAID_DEBUG:
3640                         err = 0;
3641                         md_print_devices();
3642                         goto done;
3643
3644 #ifndef MODULE
3645                 case RAID_AUTORUN:
3646                         err = 0;
3647                         autostart_arrays(arg);
3648                         goto done;
3649 #endif
3650                 default:;
3651         }
3652
3653         /*
3654          * Commands creating/starting a new array:
3655          */
3656
3657         mddev = inode->i_bdev->bd_disk->private_data;
3658
3659         if (!mddev) {
3660                 BUG();
3661                 goto abort;
3662         }
3663
3664
3665         if (cmd == START_ARRAY) {
3666                 /* START_ARRAY doesn't need to lock the array as autostart_array
3667                  * does the locking, and it could even be a different array
3668                  */
3669                 static int cnt = 3;
3670                 if (cnt > 0 ) {
3671                         printk(KERN_WARNING
3672                                "md: %s(pid %d) used deprecated START_ARRAY ioctl. "
3673                                "This will not be supported beyond July 2006\n",
3674                                current->comm, current->pid);
3675                         cnt--;
3676                 }
3677                 err = autostart_array(new_decode_dev(arg));
3678                 if (err) {
3679                         printk(KERN_WARNING "md: autostart failed!\n");
3680                         goto abort;
3681                 }
3682                 goto done;
3683         }
3684
3685         err = mddev_lock(mddev);
3686         if (err) {
3687                 printk(KERN_INFO 
3688                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
3689                         err, cmd);
3690                 goto abort;
3691         }
3692
3693         switch (cmd)
3694         {
3695                 case SET_ARRAY_INFO:
3696                         {
3697                                 mdu_array_info_t info;
3698                                 if (!arg)
3699                                         memset(&info, 0, sizeof(info));
3700                                 else if (copy_from_user(&info, argp, sizeof(info))) {
3701                                         err = -EFAULT;
3702                                         goto abort_unlock;
3703                                 }
3704                                 if (mddev->pers) {
3705                                         err = update_array_info(mddev, &info);
3706                                         if (err) {
3707                                                 printk(KERN_WARNING "md: couldn't update"
3708                                                        " array info. %d\n", err);
3709                                                 goto abort_unlock;
3710                                         }
3711                                         goto done_unlock;
3712                                 }
3713                                 if (!list_empty(&mddev->disks)) {
3714                                         printk(KERN_WARNING
3715                                                "md: array %s already has disks!\n",
3716                                                mdname(mddev));
3717                                         err = -EBUSY;
3718                                         goto abort_unlock;
3719                                 }
3720                                 if (mddev->raid_disks) {
3721                                         printk(KERN_WARNING
3722                                                "md: array %s already initialised!\n",
3723                                                mdname(mddev));
3724                                         err = -EBUSY;
3725                                         goto abort_unlock;
3726                                 }
3727                                 err = set_array_info(mddev, &info);
3728                                 if (err) {
3729                                         printk(KERN_WARNING "md: couldn't set"
3730                                                " array info. %d\n", err);
3731                                         goto abort_unlock;
3732                                 }
3733                         }
3734                         goto done_unlock;
3735
3736                 default:;
3737         }
3738
3739         /*
3740          * Commands querying/configuring an existing array:
3741          */
3742         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
3743          * RUN_ARRAY, and SET_BITMAP_FILE are allowed */
3744         if (!mddev->raid_disks && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
3745                         && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE) {
3746                 err = -ENODEV;
3747                 goto abort_unlock;
3748         }
3749
3750         /*
3751          * Commands even a read-only array can execute:
3752          */
3753         switch (cmd)
3754         {
3755                 case GET_ARRAY_INFO:
3756                         err = get_array_info(mddev, argp);
3757                         goto done_unlock;
3758
3759                 case GET_BITMAP_FILE:
3760                         err = get_bitmap_file(mddev, argp);
3761                         goto done_unlock;
3762
3763                 case GET_DISK_INFO:
3764                         err = get_disk_info(mddev, argp);
3765                         goto done_unlock;
3766
3767                 case RESTART_ARRAY_RW:
3768                         err = restart_array(mddev);
3769                         goto done_unlock;
3770
3771                 case STOP_ARRAY:
3772                         err = do_md_stop (mddev, 0);
3773                         goto done_unlock;
3774
3775                 case STOP_ARRAY_RO:
3776                         err = do_md_stop (mddev, 1);
3777                         goto done_unlock;
3778
3779         /*
3780          * We have a problem here : there is no easy way to give a CHS
3781          * virtual geometry. We currently pretend that we have a 2 heads
3782          * 4 sectors (with a BIG number of cylinders...). This drives
3783          * dosfs just mad... ;-)
3784          */
3785         }
3786
3787         /*
3788          * The remaining ioctls are changing the state of the
3789          * superblock, so we do not allow them on read-only arrays.
3790          * However non-MD ioctls (e.g. get-size) will still come through
3791          * here and hit the 'default' below, so only disallow
3792          * 'md' ioctls, and switch to rw mode if started auto-readonly.
3793          */
3794         if (_IOC_TYPE(cmd) == MD_MAJOR &&
3795             mddev->ro && mddev->pers) {
3796                 if (mddev->ro == 2) {
3797                         mddev->ro = 0;
3798                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3799                 md_wakeup_thread(mddev->thread);
3800
3801                 } else {
3802                         err = -EROFS;
3803                         goto abort_unlock;
3804                 }
3805         }
3806
3807         switch (cmd)
3808         {
3809                 case ADD_NEW_DISK:
3810                 {
3811                         mdu_disk_info_t info;
3812                         if (copy_from_user(&info, argp, sizeof(info)))
3813                                 err = -EFAULT;
3814                         else
3815                                 err = add_new_disk(mddev, &info);
3816                         goto done_unlock;
3817                 }
3818
3819                 case HOT_REMOVE_DISK:
3820                         err = hot_remove_disk(mddev, new_decode_dev(arg));
3821                         goto done_unlock;
3822
3823                 case HOT_ADD_DISK:
3824                         err = hot_add_disk(mddev, new_decode_dev(arg));
3825                         goto done_unlock;
3826
3827                 case SET_DISK_FAULTY:
3828                         err = set_disk_faulty(mddev, new_decode_dev(arg));
3829                         goto done_unlock;
3830
3831                 case RUN_ARRAY:
3832                         err = do_md_run (mddev);
3833                         goto done_unlock;
3834
3835                 case SET_BITMAP_FILE:
3836                         err = set_bitmap_file(mddev, (int)arg);
3837                         goto done_unlock;
3838
3839                 default:
3840                         if (_IOC_TYPE(cmd) == MD_MAJOR)
3841                                 printk(KERN_WARNING "md: %s(pid %d) used"
3842                                         " obsolete MD ioctl, upgrade your"
3843                                         " software to use new ictls.\n",
3844                                         current->comm, current->pid);
3845                         err = -EINVAL;
3846                         goto abort_unlock;
3847         }
3848
3849 done_unlock:
3850 abort_unlock:
3851         mddev_unlock(mddev);
3852
3853         return err;
3854 done:
3855         if (err)
3856                 MD_BUG();
3857 abort:
3858         return err;
3859 }
3860
3861 static int md_open(struct inode *inode, struct file *file)
3862 {
3863         /*
3864          * Succeed if we can lock the mddev, which confirms that
3865          * it isn't being stopped right now.
3866          */
3867         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
3868         int err;
3869
3870         if ((err = mddev_lock(mddev)))
3871                 goto out;
3872
3873         err = 0;
3874         mddev_get(mddev);
3875         mddev_unlock(mddev);
3876
3877         check_disk_change(inode->i_bdev);
3878  out:
3879         return err;
3880 }
3881
3882 static int md_release(struct inode *inode, struct file * file)
3883 {
3884         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
3885
3886         if (!mddev)
3887                 BUG();
3888         mddev_put(mddev);
3889
3890         return 0;
3891 }
3892
3893 static int md_media_changed(struct gendisk *disk)
3894 {
3895         mddev_t *mddev = disk->private_data;
3896
3897         return mddev->changed;
3898 }
3899
3900 static int md_revalidate(struct gendisk *disk)
3901 {
3902         mddev_t *mddev = disk->private_data;
3903
3904         mddev->changed = 0;
3905         return 0;
3906 }
3907 static struct block_device_operations md_fops =
3908 {
3909         .owner          = THIS_MODULE,
3910         .open           = md_open,
3911         .release        = md_release,
3912         .ioctl          = md_ioctl,
3913         .getgeo         = md_getgeo,
3914         .media_changed  = md_media_changed,
3915         .revalidate_disk= md_revalidate,
3916 };
3917
3918 static int md_thread(void * arg)
3919 {
3920         mdk_thread_t *thread = arg;
3921
3922         /*
3923          * md_thread is a 'system-thread', it's priority should be very
3924          * high. We avoid resource deadlocks individually in each
3925          * raid personality. (RAID5 does preallocation) We also use RR and
3926          * the very same RT priority as kswapd, thus we will never get
3927          * into a priority inversion deadlock.
3928          *
3929          * we definitely have to have equal or higher priority than
3930          * bdflush, otherwise bdflush will deadlock if there are too
3931          * many dirty RAID5 blocks.
3932          */
3933
3934         allow_signal(SIGKILL);
3935         while (!kthread_should_stop()) {
3936
3937                 /* We need to wait INTERRUPTIBLE so that
3938                  * we don't add to the load-average.
3939                  * That means we need to be sure no signals are
3940                  * pending
3941                  */
3942                 if (signal_pending(current))
3943                         flush_signals(current);
3944
3945                 wait_event_interruptible_timeout
3946                         (thread->wqueue,
3947                          test_bit(THREAD_WAKEUP, &thread->flags)
3948                          || kthread_should_stop(),
3949                          thread->timeout);
3950                 try_to_freeze();
3951
3952                 clear_bit(THREAD_WAKEUP, &thread->flags);
3953
3954                 thread->run(thread->mddev);
3955         }
3956
3957         return 0;
3958 }
3959
3960 void md_wakeup_thread(mdk_thread_t *thread)
3961 {
3962         if (thread) {
3963                 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
3964                 set_bit(THREAD_WAKEUP, &thread->flags);
3965                 wake_up(&thread->wqueue);
3966         }
3967 }
3968
3969 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
3970                                  const char *name)
3971 {
3972         mdk_thread_t *thread;
3973
3974         thread = kzalloc(sizeof(mdk_thread_t), GFP_KERNEL);
3975         if (!thread)
3976                 return NULL;
3977
3978         init_waitqueue_head(&thread->wqueue);
3979
3980         thread->run = run;
3981         thread->mddev = mddev;
3982         thread->timeout = MAX_SCHEDULE_TIMEOUT;
3983         thread->tsk = kthread_run(md_thread, thread, name, mdname(thread->mddev));
3984         if (IS_ERR(thread->tsk)) {
3985                 kfree(thread);
3986                 return NULL;
3987         }
3988         return thread;
3989 }
3990
3991 void md_unregister_thread(mdk_thread_t *thread)
3992 {
3993         dprintk("interrupting MD-thread pid %d\n", thread->tsk->pid);
3994
3995         kthread_stop(thread->tsk);
3996         kfree(thread);
3997 }
3998
3999 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
4000 {
4001         if (!mddev) {
4002                 MD_BUG();
4003                 return;
4004         }
4005
4006         if (!rdev || test_bit(Faulty, &rdev->flags))
4007                 return;
4008 /*
4009         dprintk("md_error dev:%s, rdev:(%d:%d), (caller: %p,%p,%p,%p).\n",
4010                 mdname(mddev),
4011                 MAJOR(rdev->bdev->bd_dev), MINOR(rdev->bdev->bd_dev),
4012                 __builtin_return_address(0),__builtin_return_address(1),
4013                 __builtin_return_address(2),__builtin_return_address(3));
4014 */
4015         if (!mddev->pers->error_handler)
4016                 return;
4017         mddev->pers->error_handler(mddev,rdev);
4018         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4019         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4020         md_wakeup_thread(mddev->thread);
4021         md_new_event(mddev);
4022 }
4023
4024 /* seq_file implementation /proc/mdstat */
4025
4026 static void status_unused(struct seq_file *seq)
4027 {
4028         int i = 0;
4029         mdk_rdev_t *rdev;
4030         struct list_head *tmp;
4031
4032         seq_printf(seq, "unused devices: ");
4033
4034         ITERATE_RDEV_PENDING(rdev,tmp) {
4035                 char b[BDEVNAME_SIZE];
4036                 i++;
4037                 seq_printf(seq, "%s ",
4038                               bdevname(rdev->bdev,b));
4039         }
4040         if (!i)
4041                 seq_printf(seq, "<none>");
4042
4043         seq_printf(seq, "\n");
4044 }
4045
4046
4047 static void status_resync(struct seq_file *seq, mddev_t * mddev)
4048 {
4049         sector_t max_blocks, resync, res;
4050         unsigned long dt, db, rt;
4051         int scale;
4052         unsigned int per_milli;
4053
4054         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active))/2;
4055
4056         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
4057                 max_blocks = mddev->resync_max_sectors >> 1;
4058         else
4059                 max_blocks = mddev->size;
4060
4061         /*
4062          * Should not happen.
4063          */
4064         if (!max_blocks) {
4065                 MD_BUG();
4066                 return;
4067         }
4068         /* Pick 'scale' such that (resync>>scale)*1000 will fit
4069          * in a sector_t, and (max_blocks>>scale) will fit in a
4070          * u32, as those are the requirements for sector_div.
4071          * Thus 'scale' must be at least 10
4072          */
4073         scale = 10;
4074         if (sizeof(sector_t) > sizeof(unsigned long)) {
4075                 while ( max_blocks/2 > (1ULL<<(scale+32)))
4076                         scale++;
4077         }
4078         res = (resync>>scale)*1000;
4079         sector_div(res, (u32)((max_blocks>>scale)+1));
4080
4081         per_milli = res;
4082         {
4083                 int i, x = per_milli/50, y = 20-x;
4084                 seq_printf(seq, "[");
4085                 for (i = 0; i < x; i++)
4086                         seq_printf(seq, "=");
4087                 seq_printf(seq, ">");
4088                 for (i = 0; i < y; i++)
4089                         seq_printf(seq, ".");
4090                 seq_printf(seq, "] ");
4091         }
4092         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
4093                    (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
4094                     "reshape" :
4095                       (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
4096                        "resync" : "recovery")),
4097                       per_milli/10, per_milli % 10,
4098                    (unsigned long long) resync,
4099                    (unsigned long long) max_blocks);
4100
4101         /*
4102          * We do not want to overflow, so the order of operands and
4103          * the * 100 / 100 trick are important. We do a +1 to be
4104          * safe against division by zero. We only estimate anyway.
4105          *
4106          * dt: time from mark until now
4107          * db: blocks written from mark until now
4108          * rt: remaining time
4109          */
4110         dt = ((jiffies - mddev->resync_mark) / HZ);
4111         if (!dt) dt++;
4112         db = resync - (mddev->resync_mark_cnt/2);
4113         rt = (dt * ((unsigned long)(max_blocks-resync) / (db/100+1)))/100;
4114
4115         seq_printf(seq, " finish=%lu.%lumin", rt / 60, (rt % 60)/6);
4116
4117         seq_printf(seq, " speed=%ldK/sec", db/dt);
4118 }
4119
4120 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
4121 {
4122         struct list_head *tmp;
4123         loff_t l = *pos;
4124         mddev_t *mddev;
4125
4126         if (l >= 0x10000)
4127                 return NULL;
4128         if (!l--)
4129                 /* header */
4130                 return (void*)1;
4131
4132         spin_lock(&all_mddevs_lock);
4133         list_for_each(tmp,&all_mddevs)
4134                 if (!l--) {
4135                         mddev = list_entry(tmp, mddev_t, all_mddevs);
4136                         mddev_get(mddev);
4137                         spin_unlock(&all_mddevs_lock);
4138                         return mddev;
4139                 }
4140         spin_unlock(&all_mddevs_lock);
4141         if (!l--)
4142                 return (void*)2;/* tail */
4143         return NULL;
4144 }
4145
4146 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4147 {
4148         struct list_head *tmp;
4149         mddev_t *next_mddev, *mddev = v;
4150         
4151         ++*pos;
4152         if (v == (void*)2)
4153                 return NULL;
4154
4155         spin_lock(&all_mddevs_lock);
4156         if (v == (void*)1)
4157                 tmp = all_mddevs.next;
4158         else
4159                 tmp = mddev->all_mddevs.next;
4160         if (tmp != &all_mddevs)
4161                 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
4162         else {
4163                 next_mddev = (void*)2;
4164                 *pos = 0x10000;
4165         }               
4166         spin_unlock(&all_mddevs_lock);
4167
4168         if (v != (void*)1)
4169                 mddev_put(mddev);
4170         return next_mddev;
4171
4172 }
4173
4174 static void md_seq_stop(struct seq_file *seq, void *v)
4175 {
4176         mddev_t *mddev = v;
4177
4178         if (mddev && v != (void*)1 && v != (void*)2)
4179                 mddev_put(mddev);
4180 }
4181
4182 struct mdstat_info {
4183         int event;
4184 };
4185
4186 static int md_seq_show(struct seq_file *seq, void *v)
4187 {
4188         mddev_t *mddev = v;
4189         sector_t size;
4190         struct list_head *tmp2;
4191         mdk_rdev_t *rdev;
4192         struct mdstat_info *mi = seq->private;
4193         struct bitmap *bitmap;
4194
4195         if (v == (void*)1) {
4196                 struct mdk_personality *pers;
4197                 seq_printf(seq, "Personalities : ");
4198                 spin_lock(&pers_lock);
4199                 list_for_each_entry(pers, &pers_list, list)
4200                         seq_printf(seq, "[%s] ", pers->name);
4201
4202                 spin_unlock(&pers_lock);
4203                 seq_printf(seq, "\n");
4204                 mi->event = atomic_read(&md_event_count);
4205                 return 0;
4206         }
4207         if (v == (void*)2) {
4208                 status_unused(seq);
4209                 return 0;
4210         }
4211
4212         if (mddev_lock(mddev)!=0) 
4213                 return -EINTR;
4214         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
4215                 seq_printf(seq, "%s : %sactive", mdname(mddev),
4216                                                 mddev->pers ? "" : "in");
4217                 if (mddev->pers) {
4218                         if (mddev->ro==1)
4219                                 seq_printf(seq, " (read-only)");
4220                         if (mddev->ro==2)
4221                                 seq_printf(seq, "(auto-read-only)");
4222                         seq_printf(seq, " %s", mddev->pers->name);
4223                 }
4224
4225                 size = 0;
4226                 ITERATE_RDEV(mddev,rdev,tmp2) {
4227                         char b[BDEVNAME_SIZE];
4228                         seq_printf(seq, " %s[%d]",
4229                                 bdevname(rdev->bdev,b), rdev->desc_nr);
4230                         if (test_bit(WriteMostly, &rdev->flags))
4231                                 seq_printf(seq, "(W)");
4232                         if (test_bit(Faulty, &rdev->flags)) {
4233                                 seq_printf(seq, "(F)");
4234                                 continue;
4235                         } else if (rdev->raid_disk < 0)
4236                                 seq_printf(seq, "(S)"); /* spare */
4237                         size += rdev->size;
4238                 }
4239
4240                 if (!list_empty(&mddev->disks)) {
4241                         if (mddev->pers)
4242                                 seq_printf(seq, "\n      %llu blocks",
4243                                         (unsigned long long)mddev->array_size);
4244                         else
4245                                 seq_printf(seq, "\n      %llu blocks",
4246                                         (unsigned long long)size);
4247                 }
4248                 if (mddev->persistent) {
4249                         if (mddev->major_version != 0 ||
4250                             mddev->minor_version != 90) {
4251                                 seq_printf(seq," super %d.%d",
4252                                            mddev->major_version,
4253                                            mddev->minor_version);
4254                         }
4255                 } else
4256                         seq_printf(seq, " super non-persistent");
4257
4258                 if (mddev->pers) {
4259                         mddev->pers->status (seq, mddev);
4260                         seq_printf(seq, "\n      ");
4261                         if (mddev->pers->sync_request) {
4262                                 if (mddev->curr_resync > 2) {
4263                                         status_resync (seq, mddev);
4264                                         seq_printf(seq, "\n      ");
4265                                 } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
4266                                         seq_printf(seq, "\tresync=DELAYED\n      ");
4267                                 else if (mddev->recovery_cp < MaxSector)
4268                                         seq_printf(seq, "\tresync=PENDING\n      ");
4269                         }
4270                 } else
4271                         seq_printf(seq, "\n       ");
4272
4273                 if ((bitmap = mddev->bitmap)) {
4274                         unsigned long chunk_kb;
4275                         unsigned long flags;
4276                         spin_lock_irqsave(&bitmap->lock, flags);
4277                         chunk_kb = bitmap->chunksize >> 10;
4278                         seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
4279                                 "%lu%s chunk",
4280                                 bitmap->pages - bitmap->missing_pages,
4281                                 bitmap->pages,
4282                                 (bitmap->pages - bitmap->missing_pages)
4283                                         << (PAGE_SHIFT - 10),
4284                                 chunk_kb ? chunk_kb : bitmap->chunksize,
4285                                 chunk_kb ? "KB" : "B");
4286                         if (bitmap->file) {
4287                                 seq_printf(seq, ", file: ");
4288                                 seq_path(seq, bitmap->file->f_vfsmnt,
4289                                          bitmap->file->f_dentry," \t\n");
4290                         }
4291
4292                         seq_printf(seq, "\n");
4293                         spin_unlock_irqrestore(&bitmap->lock, flags);
4294                 }
4295
4296                 seq_printf(seq, "\n");
4297         }
4298         mddev_unlock(mddev);
4299         
4300         return 0;
4301 }
4302
4303 static struct seq_operations md_seq_ops = {
4304         .start  = md_seq_start,
4305         .next   = md_seq_next,
4306         .stop   = md_seq_stop,
4307         .show   = md_seq_show,
4308 };
4309
4310 static int md_seq_open(struct inode *inode, struct file *file)
4311 {
4312         int error;
4313         struct mdstat_info *mi = kmalloc(sizeof(*mi), GFP_KERNEL);
4314         if (mi == NULL)
4315                 return -ENOMEM;
4316
4317         error = seq_open(file, &md_seq_ops);
4318         if (error)
4319                 kfree(mi);
4320         else {
4321                 struct seq_file *p = file->private_data;
4322                 p->private = mi;
4323                 mi->event = atomic_read(&md_event_count);
4324         }
4325         return error;
4326 }
4327
4328 static int md_seq_release(struct inode *inode, struct file *file)
4329 {
4330         struct seq_file *m = file->private_data;
4331         struct mdstat_info *mi = m->private;
4332         m->private = NULL;
4333         kfree(mi);
4334         return seq_release(inode, file);
4335 }
4336
4337 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
4338 {
4339         struct seq_file *m = filp->private_data;
4340         struct mdstat_info *mi = m->private;
4341         int mask;
4342
4343         poll_wait(filp, &md_event_waiters, wait);
4344
4345         /* always allow read */
4346         mask = POLLIN | POLLRDNORM;
4347
4348         if (mi->event != atomic_read(&md_event_count))
4349                 mask |= POLLERR | POLLPRI;
4350         return mask;
4351 }
4352
4353 static struct file_operations md_seq_fops = {
4354         .open           = md_seq_open,
4355         .read           = seq_read,
4356         .llseek         = seq_lseek,
4357         .release        = md_seq_release,
4358         .poll           = mdstat_poll,
4359 };
4360
4361 int register_md_personality(struct mdk_personality *p)
4362 {
4363         spin_lock(&pers_lock);
4364         list_add_tail(&p->list, &pers_list);
4365         printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
4366         spin_unlock(&pers_lock);
4367         return 0;
4368 }
4369
4370 int unregister_md_personality(struct mdk_personality *p)
4371 {
4372         printk(KERN_INFO "md: %s personality unregistered\n", p->name);
4373         spin_lock(&pers_lock);
4374         list_del_init(&p->list);
4375         spin_unlock(&pers_lock);
4376         return 0;
4377 }
4378
4379 static int is_mddev_idle(mddev_t *mddev)
4380 {
4381         mdk_rdev_t * rdev;
4382         struct list_head *tmp;
4383         int idle;
4384         unsigned long curr_events;
4385
4386         idle = 1;
4387         ITERATE_RDEV(mddev,rdev,tmp) {
4388                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
4389                 curr_events = disk_stat_read(disk, sectors[0]) + 
4390                                 disk_stat_read(disk, sectors[1]) - 
4391                                 atomic_read(&disk->sync_io);
4392                 /* The difference between curr_events and last_events
4393                  * will be affected by any new non-sync IO (making
4394                  * curr_events bigger) and any difference in the amount of
4395                  * in-flight syncio (making current_events bigger or smaller)
4396                  * The amount in-flight is currently limited to
4397                  * 32*64K in raid1/10 and 256*PAGE_SIZE in raid5/6
4398                  * which is at most 4096 sectors.
4399                  * These numbers are fairly fragile and should be made
4400                  * more robust, probably by enforcing the
4401                  * 'window size' that md_do_sync sort-of uses.
4402                  *
4403                  * Note: the following is an unsigned comparison.
4404                  */
4405                 if ((curr_events - rdev->last_events + 4096) > 8192) {
4406                         rdev->last_events = curr_events;
4407                         idle = 0;
4408                 }
4409         }
4410         return idle;
4411 }
4412
4413 void md_done_sync(mddev_t *mddev, int blocks, int ok)
4414 {
4415         /* another "blocks" (512byte) blocks have been synced */
4416         atomic_sub(blocks, &mddev->recovery_active);
4417         wake_up(&mddev->recovery_wait);
4418         if (!ok) {
4419                 set_bit(MD_RECOVERY_ERR, &mddev->recovery);
4420                 md_wakeup_thread(mddev->thread);
4421                 // stop recovery, signal do_sync ....
4422         }
4423 }
4424
4425
4426 /* md_write_start(mddev, bi)
4427  * If we need to update some array metadata (e.g. 'active' flag
4428  * in superblock) before writing, schedule a superblock update
4429  * and wait for it to complete.
4430  */
4431 void md_write_start(mddev_t *mddev, struct bio *bi)
4432 {
4433         if (bio_data_dir(bi) != WRITE)
4434                 return;
4435
4436         BUG_ON(mddev->ro == 1);
4437         if (mddev->ro == 2) {
4438                 /* need to switch to read/write */
4439                 mddev->ro = 0;
4440                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4441                 md_wakeup_thread(mddev->thread);
4442         }
4443         atomic_inc(&mddev->writes_pending);
4444         if (mddev->in_sync) {
4445                 spin_lock_irq(&mddev->write_lock);
4446                 if (mddev->in_sync) {
4447                         mddev->in_sync = 0;
4448                         mddev->sb_dirty = 1;
4449                         md_wakeup_thread(mddev->thread);
4450                 }
4451                 spin_unlock_irq(&mddev->write_lock);
4452         }
4453         wait_event(mddev->sb_wait, mddev->sb_dirty==0);
4454 }
4455
4456 void md_write_end(mddev_t *mddev)
4457 {
4458         if (atomic_dec_and_test(&mddev->writes_pending)) {
4459                 if (mddev->safemode == 2)
4460                         md_wakeup_thread(mddev->thread);
4461                 else
4462                         mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
4463         }
4464 }
4465
4466 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
4467
4468 #define SYNC_MARKS      10
4469 #define SYNC_MARK_STEP  (3*HZ)
4470 static void md_do_sync(mddev_t *mddev)
4471 {
4472         mddev_t *mddev2;
4473         unsigned int currspeed = 0,
4474                  window;
4475         sector_t max_sectors,j, io_sectors;
4476         unsigned long mark[SYNC_MARKS];
4477         sector_t mark_cnt[SYNC_MARKS];
4478         int last_mark,m;
4479         struct list_head *tmp;
4480         sector_t last_check;
4481         int skipped = 0;
4482
4483         /* just incase thread restarts... */
4484         if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
4485                 return;
4486
4487         /* we overload curr_resync somewhat here.
4488          * 0 == not engaged in resync at all
4489          * 2 == checking that there is no conflict with another sync
4490          * 1 == like 2, but have yielded to allow conflicting resync to
4491          *              commense
4492          * other == active in resync - this many blocks
4493          *
4494          * Before starting a resync we must have set curr_resync to
4495          * 2, and then checked that every "conflicting" array has curr_resync
4496          * less than ours.  When we find one that is the same or higher
4497          * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
4498          * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
4499          * This will mean we have to start checking from the beginning again.
4500          *
4501          */
4502
4503         do {
4504                 mddev->curr_resync = 2;
4505
4506         try_again:
4507                 if (kthread_should_stop()) {
4508                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4509                         goto skip;
4510                 }
4511                 ITERATE_MDDEV(mddev2,tmp) {
4512                         if (mddev2 == mddev)
4513                                 continue;
4514                         if (mddev2->curr_resync && 
4515                             match_mddev_units(mddev,mddev2)) {
4516                                 DEFINE_WAIT(wq);
4517                                 if (mddev < mddev2 && mddev->curr_resync == 2) {
4518                                         /* arbitrarily yield */
4519                                         mddev->curr_resync = 1;
4520                                         wake_up(&resync_wait);
4521                                 }
4522                                 if (mddev > mddev2 && mddev->curr_resync == 1)
4523                                         /* no need to wait here, we can wait the next
4524                                          * time 'round when curr_resync == 2
4525                                          */
4526                                         continue;
4527                                 prepare_to_wait(&resync_wait, &wq, TASK_UNINTERRUPTIBLE);
4528                                 if (!kthread_should_stop() &&
4529                                     mddev2->curr_resync >= mddev->curr_resync) {
4530                                         printk(KERN_INFO "md: delaying resync of %s"
4531                                                " until %s has finished resync (they"
4532                                                " share one or more physical units)\n",
4533                                                mdname(mddev), mdname(mddev2));
4534                                         mddev_put(mddev2);
4535                                         schedule();
4536                                         finish_wait(&resync_wait, &wq);
4537                                         goto try_again;
4538                                 }
4539                                 finish_wait(&resync_wait, &wq);
4540                         }
4541                 }
4542         } while (mddev->curr_resync < 2);
4543
4544         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4545                 /* resync follows the size requested by the personality,
4546                  * which defaults to physical size, but can be virtual size
4547                  */
4548                 max_sectors = mddev->resync_max_sectors;
4549                 mddev->resync_mismatches = 0;
4550         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4551                 max_sectors = mddev->size << 1;
4552         else
4553                 /* recovery follows the physical size of devices */
4554                 max_sectors = mddev->size << 1;
4555
4556         printk(KERN_INFO "md: syncing RAID array %s\n", mdname(mddev));
4557         printk(KERN_INFO "md: minimum _guaranteed_ reconstruction speed:"
4558                 " %d KB/sec/disc.\n", speed_min(mddev));
4559         printk(KERN_INFO "md: using maximum available idle IO bandwidth "
4560                "(but not more than %d KB/sec) for reconstruction.\n",
4561                speed_max(mddev));
4562
4563         is_mddev_idle(mddev); /* this also initializes IO event counters */
4564         /* we don't use the checkpoint if there's a bitmap */
4565         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) && !mddev->bitmap
4566             && ! test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
4567                 j = mddev->recovery_cp;
4568         else
4569                 j = 0;
4570         io_sectors = 0;
4571         for (m = 0; m < SYNC_MARKS; m++) {
4572                 mark[m] = jiffies;
4573                 mark_cnt[m] = io_sectors;
4574         }
4575         last_mark = 0;
4576         mddev->resync_mark = mark[last_mark];
4577         mddev->resync_mark_cnt = mark_cnt[last_mark];
4578
4579         /*
4580          * Tune reconstruction:
4581          */
4582         window = 32*(PAGE_SIZE/512);
4583         printk(KERN_INFO "md: using %dk window, over a total of %llu blocks.\n",
4584                 window/2,(unsigned long long) max_sectors/2);
4585
4586         atomic_set(&mddev->recovery_active, 0);
4587         init_waitqueue_head(&mddev->recovery_wait);
4588         last_check = 0;
4589
4590         if (j>2) {
4591                 printk(KERN_INFO 
4592                         "md: resuming recovery of %s from checkpoint.\n",
4593                         mdname(mddev));
4594                 mddev->curr_resync = j;
4595         }
4596
4597         while (j < max_sectors) {
4598                 sector_t sectors;
4599
4600                 skipped = 0;
4601                 sectors = mddev->pers->sync_request(mddev, j, &skipped,
4602                                             currspeed < speed_min(mddev));
4603                 if (sectors == 0) {
4604                         set_bit(MD_RECOVERY_ERR, &mddev->recovery);
4605                         goto out;
4606                 }
4607
4608                 if (!skipped) { /* actual IO requested */
4609                         io_sectors += sectors;
4610                         atomic_add(sectors, &mddev->recovery_active);
4611                 }
4612
4613                 j += sectors;
4614                 if (j>1) mddev->curr_resync = j;
4615                 if (last_check == 0)
4616                         /* this is the earliers that rebuilt will be
4617                          * visible in /proc/mdstat
4618                          */
4619                         md_new_event(mddev);
4620
4621                 if (last_check + window > io_sectors || j == max_sectors)
4622                         continue;
4623
4624                 last_check = io_sectors;
4625
4626                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery) ||
4627                     test_bit(MD_RECOVERY_ERR, &mddev->recovery))
4628                         break;
4629
4630         repeat:
4631                 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
4632                         /* step marks */
4633                         int next = (last_mark+1) % SYNC_MARKS;
4634
4635                         mddev->resync_mark = mark[next];
4636                         mddev->resync_mark_cnt = mark_cnt[next];
4637                         mark[next] = jiffies;
4638                         mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
4639                         last_mark = next;
4640                 }
4641
4642
4643                 if (kthread_should_stop()) {
4644                         /*
4645                          * got a signal, exit.
4646                          */
4647                         printk(KERN_INFO 
4648                                 "md: md_do_sync() got signal ... exiting\n");
4649                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4650                         goto out;
4651                 }
4652
4653                 /*
4654                  * this loop exits only if either when we are slower than
4655                  * the 'hard' speed limit, or the system was IO-idle for
4656                  * a jiffy.
4657                  * the system might be non-idle CPU-wise, but we only care
4658                  * about not overloading the IO subsystem. (things like an
4659                  * e2fsck being done on the RAID array should execute fast)
4660                  */
4661                 mddev->queue->unplug_fn(mddev->queue);
4662                 cond_resched();
4663
4664                 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
4665                         /((jiffies-mddev->resync_mark)/HZ +1) +1;
4666
4667                 if (currspeed > speed_min(mddev)) {
4668                         if ((currspeed > speed_max(mddev)) ||
4669                                         !is_mddev_idle(mddev)) {
4670                                 msleep(500);
4671                                 goto repeat;
4672                         }
4673                 }
4674         }
4675         printk(KERN_INFO "md: %s: sync done.\n",mdname(mddev));
4676         /*
4677          * this also signals 'finished resyncing' to md_stop
4678          */
4679  out:
4680         mddev->queue->unplug_fn(mddev->queue);
4681
4682         wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
4683
4684         /* tell personality that we are finished */
4685         mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
4686
4687         if (!test_bit(MD_RECOVERY_ERR, &mddev->recovery) &&
4688             test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
4689             !test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
4690             mddev->curr_resync > 2 &&
4691             mddev->curr_resync >= mddev->recovery_cp) {
4692                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
4693                         printk(KERN_INFO 
4694                                 "md: checkpointing recovery of %s.\n",
4695                                 mdname(mddev));
4696                         mddev->recovery_cp = mddev->curr_resync;
4697                 } else
4698                         mddev->recovery_cp = MaxSector;
4699         }
4700
4701  skip:
4702         mddev->curr_resync = 0;
4703         wake_up(&resync_wait);
4704         set_bit(MD_RECOVERY_DONE, &mddev->recovery);
4705         md_wakeup_thread(mddev->thread);
4706 }
4707
4708
4709 /*
4710  * This routine is regularly called by all per-raid-array threads to
4711  * deal with generic issues like resync and super-block update.
4712  * Raid personalities that don't have a thread (linear/raid0) do not
4713  * need this as they never do any recovery or update the superblock.
4714  *
4715  * It does not do any resync itself, but rather "forks" off other threads
4716  * to do that as needed.
4717  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
4718  * "->recovery" and create a thread at ->sync_thread.
4719  * When the thread finishes it sets MD_RECOVERY_DONE (and might set MD_RECOVERY_ERR)
4720  * and wakeups up this thread which will reap the thread and finish up.
4721  * This thread also removes any faulty devices (with nr_pending == 0).
4722  *
4723  * The overall approach is:
4724  *  1/ if the superblock needs updating, update it.
4725  *  2/ If a recovery thread is running, don't do anything else.
4726  *  3/ If recovery has finished, clean up, possibly marking spares active.
4727  *  4/ If there are any faulty devices, remove them.
4728  *  5/ If array is degraded, try to add spares devices
4729  *  6/ If array has spares or is not in-sync, start a resync thread.
4730  */
4731 void md_check_recovery(mddev_t *mddev)
4732 {
4733         mdk_rdev_t *rdev;
4734         struct list_head *rtmp;
4735
4736
4737         if (mddev->bitmap)
4738                 bitmap_daemon_work(mddev->bitmap);
4739
4740         if (mddev->ro)
4741                 return;
4742
4743         if (signal_pending(current)) {
4744                 if (mddev->pers->sync_request) {
4745                         printk(KERN_INFO "md: %s in immediate safe mode\n",
4746                                mdname(mddev));
4747                         mddev->safemode = 2;
4748                 }
4749                 flush_signals(current);
4750         }
4751
4752         if ( ! (
4753                 mddev->sb_dirty ||
4754                 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
4755                 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
4756                 (mddev->safemode == 1) ||
4757                 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
4758                  && !mddev->in_sync && mddev->recovery_cp == MaxSector)
4759                 ))
4760                 return;
4761
4762         if (mddev_trylock(mddev)==0) {
4763                 int spares =0;
4764
4765                 spin_lock_irq(&mddev->write_lock);
4766                 if (mddev->safemode && !atomic_read(&mddev->writes_pending) &&
4767                     !mddev->in_sync && mddev->recovery_cp == MaxSector) {
4768                         mddev->in_sync = 1;
4769                         mddev->sb_dirty = 1;
4770                 }
4771                 if (mddev->safemode == 1)
4772                         mddev->safemode = 0;
4773                 spin_unlock_irq(&mddev->write_lock);
4774
4775                 if (mddev->sb_dirty)
4776                         md_update_sb(mddev);
4777
4778
4779                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
4780                     !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
4781                         /* resync/recovery still happening */
4782                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4783                         goto unlock;
4784                 }
4785                 if (mddev->sync_thread) {
4786                         /* resync has finished, collect result */
4787                         md_unregister_thread(mddev->sync_thread);
4788                         mddev->sync_thread = NULL;
4789                         if (!test_bit(MD_RECOVERY_ERR, &mddev->recovery) &&
4790                             !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
4791                                 /* success...*/
4792                                 /* activate any spares */
4793                                 mddev->pers->spare_active(mddev);
4794                         }
4795                         md_update_sb(mddev);
4796
4797                         /* if array is no-longer degraded, then any saved_raid_disk
4798                          * information must be scrapped
4799                          */
4800                         if (!mddev->degraded)
4801                                 ITERATE_RDEV(mddev,rdev,rtmp)
4802                                         rdev->saved_raid_disk = -1;
4803
4804                         mddev->recovery = 0;
4805                         /* flag recovery needed just to double check */
4806                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4807                         md_new_event(mddev);
4808                         goto unlock;
4809                 }
4810                 /* Clear some bits that don't mean anything, but
4811                  * might be left set
4812                  */
4813                 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4814                 clear_bit(MD_RECOVERY_ERR, &mddev->recovery);
4815                 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
4816                 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
4817
4818                 /* no recovery is running.
4819                  * remove any failed drives, then
4820                  * add spares if possible.
4821                  * Spare are also removed and re-added, to allow
4822                  * the personality to fail the re-add.
4823                  */
4824                 ITERATE_RDEV(mddev,rdev,rtmp)
4825                         if (rdev->raid_disk >= 0 &&
4826                             (test_bit(Faulty, &rdev->flags) || ! test_bit(In_sync, &rdev->flags)) &&
4827                             atomic_read(&rdev->nr_pending)==0) {
4828                                 if (mddev->pers->hot_remove_disk(mddev, rdev->raid_disk)==0) {
4829                                         char nm[20];
4830                                         sprintf(nm,"rd%d", rdev->raid_disk);
4831                                         sysfs_remove_link(&mddev->kobj, nm);
4832                                         rdev->raid_disk = -1;
4833                                 }
4834                         }
4835
4836                 if (mddev->degraded) {
4837                         ITERATE_RDEV(mddev,rdev,rtmp)
4838                                 if (rdev->raid_disk < 0
4839                                     && !test_bit(Faulty, &rdev->flags)) {
4840                                         if (mddev->pers->hot_add_disk(mddev,rdev)) {
4841                                                 char nm[20];
4842                                                 sprintf(nm, "rd%d", rdev->raid_disk);
4843                                                 sysfs_create_link(&mddev->kobj, &rdev->kobj, nm);
4844                                                 spares++;
4845                                                 md_new_event(mddev);
4846                                         } else
4847                                                 break;
4848                                 }
4849                 }
4850
4851                 if (spares) {
4852                         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4853                         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4854                 } else if (mddev->recovery_cp < MaxSector) {
4855                         set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4856                 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
4857                         /* nothing to be done ... */
4858                         goto unlock;
4859
4860                 if (mddev->pers->sync_request) {
4861                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4862                         if (spares && mddev->bitmap && ! mddev->bitmap->file) {
4863                                 /* We are adding a device or devices to an array
4864                                  * which has the bitmap stored on all devices.
4865                                  * So make sure all bitmap pages get written
4866                                  */
4867                                 bitmap_write_all(mddev->bitmap);
4868                         }
4869                         mddev->sync_thread = md_register_thread(md_do_sync,
4870                                                                 mddev,
4871                                                                 "%s_resync");
4872                         if (!mddev->sync_thread) {
4873                                 printk(KERN_ERR "%s: could not start resync"
4874                                         " thread...\n", 
4875                                         mdname(mddev));
4876                                 /* leave the spares where they are, it shouldn't hurt */
4877                                 mddev->recovery = 0;
4878                         } else
4879                                 md_wakeup_thread(mddev->sync_thread);
4880                         md_new_event(mddev);
4881                 }
4882         unlock:
4883                 mddev_unlock(mddev);
4884         }
4885 }
4886
4887 static int md_notify_reboot(struct notifier_block *this,
4888                             unsigned long code, void *x)
4889 {
4890         struct list_head *tmp;
4891         mddev_t *mddev;
4892
4893         if ((code == SYS_DOWN) || (code == SYS_HALT) || (code == SYS_POWER_OFF)) {
4894
4895                 printk(KERN_INFO "md: stopping all md devices.\n");
4896
4897                 ITERATE_MDDEV(mddev,tmp)
4898                         if (mddev_trylock(mddev)==0)
4899                                 do_md_stop (mddev, 1);
4900                 /*
4901                  * certain more exotic SCSI devices are known to be
4902                  * volatile wrt too early system reboots. While the
4903                  * right place to handle this issue is the given
4904                  * driver, we do want to have a safe RAID driver ...
4905                  */
4906                 mdelay(1000*1);
4907         }
4908         return NOTIFY_DONE;
4909 }
4910
4911 static struct notifier_block md_notifier = {
4912         .notifier_call  = md_notify_reboot,
4913         .next           = NULL,
4914         .priority       = INT_MAX, /* before any real devices */
4915 };
4916
4917 static void md_geninit(void)
4918 {
4919         struct proc_dir_entry *p;
4920
4921         dprintk("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
4922
4923         p = create_proc_entry("mdstat", S_IRUGO, NULL);
4924         if (p)
4925                 p->proc_fops = &md_seq_fops;
4926 }
4927
4928 static int __init md_init(void)
4929 {
4930         int minor;
4931
4932         printk(KERN_INFO "md: md driver %d.%d.%d MAX_MD_DEVS=%d,"
4933                         " MD_SB_DISKS=%d\n",
4934                         MD_MAJOR_VERSION, MD_MINOR_VERSION,
4935                         MD_PATCHLEVEL_VERSION, MAX_MD_DEVS, MD_SB_DISKS);
4936         printk(KERN_INFO "md: bitmap version %d.%d\n", BITMAP_MAJOR_HI,
4937                         BITMAP_MINOR);
4938
4939         if (register_blkdev(MAJOR_NR, "md"))
4940                 return -1;
4941         if ((mdp_major=register_blkdev(0, "mdp"))<=0) {
4942                 unregister_blkdev(MAJOR_NR, "md");
4943                 return -1;
4944         }
4945         devfs_mk_dir("md");
4946         blk_register_region(MKDEV(MAJOR_NR, 0), MAX_MD_DEVS, THIS_MODULE,
4947                                 md_probe, NULL, NULL);
4948         blk_register_region(MKDEV(mdp_major, 0), MAX_MD_DEVS<<MdpMinorShift, THIS_MODULE,
4949                             md_probe, NULL, NULL);
4950
4951         for (minor=0; minor < MAX_MD_DEVS; ++minor)
4952                 devfs_mk_bdev(MKDEV(MAJOR_NR, minor),
4953                                 S_IFBLK|S_IRUSR|S_IWUSR,
4954                                 "md/%d", minor);
4955
4956         for (minor=0; minor < MAX_MD_DEVS; ++minor)
4957                 devfs_mk_bdev(MKDEV(mdp_major, minor<<MdpMinorShift),
4958                               S_IFBLK|S_IRUSR|S_IWUSR,
4959                               "md/mdp%d", minor);
4960
4961
4962         register_reboot_notifier(&md_notifier);
4963         raid_table_header = register_sysctl_table(raid_root_table, 1);
4964
4965         md_geninit();
4966         return (0);
4967 }
4968
4969
4970 #ifndef MODULE
4971
4972 /*
4973  * Searches all registered partitions for autorun RAID arrays
4974  * at boot time.
4975  */
4976 static dev_t detected_devices[128];
4977 static int dev_cnt;
4978
4979 void md_autodetect_dev(dev_t dev)
4980 {
4981         if (dev_cnt >= 0 && dev_cnt < 127)
4982                 detected_devices[dev_cnt++] = dev;
4983 }
4984
4985
4986 static void autostart_arrays(int part)
4987 {
4988         mdk_rdev_t *rdev;
4989         int i;
4990
4991         printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
4992
4993         for (i = 0; i < dev_cnt; i++) {
4994                 dev_t dev = detected_devices[i];
4995
4996                 rdev = md_import_device(dev,0, 0);
4997                 if (IS_ERR(rdev))
4998                         continue;
4999
5000                 if (test_bit(Faulty, &rdev->flags)) {
5001                         MD_BUG();
5002                         continue;
5003                 }
5004                 list_add(&rdev->same_set, &pending_raid_disks);
5005         }
5006         dev_cnt = 0;
5007
5008         autorun_devices(part);
5009 }
5010
5011 #endif
5012
5013 static __exit void md_exit(void)
5014 {
5015         mddev_t *mddev;
5016         struct list_head *tmp;
5017         int i;
5018         blk_unregister_region(MKDEV(MAJOR_NR,0), MAX_MD_DEVS);
5019         blk_unregister_region(MKDEV(mdp_major,0), MAX_MD_DEVS << MdpMinorShift);
5020         for (i=0; i < MAX_MD_DEVS; i++)
5021                 devfs_remove("md/%d", i);
5022         for (i=0; i < MAX_MD_DEVS; i++)
5023                 devfs_remove("md/d%d", i);
5024
5025         devfs_remove("md");
5026
5027         unregister_blkdev(MAJOR_NR,"md");
5028         unregister_blkdev(mdp_major, "mdp");
5029         unregister_reboot_notifier(&md_notifier);
5030         unregister_sysctl_table(raid_table_header);
5031         remove_proc_entry("mdstat", NULL);
5032         ITERATE_MDDEV(mddev,tmp) {
5033                 struct gendisk *disk = mddev->gendisk;
5034                 if (!disk)
5035                         continue;
5036                 export_array(mddev);
5037                 del_gendisk(disk);
5038                 put_disk(disk);
5039                 mddev->gendisk = NULL;
5040                 mddev_put(mddev);
5041         }
5042 }
5043
5044 module_init(md_init)
5045 module_exit(md_exit)
5046
5047 static int get_ro(char *buffer, struct kernel_param *kp)
5048 {
5049         return sprintf(buffer, "%d", start_readonly);
5050 }
5051 static int set_ro(const char *val, struct kernel_param *kp)
5052 {
5053         char *e;
5054         int num = simple_strtoul(val, &e, 10);
5055         if (*val && (*e == '\0' || *e == '\n')) {
5056                 start_readonly = num;
5057                 return 0;
5058         }
5059         return -EINVAL;
5060 }
5061
5062 module_param_call(start_ro, set_ro, get_ro, NULL, 0600);
5063 module_param(start_dirty_degraded, int, 0644);
5064
5065
5066 EXPORT_SYMBOL(register_md_personality);
5067 EXPORT_SYMBOL(unregister_md_personality);
5068 EXPORT_SYMBOL(md_error);
5069 EXPORT_SYMBOL(md_done_sync);
5070 EXPORT_SYMBOL(md_write_start);
5071 EXPORT_SYMBOL(md_write_end);
5072 EXPORT_SYMBOL(md_register_thread);
5073 EXPORT_SYMBOL(md_unregister_thread);
5074 EXPORT_SYMBOL(md_wakeup_thread);
5075 EXPORT_SYMBOL(md_print_devices);
5076 EXPORT_SYMBOL(md_check_recovery);
5077 MODULE_LICENSE("GPL");
5078 MODULE_ALIAS("md");
5079 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);