[PATCH] md: Allow stripes to be expanded in preparation for expanding an array
[linux-3.10.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_SYNC, &mddev->recovery)) {
2169                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2170                                 type = "resync";
2171                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2172                                 type = "check";
2173                         else
2174                                 type = "repair";
2175                 } else
2176                         type = "recover";
2177         }
2178         return sprintf(page, "%s\n", type);
2179 }
2180
2181 static ssize_t
2182 action_store(mddev_t *mddev, const char *page, size_t len)
2183 {
2184         if (!mddev->pers || !mddev->pers->sync_request)
2185                 return -EINVAL;
2186
2187         if (cmd_match(page, "idle")) {
2188                 if (mddev->sync_thread) {
2189                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2190                         md_unregister_thread(mddev->sync_thread);
2191                         mddev->sync_thread = NULL;
2192                         mddev->recovery = 0;
2193                 }
2194         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2195                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
2196                 return -EBUSY;
2197         else if (cmd_match(page, "resync") || cmd_match(page, "recover"))
2198                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2199         else {
2200                 if (cmd_match(page, "check"))
2201                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
2202                 else if (cmd_match(page, "repair"))
2203                         return -EINVAL;
2204                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
2205                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
2206         }
2207         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2208         md_wakeup_thread(mddev->thread);
2209         return len;
2210 }
2211
2212 static ssize_t
2213 mismatch_cnt_show(mddev_t *mddev, char *page)
2214 {
2215         return sprintf(page, "%llu\n",
2216                        (unsigned long long) mddev->resync_mismatches);
2217 }
2218
2219 static struct md_sysfs_entry
2220 md_scan_mode = __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
2221
2222
2223 static struct md_sysfs_entry
2224 md_mismatches = __ATTR_RO(mismatch_cnt);
2225
2226 static ssize_t
2227 sync_min_show(mddev_t *mddev, char *page)
2228 {
2229         return sprintf(page, "%d (%s)\n", speed_min(mddev),
2230                        mddev->sync_speed_min ? "local": "system");
2231 }
2232
2233 static ssize_t
2234 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
2235 {
2236         int min;
2237         char *e;
2238         if (strncmp(buf, "system", 6)==0) {
2239                 mddev->sync_speed_min = 0;
2240                 return len;
2241         }
2242         min = simple_strtoul(buf, &e, 10);
2243         if (buf == e || (*e && *e != '\n') || min <= 0)
2244                 return -EINVAL;
2245         mddev->sync_speed_min = min;
2246         return len;
2247 }
2248
2249 static struct md_sysfs_entry md_sync_min =
2250 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
2251
2252 static ssize_t
2253 sync_max_show(mddev_t *mddev, char *page)
2254 {
2255         return sprintf(page, "%d (%s)\n", speed_max(mddev),
2256                        mddev->sync_speed_max ? "local": "system");
2257 }
2258
2259 static ssize_t
2260 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
2261 {
2262         int max;
2263         char *e;
2264         if (strncmp(buf, "system", 6)==0) {
2265                 mddev->sync_speed_max = 0;
2266                 return len;
2267         }
2268         max = simple_strtoul(buf, &e, 10);
2269         if (buf == e || (*e && *e != '\n') || max <= 0)
2270                 return -EINVAL;
2271         mddev->sync_speed_max = max;
2272         return len;
2273 }
2274
2275 static struct md_sysfs_entry md_sync_max =
2276 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
2277
2278
2279 static ssize_t
2280 sync_speed_show(mddev_t *mddev, char *page)
2281 {
2282         unsigned long resync, dt, db;
2283         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
2284         dt = ((jiffies - mddev->resync_mark) / HZ);
2285         if (!dt) dt++;
2286         db = resync - (mddev->resync_mark_cnt);
2287         return sprintf(page, "%ld\n", db/dt/2); /* K/sec */
2288 }
2289
2290 static struct md_sysfs_entry
2291 md_sync_speed = __ATTR_RO(sync_speed);
2292
2293 static ssize_t
2294 sync_completed_show(mddev_t *mddev, char *page)
2295 {
2296         unsigned long max_blocks, resync;
2297
2298         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2299                 max_blocks = mddev->resync_max_sectors;
2300         else
2301                 max_blocks = mddev->size << 1;
2302
2303         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
2304         return sprintf(page, "%lu / %lu\n", resync, max_blocks);
2305 }
2306
2307 static struct md_sysfs_entry
2308 md_sync_completed = __ATTR_RO(sync_completed);
2309
2310 static struct attribute *md_default_attrs[] = {
2311         &md_level.attr,
2312         &md_raid_disks.attr,
2313         &md_chunk_size.attr,
2314         &md_size.attr,
2315         &md_metadata.attr,
2316         &md_new_device.attr,
2317         NULL,
2318 };
2319
2320 static struct attribute *md_redundancy_attrs[] = {
2321         &md_scan_mode.attr,
2322         &md_mismatches.attr,
2323         &md_sync_min.attr,
2324         &md_sync_max.attr,
2325         &md_sync_speed.attr,
2326         &md_sync_completed.attr,
2327         NULL,
2328 };
2329 static struct attribute_group md_redundancy_group = {
2330         .name = NULL,
2331         .attrs = md_redundancy_attrs,
2332 };
2333
2334
2335 static ssize_t
2336 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2337 {
2338         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
2339         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
2340         ssize_t rv;
2341
2342         if (!entry->show)
2343                 return -EIO;
2344         mddev_lock(mddev);
2345         rv = entry->show(mddev, page);
2346         mddev_unlock(mddev);
2347         return rv;
2348 }
2349
2350 static ssize_t
2351 md_attr_store(struct kobject *kobj, struct attribute *attr,
2352               const char *page, size_t length)
2353 {
2354         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
2355         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
2356         ssize_t rv;
2357
2358         if (!entry->store)
2359                 return -EIO;
2360         mddev_lock(mddev);
2361         rv = entry->store(mddev, page, length);
2362         mddev_unlock(mddev);
2363         return rv;
2364 }
2365
2366 static void md_free(struct kobject *ko)
2367 {
2368         mddev_t *mddev = container_of(ko, mddev_t, kobj);
2369         kfree(mddev);
2370 }
2371
2372 static struct sysfs_ops md_sysfs_ops = {
2373         .show   = md_attr_show,
2374         .store  = md_attr_store,
2375 };
2376 static struct kobj_type md_ktype = {
2377         .release        = md_free,
2378         .sysfs_ops      = &md_sysfs_ops,
2379         .default_attrs  = md_default_attrs,
2380 };
2381
2382 int mdp_major = 0;
2383
2384 static struct kobject *md_probe(dev_t dev, int *part, void *data)
2385 {
2386         static DECLARE_MUTEX(disks_sem);
2387         mddev_t *mddev = mddev_find(dev);
2388         struct gendisk *disk;
2389         int partitioned = (MAJOR(dev) != MD_MAJOR);
2390         int shift = partitioned ? MdpMinorShift : 0;
2391         int unit = MINOR(dev) >> shift;
2392
2393         if (!mddev)
2394                 return NULL;
2395
2396         down(&disks_sem);
2397         if (mddev->gendisk) {
2398                 up(&disks_sem);
2399                 mddev_put(mddev);
2400                 return NULL;
2401         }
2402         disk = alloc_disk(1 << shift);
2403         if (!disk) {
2404                 up(&disks_sem);
2405                 mddev_put(mddev);
2406                 return NULL;
2407         }
2408         disk->major = MAJOR(dev);
2409         disk->first_minor = unit << shift;
2410         if (partitioned) {
2411                 sprintf(disk->disk_name, "md_d%d", unit);
2412                 sprintf(disk->devfs_name, "md/d%d", unit);
2413         } else {
2414                 sprintf(disk->disk_name, "md%d", unit);
2415                 sprintf(disk->devfs_name, "md/%d", unit);
2416         }
2417         disk->fops = &md_fops;
2418         disk->private_data = mddev;
2419         disk->queue = mddev->queue;
2420         add_disk(disk);
2421         mddev->gendisk = disk;
2422         up(&disks_sem);
2423         mddev->kobj.parent = &disk->kobj;
2424         mddev->kobj.k_name = NULL;
2425         snprintf(mddev->kobj.name, KOBJ_NAME_LEN, "%s", "md");
2426         mddev->kobj.ktype = &md_ktype;
2427         kobject_register(&mddev->kobj);
2428         return NULL;
2429 }
2430
2431 void md_wakeup_thread(mdk_thread_t *thread);
2432
2433 static void md_safemode_timeout(unsigned long data)
2434 {
2435         mddev_t *mddev = (mddev_t *) data;
2436
2437         mddev->safemode = 1;
2438         md_wakeup_thread(mddev->thread);
2439 }
2440
2441 static int start_dirty_degraded;
2442
2443 static int do_md_run(mddev_t * mddev)
2444 {
2445         int err;
2446         int chunk_size;
2447         struct list_head *tmp;
2448         mdk_rdev_t *rdev;
2449         struct gendisk *disk;
2450         struct mdk_personality *pers;
2451         char b[BDEVNAME_SIZE];
2452
2453         if (list_empty(&mddev->disks))
2454                 /* cannot run an array with no devices.. */
2455                 return -EINVAL;
2456
2457         if (mddev->pers)
2458                 return -EBUSY;
2459
2460         /*
2461          * Analyze all RAID superblock(s)
2462          */
2463         if (!mddev->raid_disks)
2464                 analyze_sbs(mddev);
2465
2466         chunk_size = mddev->chunk_size;
2467
2468         if (chunk_size) {
2469                 if (chunk_size > MAX_CHUNK_SIZE) {
2470                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
2471                                 chunk_size, MAX_CHUNK_SIZE);
2472                         return -EINVAL;
2473                 }
2474                 /*
2475                  * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
2476                  */
2477                 if ( (1 << ffz(~chunk_size)) != chunk_size) {
2478                         printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
2479                         return -EINVAL;
2480                 }
2481                 if (chunk_size < PAGE_SIZE) {
2482                         printk(KERN_ERR "too small chunk_size: %d < %ld\n",
2483                                 chunk_size, PAGE_SIZE);
2484                         return -EINVAL;
2485                 }
2486
2487                 /* devices must have minimum size of one chunk */
2488                 ITERATE_RDEV(mddev,rdev,tmp) {
2489                         if (test_bit(Faulty, &rdev->flags))
2490                                 continue;
2491                         if (rdev->size < chunk_size / 1024) {
2492                                 printk(KERN_WARNING
2493                                         "md: Dev %s smaller than chunk_size:"
2494                                         " %lluk < %dk\n",
2495                                         bdevname(rdev->bdev,b),
2496                                         (unsigned long long)rdev->size,
2497                                         chunk_size / 1024);
2498                                 return -EINVAL;
2499                         }
2500                 }
2501         }
2502
2503 #ifdef CONFIG_KMOD
2504         if (mddev->level != LEVEL_NONE)
2505                 request_module("md-level-%d", mddev->level);
2506         else if (mddev->clevel[0])
2507                 request_module("md-%s", mddev->clevel);
2508 #endif
2509
2510         /*
2511          * Drop all container device buffers, from now on
2512          * the only valid external interface is through the md
2513          * device.
2514          * Also find largest hardsector size
2515          */
2516         ITERATE_RDEV(mddev,rdev,tmp) {
2517                 if (test_bit(Faulty, &rdev->flags))
2518                         continue;
2519                 sync_blockdev(rdev->bdev);
2520                 invalidate_bdev(rdev->bdev, 0);
2521         }
2522
2523         md_probe(mddev->unit, NULL, NULL);
2524         disk = mddev->gendisk;
2525         if (!disk)
2526                 return -ENOMEM;
2527
2528         spin_lock(&pers_lock);
2529         pers = find_pers(mddev->level, mddev->clevel);
2530         if (!pers || !try_module_get(pers->owner)) {
2531                 spin_unlock(&pers_lock);
2532                 if (mddev->level != LEVEL_NONE)
2533                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
2534                                mddev->level);
2535                 else
2536                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
2537                                mddev->clevel);
2538                 return -EINVAL;
2539         }
2540         mddev->pers = pers;
2541         spin_unlock(&pers_lock);
2542         mddev->level = pers->level;
2543         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
2544
2545         mddev->recovery = 0;
2546         mddev->resync_max_sectors = mddev->size << 1; /* may be over-ridden by personality */
2547         mddev->barriers_work = 1;
2548         mddev->ok_start_degraded = start_dirty_degraded;
2549
2550         if (start_readonly)
2551                 mddev->ro = 2; /* read-only, but switch on first write */
2552
2553         err = mddev->pers->run(mddev);
2554         if (!err && mddev->pers->sync_request) {
2555                 err = bitmap_create(mddev);
2556                 if (err) {
2557                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
2558                                mdname(mddev), err);
2559                         mddev->pers->stop(mddev);
2560                 }
2561         }
2562         if (err) {
2563                 printk(KERN_ERR "md: pers->run() failed ...\n");
2564                 module_put(mddev->pers->owner);
2565                 mddev->pers = NULL;
2566                 bitmap_destroy(mddev);
2567                 return err;
2568         }
2569         if (mddev->pers->sync_request)
2570                 sysfs_create_group(&mddev->kobj, &md_redundancy_group);
2571         else if (mddev->ro == 2) /* auto-readonly not meaningful */
2572                 mddev->ro = 0;
2573
2574         atomic_set(&mddev->writes_pending,0);
2575         mddev->safemode = 0;
2576         mddev->safemode_timer.function = md_safemode_timeout;
2577         mddev->safemode_timer.data = (unsigned long) mddev;
2578         mddev->safemode_delay = (20 * HZ)/1000 +1; /* 20 msec delay */
2579         mddev->in_sync = 1;
2580
2581         ITERATE_RDEV(mddev,rdev,tmp)
2582                 if (rdev->raid_disk >= 0) {
2583                         char nm[20];
2584                         sprintf(nm, "rd%d", rdev->raid_disk);
2585                         sysfs_create_link(&mddev->kobj, &rdev->kobj, nm);
2586                 }
2587         
2588         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2589         md_wakeup_thread(mddev->thread);
2590         
2591         if (mddev->sb_dirty)
2592                 md_update_sb(mddev);
2593
2594         set_capacity(disk, mddev->array_size<<1);
2595
2596         /* If we call blk_queue_make_request here, it will
2597          * re-initialise max_sectors etc which may have been
2598          * refined inside -> run.  So just set the bits we need to set.
2599          * Most initialisation happended when we called
2600          * blk_queue_make_request(..., md_fail_request)
2601          * earlier.
2602          */
2603         mddev->queue->queuedata = mddev;
2604         mddev->queue->make_request_fn = mddev->pers->make_request;
2605
2606         mddev->changed = 1;
2607         md_new_event(mddev);
2608         return 0;
2609 }
2610
2611 static int restart_array(mddev_t *mddev)
2612 {
2613         struct gendisk *disk = mddev->gendisk;
2614         int err;
2615
2616         /*
2617          * Complain if it has no devices
2618          */
2619         err = -ENXIO;
2620         if (list_empty(&mddev->disks))
2621                 goto out;
2622
2623         if (mddev->pers) {
2624                 err = -EBUSY;
2625                 if (!mddev->ro)
2626                         goto out;
2627
2628                 mddev->safemode = 0;
2629                 mddev->ro = 0;
2630                 set_disk_ro(disk, 0);
2631
2632                 printk(KERN_INFO "md: %s switched to read-write mode.\n",
2633                         mdname(mddev));
2634                 /*
2635                  * Kick recovery or resync if necessary
2636                  */
2637                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2638                 md_wakeup_thread(mddev->thread);
2639                 err = 0;
2640         } else {
2641                 printk(KERN_ERR "md: %s has no personality assigned.\n",
2642                         mdname(mddev));
2643                 err = -EINVAL;
2644         }
2645
2646 out:
2647         return err;
2648 }
2649
2650 static int do_md_stop(mddev_t * mddev, int ro)
2651 {
2652         int err = 0;
2653         struct gendisk *disk = mddev->gendisk;
2654
2655         if (mddev->pers) {
2656                 if (atomic_read(&mddev->active)>2) {
2657                         printk("md: %s still in use.\n",mdname(mddev));
2658                         return -EBUSY;
2659                 }
2660
2661                 if (mddev->sync_thread) {
2662                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2663                         md_unregister_thread(mddev->sync_thread);
2664                         mddev->sync_thread = NULL;
2665                 }
2666
2667                 del_timer_sync(&mddev->safemode_timer);
2668
2669                 invalidate_partition(disk, 0);
2670
2671                 if (ro) {
2672                         err  = -ENXIO;
2673                         if (mddev->ro==1)
2674                                 goto out;
2675                         mddev->ro = 1;
2676                 } else {
2677                         bitmap_flush(mddev);
2678                         md_super_wait(mddev);
2679                         if (mddev->ro)
2680                                 set_disk_ro(disk, 0);
2681                         blk_queue_make_request(mddev->queue, md_fail_request);
2682                         mddev->pers->stop(mddev);
2683                         if (mddev->pers->sync_request)
2684                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
2685
2686                         module_put(mddev->pers->owner);
2687                         mddev->pers = NULL;
2688                         if (mddev->ro)
2689                                 mddev->ro = 0;
2690                 }
2691                 if (!mddev->in_sync) {
2692                         /* mark array as shutdown cleanly */
2693                         mddev->in_sync = 1;
2694                         md_update_sb(mddev);
2695                 }
2696                 if (ro)
2697                         set_disk_ro(disk, 1);
2698         }
2699
2700         /*
2701          * Free resources if final stop
2702          */
2703         if (!ro) {
2704                 mdk_rdev_t *rdev;
2705                 struct list_head *tmp;
2706                 struct gendisk *disk;
2707                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
2708
2709                 bitmap_destroy(mddev);
2710                 if (mddev->bitmap_file) {
2711                         atomic_set(&mddev->bitmap_file->f_dentry->d_inode->i_writecount, 1);
2712                         fput(mddev->bitmap_file);
2713                         mddev->bitmap_file = NULL;
2714                 }
2715                 mddev->bitmap_offset = 0;
2716
2717                 ITERATE_RDEV(mddev,rdev,tmp)
2718                         if (rdev->raid_disk >= 0) {
2719                                 char nm[20];
2720                                 sprintf(nm, "rd%d", rdev->raid_disk);
2721                                 sysfs_remove_link(&mddev->kobj, nm);
2722                         }
2723
2724                 export_array(mddev);
2725
2726                 mddev->array_size = 0;
2727                 disk = mddev->gendisk;
2728                 if (disk)
2729                         set_capacity(disk, 0);
2730                 mddev->changed = 1;
2731         } else
2732                 printk(KERN_INFO "md: %s switched to read-only mode.\n",
2733                         mdname(mddev));
2734         err = 0;
2735         md_new_event(mddev);
2736 out:
2737         return err;
2738 }
2739
2740 static void autorun_array(mddev_t *mddev)
2741 {
2742         mdk_rdev_t *rdev;
2743         struct list_head *tmp;
2744         int err;
2745
2746         if (list_empty(&mddev->disks))
2747                 return;
2748
2749         printk(KERN_INFO "md: running: ");
2750
2751         ITERATE_RDEV(mddev,rdev,tmp) {
2752                 char b[BDEVNAME_SIZE];
2753                 printk("<%s>", bdevname(rdev->bdev,b));
2754         }
2755         printk("\n");
2756
2757         err = do_md_run (mddev);
2758         if (err) {
2759                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
2760                 do_md_stop (mddev, 0);
2761         }
2762 }
2763
2764 /*
2765  * lets try to run arrays based on all disks that have arrived
2766  * until now. (those are in pending_raid_disks)
2767  *
2768  * the method: pick the first pending disk, collect all disks with
2769  * the same UUID, remove all from the pending list and put them into
2770  * the 'same_array' list. Then order this list based on superblock
2771  * update time (freshest comes first), kick out 'old' disks and
2772  * compare superblocks. If everything's fine then run it.
2773  *
2774  * If "unit" is allocated, then bump its reference count
2775  */
2776 static void autorun_devices(int part)
2777 {
2778         struct list_head *tmp;
2779         mdk_rdev_t *rdev0, *rdev;
2780         mddev_t *mddev;
2781         char b[BDEVNAME_SIZE];
2782
2783         printk(KERN_INFO "md: autorun ...\n");
2784         while (!list_empty(&pending_raid_disks)) {
2785                 dev_t dev;
2786                 LIST_HEAD(candidates);
2787                 rdev0 = list_entry(pending_raid_disks.next,
2788                                          mdk_rdev_t, same_set);
2789
2790                 printk(KERN_INFO "md: considering %s ...\n",
2791                         bdevname(rdev0->bdev,b));
2792                 INIT_LIST_HEAD(&candidates);
2793                 ITERATE_RDEV_PENDING(rdev,tmp)
2794                         if (super_90_load(rdev, rdev0, 0) >= 0) {
2795                                 printk(KERN_INFO "md:  adding %s ...\n",
2796                                         bdevname(rdev->bdev,b));
2797                                 list_move(&rdev->same_set, &candidates);
2798                         }
2799                 /*
2800                  * now we have a set of devices, with all of them having
2801                  * mostly sane superblocks. It's time to allocate the
2802                  * mddev.
2803                  */
2804                 if (rdev0->preferred_minor < 0 || rdev0->preferred_minor >= MAX_MD_DEVS) {
2805                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
2806                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
2807                         break;
2808                 }
2809                 if (part)
2810                         dev = MKDEV(mdp_major,
2811                                     rdev0->preferred_minor << MdpMinorShift);
2812                 else
2813                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
2814
2815                 md_probe(dev, NULL, NULL);
2816                 mddev = mddev_find(dev);
2817                 if (!mddev) {
2818                         printk(KERN_ERR 
2819                                 "md: cannot allocate memory for md drive.\n");
2820                         break;
2821                 }
2822                 if (mddev_lock(mddev)) 
2823                         printk(KERN_WARNING "md: %s locked, cannot run\n",
2824                                mdname(mddev));
2825                 else if (mddev->raid_disks || mddev->major_version
2826                          || !list_empty(&mddev->disks)) {
2827                         printk(KERN_WARNING 
2828                                 "md: %s already running, cannot run %s\n",
2829                                 mdname(mddev), bdevname(rdev0->bdev,b));
2830                         mddev_unlock(mddev);
2831                 } else {
2832                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
2833                         ITERATE_RDEV_GENERIC(candidates,rdev,tmp) {
2834                                 list_del_init(&rdev->same_set);
2835                                 if (bind_rdev_to_array(rdev, mddev))
2836                                         export_rdev(rdev);
2837                         }
2838                         autorun_array(mddev);
2839                         mddev_unlock(mddev);
2840                 }
2841                 /* on success, candidates will be empty, on error
2842                  * it won't...
2843                  */
2844                 ITERATE_RDEV_GENERIC(candidates,rdev,tmp)
2845                         export_rdev(rdev);
2846                 mddev_put(mddev);
2847         }
2848         printk(KERN_INFO "md: ... autorun DONE.\n");
2849 }
2850
2851 /*
2852  * import RAID devices based on one partition
2853  * if possible, the array gets run as well.
2854  */
2855
2856 static int autostart_array(dev_t startdev)
2857 {
2858         char b[BDEVNAME_SIZE];
2859         int err = -EINVAL, i;
2860         mdp_super_t *sb = NULL;
2861         mdk_rdev_t *start_rdev = NULL, *rdev;
2862
2863         start_rdev = md_import_device(startdev, 0, 0);
2864         if (IS_ERR(start_rdev))
2865                 return err;
2866
2867
2868         /* NOTE: this can only work for 0.90.0 superblocks */
2869         sb = (mdp_super_t*)page_address(start_rdev->sb_page);
2870         if (sb->major_version != 0 ||
2871             sb->minor_version != 90 ) {
2872                 printk(KERN_WARNING "md: can only autostart 0.90.0 arrays\n");
2873                 export_rdev(start_rdev);
2874                 return err;
2875         }
2876
2877         if (test_bit(Faulty, &start_rdev->flags)) {
2878                 printk(KERN_WARNING 
2879                         "md: can not autostart based on faulty %s!\n",
2880                         bdevname(start_rdev->bdev,b));
2881                 export_rdev(start_rdev);
2882                 return err;
2883         }
2884         list_add(&start_rdev->same_set, &pending_raid_disks);
2885
2886         for (i = 0; i < MD_SB_DISKS; i++) {
2887                 mdp_disk_t *desc = sb->disks + i;
2888                 dev_t dev = MKDEV(desc->major, desc->minor);
2889
2890                 if (!dev)
2891                         continue;
2892                 if (dev == startdev)
2893                         continue;
2894                 if (MAJOR(dev) != desc->major || MINOR(dev) != desc->minor)
2895                         continue;
2896                 rdev = md_import_device(dev, 0, 0);
2897                 if (IS_ERR(rdev))
2898                         continue;
2899
2900                 list_add(&rdev->same_set, &pending_raid_disks);
2901         }
2902
2903         /*
2904          * possibly return codes
2905          */
2906         autorun_devices(0);
2907         return 0;
2908
2909 }
2910
2911
2912 static int get_version(void __user * arg)
2913 {
2914         mdu_version_t ver;
2915
2916         ver.major = MD_MAJOR_VERSION;
2917         ver.minor = MD_MINOR_VERSION;
2918         ver.patchlevel = MD_PATCHLEVEL_VERSION;
2919
2920         if (copy_to_user(arg, &ver, sizeof(ver)))
2921                 return -EFAULT;
2922
2923         return 0;
2924 }
2925
2926 static int get_array_info(mddev_t * mddev, void __user * arg)
2927 {
2928         mdu_array_info_t info;
2929         int nr,working,active,failed,spare;
2930         mdk_rdev_t *rdev;
2931         struct list_head *tmp;
2932
2933         nr=working=active=failed=spare=0;
2934         ITERATE_RDEV(mddev,rdev,tmp) {
2935                 nr++;
2936                 if (test_bit(Faulty, &rdev->flags))
2937                         failed++;
2938                 else {
2939                         working++;
2940                         if (test_bit(In_sync, &rdev->flags))
2941                                 active++;       
2942                         else
2943                                 spare++;
2944                 }
2945         }
2946
2947         info.major_version = mddev->major_version;
2948         info.minor_version = mddev->minor_version;
2949         info.patch_version = MD_PATCHLEVEL_VERSION;
2950         info.ctime         = mddev->ctime;
2951         info.level         = mddev->level;
2952         info.size          = mddev->size;
2953         if (info.size != mddev->size) /* overflow */
2954                 info.size = -1;
2955         info.nr_disks      = nr;
2956         info.raid_disks    = mddev->raid_disks;
2957         info.md_minor      = mddev->md_minor;
2958         info.not_persistent= !mddev->persistent;
2959
2960         info.utime         = mddev->utime;
2961         info.state         = 0;
2962         if (mddev->in_sync)
2963                 info.state = (1<<MD_SB_CLEAN);
2964         if (mddev->bitmap && mddev->bitmap_offset)
2965                 info.state = (1<<MD_SB_BITMAP_PRESENT);
2966         info.active_disks  = active;
2967         info.working_disks = working;
2968         info.failed_disks  = failed;
2969         info.spare_disks   = spare;
2970
2971         info.layout        = mddev->layout;
2972         info.chunk_size    = mddev->chunk_size;
2973
2974         if (copy_to_user(arg, &info, sizeof(info)))
2975                 return -EFAULT;
2976
2977         return 0;
2978 }
2979
2980 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
2981 {
2982         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
2983         char *ptr, *buf = NULL;
2984         int err = -ENOMEM;
2985
2986         file = kmalloc(sizeof(*file), GFP_KERNEL);
2987         if (!file)
2988                 goto out;
2989
2990         /* bitmap disabled, zero the first byte and copy out */
2991         if (!mddev->bitmap || !mddev->bitmap->file) {
2992                 file->pathname[0] = '\0';
2993                 goto copy_out;
2994         }
2995
2996         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
2997         if (!buf)
2998                 goto out;
2999
3000         ptr = file_path(mddev->bitmap->file, buf, sizeof(file->pathname));
3001         if (!ptr)
3002                 goto out;
3003
3004         strcpy(file->pathname, ptr);
3005
3006 copy_out:
3007         err = 0;
3008         if (copy_to_user(arg, file, sizeof(*file)))
3009                 err = -EFAULT;
3010 out:
3011         kfree(buf);
3012         kfree(file);
3013         return err;
3014 }
3015
3016 static int get_disk_info(mddev_t * mddev, void __user * arg)
3017 {
3018         mdu_disk_info_t info;
3019         unsigned int nr;
3020         mdk_rdev_t *rdev;
3021
3022         if (copy_from_user(&info, arg, sizeof(info)))
3023                 return -EFAULT;
3024
3025         nr = info.number;
3026
3027         rdev = find_rdev_nr(mddev, nr);
3028         if (rdev) {
3029                 info.major = MAJOR(rdev->bdev->bd_dev);
3030                 info.minor = MINOR(rdev->bdev->bd_dev);
3031                 info.raid_disk = rdev->raid_disk;
3032                 info.state = 0;
3033                 if (test_bit(Faulty, &rdev->flags))
3034                         info.state |= (1<<MD_DISK_FAULTY);
3035                 else if (test_bit(In_sync, &rdev->flags)) {
3036                         info.state |= (1<<MD_DISK_ACTIVE);
3037                         info.state |= (1<<MD_DISK_SYNC);
3038                 }
3039                 if (test_bit(WriteMostly, &rdev->flags))
3040                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
3041         } else {
3042                 info.major = info.minor = 0;
3043                 info.raid_disk = -1;
3044                 info.state = (1<<MD_DISK_REMOVED);
3045         }
3046
3047         if (copy_to_user(arg, &info, sizeof(info)))
3048                 return -EFAULT;
3049
3050         return 0;
3051 }
3052
3053 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
3054 {
3055         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
3056         mdk_rdev_t *rdev;
3057         dev_t dev = MKDEV(info->major,info->minor);
3058
3059         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
3060                 return -EOVERFLOW;
3061
3062         if (!mddev->raid_disks) {
3063                 int err;
3064                 /* expecting a device which has a superblock */
3065                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
3066                 if (IS_ERR(rdev)) {
3067                         printk(KERN_WARNING 
3068                                 "md: md_import_device returned %ld\n",
3069                                 PTR_ERR(rdev));
3070                         return PTR_ERR(rdev);
3071                 }
3072                 if (!list_empty(&mddev->disks)) {
3073                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
3074                                                         mdk_rdev_t, same_set);
3075                         int err = super_types[mddev->major_version]
3076                                 .load_super(rdev, rdev0, mddev->minor_version);
3077                         if (err < 0) {
3078                                 printk(KERN_WARNING 
3079                                         "md: %s has different UUID to %s\n",
3080                                         bdevname(rdev->bdev,b), 
3081                                         bdevname(rdev0->bdev,b2));
3082                                 export_rdev(rdev);
3083                                 return -EINVAL;
3084                         }
3085                 }
3086                 err = bind_rdev_to_array(rdev, mddev);
3087                 if (err)
3088                         export_rdev(rdev);
3089                 return err;
3090         }
3091
3092         /*
3093          * add_new_disk can be used once the array is assembled
3094          * to add "hot spares".  They must already have a superblock
3095          * written
3096          */
3097         if (mddev->pers) {
3098                 int err;
3099                 if (!mddev->pers->hot_add_disk) {
3100                         printk(KERN_WARNING 
3101                                 "%s: personality does not support diskops!\n",
3102                                mdname(mddev));
3103                         return -EINVAL;
3104                 }
3105                 if (mddev->persistent)
3106                         rdev = md_import_device(dev, mddev->major_version,
3107                                                 mddev->minor_version);
3108                 else
3109                         rdev = md_import_device(dev, -1, -1);
3110                 if (IS_ERR(rdev)) {
3111                         printk(KERN_WARNING 
3112                                 "md: md_import_device returned %ld\n",
3113                                 PTR_ERR(rdev));
3114                         return PTR_ERR(rdev);
3115                 }
3116                 /* set save_raid_disk if appropriate */
3117                 if (!mddev->persistent) {
3118                         if (info->state & (1<<MD_DISK_SYNC)  &&
3119                             info->raid_disk < mddev->raid_disks)
3120                                 rdev->raid_disk = info->raid_disk;
3121                         else
3122                                 rdev->raid_disk = -1;
3123                 } else
3124                         super_types[mddev->major_version].
3125                                 validate_super(mddev, rdev);
3126                 rdev->saved_raid_disk = rdev->raid_disk;
3127
3128                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
3129                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
3130                         set_bit(WriteMostly, &rdev->flags);
3131
3132                 rdev->raid_disk = -1;
3133                 err = bind_rdev_to_array(rdev, mddev);
3134                 if (err)
3135                         export_rdev(rdev);
3136
3137                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3138                 md_wakeup_thread(mddev->thread);
3139                 return err;
3140         }
3141
3142         /* otherwise, add_new_disk is only allowed
3143          * for major_version==0 superblocks
3144          */
3145         if (mddev->major_version != 0) {
3146                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
3147                        mdname(mddev));
3148                 return -EINVAL;
3149         }
3150
3151         if (!(info->state & (1<<MD_DISK_FAULTY))) {
3152                 int err;
3153                 rdev = md_import_device (dev, -1, 0);
3154                 if (IS_ERR(rdev)) {
3155                         printk(KERN_WARNING 
3156                                 "md: error, md_import_device() returned %ld\n",
3157                                 PTR_ERR(rdev));
3158                         return PTR_ERR(rdev);
3159                 }
3160                 rdev->desc_nr = info->number;
3161                 if (info->raid_disk < mddev->raid_disks)
3162                         rdev->raid_disk = info->raid_disk;
3163                 else
3164                         rdev->raid_disk = -1;
3165
3166                 rdev->flags = 0;
3167
3168                 if (rdev->raid_disk < mddev->raid_disks)
3169                         if (info->state & (1<<MD_DISK_SYNC))
3170                                 set_bit(In_sync, &rdev->flags);
3171
3172                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
3173                         set_bit(WriteMostly, &rdev->flags);
3174
3175                 if (!mddev->persistent) {
3176                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
3177                         rdev->sb_offset = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
3178                 } else 
3179                         rdev->sb_offset = calc_dev_sboffset(rdev->bdev);
3180                 rdev->size = calc_dev_size(rdev, mddev->chunk_size);
3181
3182                 err = bind_rdev_to_array(rdev, mddev);
3183                 if (err) {
3184                         export_rdev(rdev);
3185                         return err;
3186                 }
3187         }
3188
3189         return 0;
3190 }
3191
3192 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
3193 {
3194         char b[BDEVNAME_SIZE];
3195         mdk_rdev_t *rdev;
3196
3197         if (!mddev->pers)
3198                 return -ENODEV;
3199
3200         rdev = find_rdev(mddev, dev);
3201         if (!rdev)
3202                 return -ENXIO;
3203
3204         if (rdev->raid_disk >= 0)
3205                 goto busy;
3206
3207         kick_rdev_from_array(rdev);
3208         md_update_sb(mddev);
3209         md_new_event(mddev);
3210
3211         return 0;
3212 busy:
3213         printk(KERN_WARNING "md: cannot remove active disk %s from %s ... \n",
3214                 bdevname(rdev->bdev,b), mdname(mddev));
3215         return -EBUSY;
3216 }
3217
3218 static int hot_add_disk(mddev_t * mddev, dev_t dev)
3219 {
3220         char b[BDEVNAME_SIZE];
3221         int err;
3222         unsigned int size;
3223         mdk_rdev_t *rdev;
3224
3225         if (!mddev->pers)
3226                 return -ENODEV;
3227
3228         if (mddev->major_version != 0) {
3229                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
3230                         " version-0 superblocks.\n",
3231                         mdname(mddev));
3232                 return -EINVAL;
3233         }
3234         if (!mddev->pers->hot_add_disk) {
3235                 printk(KERN_WARNING 
3236                         "%s: personality does not support diskops!\n",
3237                         mdname(mddev));
3238                 return -EINVAL;
3239         }
3240
3241         rdev = md_import_device (dev, -1, 0);
3242         if (IS_ERR(rdev)) {
3243                 printk(KERN_WARNING 
3244                         "md: error, md_import_device() returned %ld\n",
3245                         PTR_ERR(rdev));
3246                 return -EINVAL;
3247         }
3248
3249         if (mddev->persistent)
3250                 rdev->sb_offset = calc_dev_sboffset(rdev->bdev);
3251         else
3252                 rdev->sb_offset =
3253                         rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
3254
3255         size = calc_dev_size(rdev, mddev->chunk_size);
3256         rdev->size = size;
3257
3258         if (test_bit(Faulty, &rdev->flags)) {
3259                 printk(KERN_WARNING 
3260                         "md: can not hot-add faulty %s disk to %s!\n",
3261                         bdevname(rdev->bdev,b), mdname(mddev));
3262                 err = -EINVAL;
3263                 goto abort_export;
3264         }
3265         clear_bit(In_sync, &rdev->flags);
3266         rdev->desc_nr = -1;
3267         err = bind_rdev_to_array(rdev, mddev);
3268         if (err)
3269                 goto abort_export;
3270
3271         /*
3272          * The rest should better be atomic, we can have disk failures
3273          * noticed in interrupt contexts ...
3274          */
3275
3276         if (rdev->desc_nr == mddev->max_disks) {
3277                 printk(KERN_WARNING "%s: can not hot-add to full array!\n",
3278                         mdname(mddev));
3279                 err = -EBUSY;
3280                 goto abort_unbind_export;
3281         }
3282
3283         rdev->raid_disk = -1;
3284
3285         md_update_sb(mddev);
3286
3287         /*
3288          * Kick recovery, maybe this spare has to be added to the
3289          * array immediately.
3290          */
3291         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3292         md_wakeup_thread(mddev->thread);
3293         md_new_event(mddev);
3294         return 0;
3295
3296 abort_unbind_export:
3297         unbind_rdev_from_array(rdev);
3298
3299 abort_export:
3300         export_rdev(rdev);
3301         return err;
3302 }
3303
3304 /* similar to deny_write_access, but accounts for our holding a reference
3305  * to the file ourselves */
3306 static int deny_bitmap_write_access(struct file * file)
3307 {
3308         struct inode *inode = file->f_mapping->host;
3309
3310         spin_lock(&inode->i_lock);
3311         if (atomic_read(&inode->i_writecount) > 1) {
3312                 spin_unlock(&inode->i_lock);
3313                 return -ETXTBSY;
3314         }
3315         atomic_set(&inode->i_writecount, -1);
3316         spin_unlock(&inode->i_lock);
3317
3318         return 0;
3319 }
3320
3321 static int set_bitmap_file(mddev_t *mddev, int fd)
3322 {
3323         int err;
3324
3325         if (mddev->pers) {
3326                 if (!mddev->pers->quiesce)
3327                         return -EBUSY;
3328                 if (mddev->recovery || mddev->sync_thread)
3329                         return -EBUSY;
3330                 /* we should be able to change the bitmap.. */
3331         }
3332
3333
3334         if (fd >= 0) {
3335                 if (mddev->bitmap)
3336                         return -EEXIST; /* cannot add when bitmap is present */
3337                 mddev->bitmap_file = fget(fd);
3338
3339                 if (mddev->bitmap_file == NULL) {
3340                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
3341                                mdname(mddev));
3342                         return -EBADF;
3343                 }
3344
3345                 err = deny_bitmap_write_access(mddev->bitmap_file);
3346                 if (err) {
3347                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
3348                                mdname(mddev));
3349                         fput(mddev->bitmap_file);
3350                         mddev->bitmap_file = NULL;
3351                         return err;
3352                 }
3353                 mddev->bitmap_offset = 0; /* file overrides offset */
3354         } else if (mddev->bitmap == NULL)
3355                 return -ENOENT; /* cannot remove what isn't there */
3356         err = 0;
3357         if (mddev->pers) {
3358                 mddev->pers->quiesce(mddev, 1);
3359                 if (fd >= 0)
3360                         err = bitmap_create(mddev);
3361                 if (fd < 0 || err)
3362                         bitmap_destroy(mddev);
3363                 mddev->pers->quiesce(mddev, 0);
3364         } else if (fd < 0) {
3365                 if (mddev->bitmap_file)
3366                         fput(mddev->bitmap_file);
3367                 mddev->bitmap_file = NULL;
3368         }
3369
3370         return err;
3371 }
3372
3373 /*
3374  * set_array_info is used two different ways
3375  * The original usage is when creating a new array.
3376  * In this usage, raid_disks is > 0 and it together with
3377  *  level, size, not_persistent,layout,chunksize determine the
3378  *  shape of the array.
3379  *  This will always create an array with a type-0.90.0 superblock.
3380  * The newer usage is when assembling an array.
3381  *  In this case raid_disks will be 0, and the major_version field is
3382  *  use to determine which style super-blocks are to be found on the devices.
3383  *  The minor and patch _version numbers are also kept incase the
3384  *  super_block handler wishes to interpret them.
3385  */
3386 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
3387 {
3388
3389         if (info->raid_disks == 0) {
3390                 /* just setting version number for superblock loading */
3391                 if (info->major_version < 0 ||
3392                     info->major_version >= sizeof(super_types)/sizeof(super_types[0]) ||
3393                     super_types[info->major_version].name == NULL) {
3394                         /* maybe try to auto-load a module? */
3395                         printk(KERN_INFO 
3396                                 "md: superblock version %d not known\n",
3397                                 info->major_version);
3398                         return -EINVAL;
3399                 }
3400                 mddev->major_version = info->major_version;
3401                 mddev->minor_version = info->minor_version;
3402                 mddev->patch_version = info->patch_version;
3403                 return 0;
3404         }
3405         mddev->major_version = MD_MAJOR_VERSION;
3406         mddev->minor_version = MD_MINOR_VERSION;
3407         mddev->patch_version = MD_PATCHLEVEL_VERSION;
3408         mddev->ctime         = get_seconds();
3409
3410         mddev->level         = info->level;
3411         mddev->clevel[0]     = 0;
3412         mddev->size          = info->size;
3413         mddev->raid_disks    = info->raid_disks;
3414         /* don't set md_minor, it is determined by which /dev/md* was
3415          * openned
3416          */
3417         if (info->state & (1<<MD_SB_CLEAN))
3418                 mddev->recovery_cp = MaxSector;
3419         else
3420                 mddev->recovery_cp = 0;
3421         mddev->persistent    = ! info->not_persistent;
3422
3423         mddev->layout        = info->layout;
3424         mddev->chunk_size    = info->chunk_size;
3425
3426         mddev->max_disks     = MD_SB_DISKS;
3427
3428         mddev->sb_dirty      = 1;
3429
3430         mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
3431         mddev->bitmap_offset = 0;
3432
3433         /*
3434          * Generate a 128 bit UUID
3435          */
3436         get_random_bytes(mddev->uuid, 16);
3437
3438         return 0;
3439 }
3440
3441 static int update_size(mddev_t *mddev, unsigned long size)
3442 {
3443         mdk_rdev_t * rdev;
3444         int rv;
3445         struct list_head *tmp;
3446
3447         if (mddev->pers->resize == NULL)
3448                 return -EINVAL;
3449         /* The "size" is the amount of each device that is used.
3450          * This can only make sense for arrays with redundancy.
3451          * linear and raid0 always use whatever space is available
3452          * We can only consider changing the size if no resync
3453          * or reconstruction is happening, and if the new size
3454          * is acceptable. It must fit before the sb_offset or,
3455          * if that is <data_offset, it must fit before the
3456          * size of each device.
3457          * If size is zero, we find the largest size that fits.
3458          */
3459         if (mddev->sync_thread)
3460                 return -EBUSY;
3461         ITERATE_RDEV(mddev,rdev,tmp) {
3462                 sector_t avail;
3463                 int fit = (size == 0);
3464                 if (rdev->sb_offset > rdev->data_offset)
3465                         avail = (rdev->sb_offset*2) - rdev->data_offset;
3466                 else
3467                         avail = get_capacity(rdev->bdev->bd_disk)
3468                                 - rdev->data_offset;
3469                 if (fit && (size == 0 || size > avail/2))
3470                         size = avail/2;
3471                 if (avail < ((sector_t)size << 1))
3472                         return -ENOSPC;
3473         }
3474         rv = mddev->pers->resize(mddev, (sector_t)size *2);
3475         if (!rv) {
3476                 struct block_device *bdev;
3477
3478                 bdev = bdget_disk(mddev->gendisk, 0);
3479                 if (bdev) {
3480                         mutex_lock(&bdev->bd_inode->i_mutex);
3481                         i_size_write(bdev->bd_inode, (loff_t)mddev->array_size << 10);
3482                         mutex_unlock(&bdev->bd_inode->i_mutex);
3483                         bdput(bdev);
3484                 }
3485         }
3486         return rv;
3487 }
3488
3489 static int update_raid_disks(mddev_t *mddev, int raid_disks)
3490 {
3491         int rv;
3492         /* change the number of raid disks */
3493         if (mddev->pers->reshape == NULL)
3494                 return -EINVAL;
3495         if (raid_disks <= 0 ||
3496             raid_disks >= mddev->max_disks)
3497                 return -EINVAL;
3498         if (mddev->sync_thread)
3499                 return -EBUSY;
3500         rv = mddev->pers->reshape(mddev, raid_disks);
3501         return rv;
3502 }
3503
3504
3505 /*
3506  * update_array_info is used to change the configuration of an
3507  * on-line array.
3508  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
3509  * fields in the info are checked against the array.
3510  * Any differences that cannot be handled will cause an error.
3511  * Normally, only one change can be managed at a time.
3512  */
3513 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
3514 {
3515         int rv = 0;
3516         int cnt = 0;
3517         int state = 0;
3518
3519         /* calculate expected state,ignoring low bits */
3520         if (mddev->bitmap && mddev->bitmap_offset)
3521                 state |= (1 << MD_SB_BITMAP_PRESENT);
3522
3523         if (mddev->major_version != info->major_version ||
3524             mddev->minor_version != info->minor_version ||
3525 /*          mddev->patch_version != info->patch_version || */
3526             mddev->ctime         != info->ctime         ||
3527             mddev->level         != info->level         ||
3528 /*          mddev->layout        != info->layout        || */
3529             !mddev->persistent   != info->not_persistent||
3530             mddev->chunk_size    != info->chunk_size    ||
3531             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
3532             ((state^info->state) & 0xfffffe00)
3533                 )
3534                 return -EINVAL;
3535         /* Check there is only one change */
3536         if (info->size >= 0 && mddev->size != info->size) cnt++;
3537         if (mddev->raid_disks != info->raid_disks) cnt++;
3538         if (mddev->layout != info->layout) cnt++;
3539         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) cnt++;
3540         if (cnt == 0) return 0;
3541         if (cnt > 1) return -EINVAL;
3542
3543         if (mddev->layout != info->layout) {
3544                 /* Change layout
3545                  * we don't need to do anything at the md level, the
3546                  * personality will take care of it all.
3547                  */
3548                 if (mddev->pers->reconfig == NULL)
3549                         return -EINVAL;
3550                 else
3551                         return mddev->pers->reconfig(mddev, info->layout, -1);
3552         }
3553         if (info->size >= 0 && mddev->size != info->size)
3554                 rv = update_size(mddev, info->size);
3555
3556         if (mddev->raid_disks    != info->raid_disks)
3557                 rv = update_raid_disks(mddev, info->raid_disks);
3558
3559         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
3560                 if (mddev->pers->quiesce == NULL)
3561                         return -EINVAL;
3562                 if (mddev->recovery || mddev->sync_thread)
3563                         return -EBUSY;
3564                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
3565                         /* add the bitmap */
3566                         if (mddev->bitmap)
3567                                 return -EEXIST;
3568                         if (mddev->default_bitmap_offset == 0)
3569                                 return -EINVAL;
3570                         mddev->bitmap_offset = mddev->default_bitmap_offset;
3571                         mddev->pers->quiesce(mddev, 1);
3572                         rv = bitmap_create(mddev);
3573                         if (rv)
3574                                 bitmap_destroy(mddev);
3575                         mddev->pers->quiesce(mddev, 0);
3576                 } else {
3577                         /* remove the bitmap */
3578                         if (!mddev->bitmap)
3579                                 return -ENOENT;
3580                         if (mddev->bitmap->file)
3581                                 return -EINVAL;
3582                         mddev->pers->quiesce(mddev, 1);
3583                         bitmap_destroy(mddev);
3584                         mddev->pers->quiesce(mddev, 0);
3585                         mddev->bitmap_offset = 0;
3586                 }
3587         }
3588         md_update_sb(mddev);
3589         return rv;
3590 }
3591
3592 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
3593 {
3594         mdk_rdev_t *rdev;
3595
3596         if (mddev->pers == NULL)
3597                 return -ENODEV;
3598
3599         rdev = find_rdev(mddev, dev);
3600         if (!rdev)
3601                 return -ENODEV;
3602
3603         md_error(mddev, rdev);
3604         return 0;
3605 }
3606
3607 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
3608 {
3609         mddev_t *mddev = bdev->bd_disk->private_data;
3610
3611         geo->heads = 2;
3612         geo->sectors = 4;
3613         geo->cylinders = get_capacity(mddev->gendisk) / 8;
3614         return 0;
3615 }
3616
3617 static int md_ioctl(struct inode *inode, struct file *file,
3618                         unsigned int cmd, unsigned long arg)
3619 {
3620         int err = 0;
3621         void __user *argp = (void __user *)arg;
3622         mddev_t *mddev = NULL;
3623
3624         if (!capable(CAP_SYS_ADMIN))
3625                 return -EACCES;
3626
3627         /*
3628          * Commands dealing with the RAID driver but not any
3629          * particular array:
3630          */
3631         switch (cmd)
3632         {
3633                 case RAID_VERSION:
3634                         err = get_version(argp);
3635                         goto done;
3636
3637                 case PRINT_RAID_DEBUG:
3638                         err = 0;
3639                         md_print_devices();
3640                         goto done;
3641
3642 #ifndef MODULE
3643                 case RAID_AUTORUN:
3644                         err = 0;
3645                         autostart_arrays(arg);
3646                         goto done;
3647 #endif
3648                 default:;
3649         }
3650
3651         /*
3652          * Commands creating/starting a new array:
3653          */
3654
3655         mddev = inode->i_bdev->bd_disk->private_data;
3656
3657         if (!mddev) {
3658                 BUG();
3659                 goto abort;
3660         }
3661
3662
3663         if (cmd == START_ARRAY) {
3664                 /* START_ARRAY doesn't need to lock the array as autostart_array
3665                  * does the locking, and it could even be a different array
3666                  */
3667                 static int cnt = 3;
3668                 if (cnt > 0 ) {
3669                         printk(KERN_WARNING
3670                                "md: %s(pid %d) used deprecated START_ARRAY ioctl. "
3671                                "This will not be supported beyond July 2006\n",
3672                                current->comm, current->pid);
3673                         cnt--;
3674                 }
3675                 err = autostart_array(new_decode_dev(arg));
3676                 if (err) {
3677                         printk(KERN_WARNING "md: autostart failed!\n");
3678                         goto abort;
3679                 }
3680                 goto done;
3681         }
3682
3683         err = mddev_lock(mddev);
3684         if (err) {
3685                 printk(KERN_INFO 
3686                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
3687                         err, cmd);
3688                 goto abort;
3689         }
3690
3691         switch (cmd)
3692         {
3693                 case SET_ARRAY_INFO:
3694                         {
3695                                 mdu_array_info_t info;
3696                                 if (!arg)
3697                                         memset(&info, 0, sizeof(info));
3698                                 else if (copy_from_user(&info, argp, sizeof(info))) {
3699                                         err = -EFAULT;
3700                                         goto abort_unlock;
3701                                 }
3702                                 if (mddev->pers) {
3703                                         err = update_array_info(mddev, &info);
3704                                         if (err) {
3705                                                 printk(KERN_WARNING "md: couldn't update"
3706                                                        " array info. %d\n", err);
3707                                                 goto abort_unlock;
3708                                         }
3709                                         goto done_unlock;
3710                                 }
3711                                 if (!list_empty(&mddev->disks)) {
3712                                         printk(KERN_WARNING
3713                                                "md: array %s already has disks!\n",
3714                                                mdname(mddev));
3715                                         err = -EBUSY;
3716                                         goto abort_unlock;
3717                                 }
3718                                 if (mddev->raid_disks) {
3719                                         printk(KERN_WARNING
3720                                                "md: array %s already initialised!\n",
3721                                                mdname(mddev));
3722                                         err = -EBUSY;
3723                                         goto abort_unlock;
3724                                 }
3725                                 err = set_array_info(mddev, &info);
3726                                 if (err) {
3727                                         printk(KERN_WARNING "md: couldn't set"
3728                                                " array info. %d\n", err);
3729                                         goto abort_unlock;
3730                                 }
3731                         }
3732                         goto done_unlock;
3733
3734                 default:;
3735         }
3736
3737         /*
3738          * Commands querying/configuring an existing array:
3739          */
3740         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
3741          * RUN_ARRAY, and SET_BITMAP_FILE are allowed */
3742         if (!mddev->raid_disks && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
3743                         && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE) {
3744                 err = -ENODEV;
3745                 goto abort_unlock;
3746         }
3747
3748         /*
3749          * Commands even a read-only array can execute:
3750          */
3751         switch (cmd)
3752         {
3753                 case GET_ARRAY_INFO:
3754                         err = get_array_info(mddev, argp);
3755                         goto done_unlock;
3756
3757                 case GET_BITMAP_FILE:
3758                         err = get_bitmap_file(mddev, argp);
3759                         goto done_unlock;
3760
3761                 case GET_DISK_INFO:
3762                         err = get_disk_info(mddev, argp);
3763                         goto done_unlock;
3764
3765                 case RESTART_ARRAY_RW:
3766                         err = restart_array(mddev);
3767                         goto done_unlock;
3768
3769                 case STOP_ARRAY:
3770                         err = do_md_stop (mddev, 0);
3771                         goto done_unlock;
3772
3773                 case STOP_ARRAY_RO:
3774                         err = do_md_stop (mddev, 1);
3775                         goto done_unlock;
3776
3777         /*
3778          * We have a problem here : there is no easy way to give a CHS
3779          * virtual geometry. We currently pretend that we have a 2 heads
3780          * 4 sectors (with a BIG number of cylinders...). This drives
3781          * dosfs just mad... ;-)
3782          */
3783         }
3784
3785         /*
3786          * The remaining ioctls are changing the state of the
3787          * superblock, so we do not allow them on read-only arrays.
3788          * However non-MD ioctls (e.g. get-size) will still come through
3789          * here and hit the 'default' below, so only disallow
3790          * 'md' ioctls, and switch to rw mode if started auto-readonly.
3791          */
3792         if (_IOC_TYPE(cmd) == MD_MAJOR &&
3793             mddev->ro && mddev->pers) {
3794                 if (mddev->ro == 2) {
3795                         mddev->ro = 0;
3796                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3797                 md_wakeup_thread(mddev->thread);
3798
3799                 } else {
3800                         err = -EROFS;
3801                         goto abort_unlock;
3802                 }
3803         }
3804
3805         switch (cmd)
3806         {
3807                 case ADD_NEW_DISK:
3808                 {
3809                         mdu_disk_info_t info;
3810                         if (copy_from_user(&info, argp, sizeof(info)))
3811                                 err = -EFAULT;
3812                         else
3813                                 err = add_new_disk(mddev, &info);
3814                         goto done_unlock;
3815                 }
3816
3817                 case HOT_REMOVE_DISK:
3818                         err = hot_remove_disk(mddev, new_decode_dev(arg));
3819                         goto done_unlock;
3820
3821                 case HOT_ADD_DISK:
3822                         err = hot_add_disk(mddev, new_decode_dev(arg));
3823                         goto done_unlock;
3824
3825                 case SET_DISK_FAULTY:
3826                         err = set_disk_faulty(mddev, new_decode_dev(arg));
3827                         goto done_unlock;
3828
3829                 case RUN_ARRAY:
3830                         err = do_md_run (mddev);
3831                         goto done_unlock;
3832
3833                 case SET_BITMAP_FILE:
3834                         err = set_bitmap_file(mddev, (int)arg);
3835                         goto done_unlock;
3836
3837                 default:
3838                         if (_IOC_TYPE(cmd) == MD_MAJOR)
3839                                 printk(KERN_WARNING "md: %s(pid %d) used"
3840                                         " obsolete MD ioctl, upgrade your"
3841                                         " software to use new ictls.\n",
3842                                         current->comm, current->pid);
3843                         err = -EINVAL;
3844                         goto abort_unlock;
3845         }
3846
3847 done_unlock:
3848 abort_unlock:
3849         mddev_unlock(mddev);
3850
3851         return err;
3852 done:
3853         if (err)
3854                 MD_BUG();
3855 abort:
3856         return err;
3857 }
3858
3859 static int md_open(struct inode *inode, struct file *file)
3860 {
3861         /*
3862          * Succeed if we can lock the mddev, which confirms that
3863          * it isn't being stopped right now.
3864          */
3865         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
3866         int err;
3867
3868         if ((err = mddev_lock(mddev)))
3869                 goto out;
3870
3871         err = 0;
3872         mddev_get(mddev);
3873         mddev_unlock(mddev);
3874
3875         check_disk_change(inode->i_bdev);
3876  out:
3877         return err;
3878 }
3879
3880 static int md_release(struct inode *inode, struct file * file)
3881 {
3882         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
3883
3884         if (!mddev)
3885                 BUG();
3886         mddev_put(mddev);
3887
3888         return 0;
3889 }
3890
3891 static int md_media_changed(struct gendisk *disk)
3892 {
3893         mddev_t *mddev = disk->private_data;
3894
3895         return mddev->changed;
3896 }
3897
3898 static int md_revalidate(struct gendisk *disk)
3899 {
3900         mddev_t *mddev = disk->private_data;
3901
3902         mddev->changed = 0;
3903         return 0;
3904 }
3905 static struct block_device_operations md_fops =
3906 {
3907         .owner          = THIS_MODULE,
3908         .open           = md_open,
3909         .release        = md_release,
3910         .ioctl          = md_ioctl,
3911         .getgeo         = md_getgeo,
3912         .media_changed  = md_media_changed,
3913         .revalidate_disk= md_revalidate,
3914 };
3915
3916 static int md_thread(void * arg)
3917 {
3918         mdk_thread_t *thread = arg;
3919
3920         /*
3921          * md_thread is a 'system-thread', it's priority should be very
3922          * high. We avoid resource deadlocks individually in each
3923          * raid personality. (RAID5 does preallocation) We also use RR and
3924          * the very same RT priority as kswapd, thus we will never get
3925          * into a priority inversion deadlock.
3926          *
3927          * we definitely have to have equal or higher priority than
3928          * bdflush, otherwise bdflush will deadlock if there are too
3929          * many dirty RAID5 blocks.
3930          */
3931
3932         allow_signal(SIGKILL);
3933         while (!kthread_should_stop()) {
3934
3935                 /* We need to wait INTERRUPTIBLE so that
3936                  * we don't add to the load-average.
3937                  * That means we need to be sure no signals are
3938                  * pending
3939                  */
3940                 if (signal_pending(current))
3941                         flush_signals(current);
3942
3943                 wait_event_interruptible_timeout
3944                         (thread->wqueue,
3945                          test_bit(THREAD_WAKEUP, &thread->flags)
3946                          || kthread_should_stop(),
3947                          thread->timeout);
3948                 try_to_freeze();
3949
3950                 clear_bit(THREAD_WAKEUP, &thread->flags);
3951
3952                 thread->run(thread->mddev);
3953         }
3954
3955         return 0;
3956 }
3957
3958 void md_wakeup_thread(mdk_thread_t *thread)
3959 {
3960         if (thread) {
3961                 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
3962                 set_bit(THREAD_WAKEUP, &thread->flags);
3963                 wake_up(&thread->wqueue);
3964         }
3965 }
3966
3967 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
3968                                  const char *name)
3969 {
3970         mdk_thread_t *thread;
3971
3972         thread = kzalloc(sizeof(mdk_thread_t), GFP_KERNEL);
3973         if (!thread)
3974                 return NULL;
3975
3976         init_waitqueue_head(&thread->wqueue);
3977
3978         thread->run = run;
3979         thread->mddev = mddev;
3980         thread->timeout = MAX_SCHEDULE_TIMEOUT;
3981         thread->tsk = kthread_run(md_thread, thread, name, mdname(thread->mddev));
3982         if (IS_ERR(thread->tsk)) {
3983                 kfree(thread);
3984                 return NULL;
3985         }
3986         return thread;
3987 }
3988
3989 void md_unregister_thread(mdk_thread_t *thread)
3990 {
3991         dprintk("interrupting MD-thread pid %d\n", thread->tsk->pid);
3992
3993         kthread_stop(thread->tsk);
3994         kfree(thread);
3995 }
3996
3997 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
3998 {
3999         if (!mddev) {
4000                 MD_BUG();
4001                 return;
4002         }
4003
4004         if (!rdev || test_bit(Faulty, &rdev->flags))
4005                 return;
4006 /*
4007         dprintk("md_error dev:%s, rdev:(%d:%d), (caller: %p,%p,%p,%p).\n",
4008                 mdname(mddev),
4009                 MAJOR(rdev->bdev->bd_dev), MINOR(rdev->bdev->bd_dev),
4010                 __builtin_return_address(0),__builtin_return_address(1),
4011                 __builtin_return_address(2),__builtin_return_address(3));
4012 */
4013         if (!mddev->pers->error_handler)
4014                 return;
4015         mddev->pers->error_handler(mddev,rdev);
4016         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4017         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4018         md_wakeup_thread(mddev->thread);
4019         md_new_event(mddev);
4020 }
4021
4022 /* seq_file implementation /proc/mdstat */
4023
4024 static void status_unused(struct seq_file *seq)
4025 {
4026         int i = 0;
4027         mdk_rdev_t *rdev;
4028         struct list_head *tmp;
4029
4030         seq_printf(seq, "unused devices: ");
4031
4032         ITERATE_RDEV_PENDING(rdev,tmp) {
4033                 char b[BDEVNAME_SIZE];
4034                 i++;
4035                 seq_printf(seq, "%s ",
4036                               bdevname(rdev->bdev,b));
4037         }
4038         if (!i)
4039                 seq_printf(seq, "<none>");
4040
4041         seq_printf(seq, "\n");
4042 }
4043
4044
4045 static void status_resync(struct seq_file *seq, mddev_t * mddev)
4046 {
4047         sector_t max_blocks, resync, res;
4048         unsigned long dt, db, rt;
4049         int scale;
4050         unsigned int per_milli;
4051
4052         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active))/2;
4053
4054         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
4055                 max_blocks = mddev->resync_max_sectors >> 1;
4056         else
4057                 max_blocks = mddev->size;
4058
4059         /*
4060          * Should not happen.
4061          */
4062         if (!max_blocks) {
4063                 MD_BUG();
4064                 return;
4065         }
4066         /* Pick 'scale' such that (resync>>scale)*1000 will fit
4067          * in a sector_t, and (max_blocks>>scale) will fit in a
4068          * u32, as those are the requirements for sector_div.
4069          * Thus 'scale' must be at least 10
4070          */
4071         scale = 10;
4072         if (sizeof(sector_t) > sizeof(unsigned long)) {
4073                 while ( max_blocks/2 > (1ULL<<(scale+32)))
4074                         scale++;
4075         }
4076         res = (resync>>scale)*1000;
4077         sector_div(res, (u32)((max_blocks>>scale)+1));
4078
4079         per_milli = res;
4080         {
4081                 int i, x = per_milli/50, y = 20-x;
4082                 seq_printf(seq, "[");
4083                 for (i = 0; i < x; i++)
4084                         seq_printf(seq, "=");
4085                 seq_printf(seq, ">");
4086                 for (i = 0; i < y; i++)
4087                         seq_printf(seq, ".");
4088                 seq_printf(seq, "] ");
4089         }
4090         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
4091                       (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
4092                        "resync" : "recovery"),
4093                       per_milli/10, per_milli % 10,
4094                    (unsigned long long) resync,
4095                    (unsigned long long) max_blocks);
4096
4097         /*
4098          * We do not want to overflow, so the order of operands and
4099          * the * 100 / 100 trick are important. We do a +1 to be
4100          * safe against division by zero. We only estimate anyway.
4101          *
4102          * dt: time from mark until now
4103          * db: blocks written from mark until now
4104          * rt: remaining time
4105          */
4106         dt = ((jiffies - mddev->resync_mark) / HZ);
4107         if (!dt) dt++;
4108         db = resync - (mddev->resync_mark_cnt/2);
4109         rt = (dt * ((unsigned long)(max_blocks-resync) / (db/100+1)))/100;
4110
4111         seq_printf(seq, " finish=%lu.%lumin", rt / 60, (rt % 60)/6);
4112
4113         seq_printf(seq, " speed=%ldK/sec", db/dt);
4114 }
4115
4116 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
4117 {
4118         struct list_head *tmp;
4119         loff_t l = *pos;
4120         mddev_t *mddev;
4121
4122         if (l >= 0x10000)
4123                 return NULL;
4124         if (!l--)
4125                 /* header */
4126                 return (void*)1;
4127
4128         spin_lock(&all_mddevs_lock);
4129         list_for_each(tmp,&all_mddevs)
4130                 if (!l--) {
4131                         mddev = list_entry(tmp, mddev_t, all_mddevs);
4132                         mddev_get(mddev);
4133                         spin_unlock(&all_mddevs_lock);
4134                         return mddev;
4135                 }
4136         spin_unlock(&all_mddevs_lock);
4137         if (!l--)
4138                 return (void*)2;/* tail */
4139         return NULL;
4140 }
4141
4142 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4143 {
4144         struct list_head *tmp;
4145         mddev_t *next_mddev, *mddev = v;
4146         
4147         ++*pos;
4148         if (v == (void*)2)
4149                 return NULL;
4150
4151         spin_lock(&all_mddevs_lock);
4152         if (v == (void*)1)
4153                 tmp = all_mddevs.next;
4154         else
4155                 tmp = mddev->all_mddevs.next;
4156         if (tmp != &all_mddevs)
4157                 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
4158         else {
4159                 next_mddev = (void*)2;
4160                 *pos = 0x10000;
4161         }               
4162         spin_unlock(&all_mddevs_lock);
4163
4164         if (v != (void*)1)
4165                 mddev_put(mddev);
4166         return next_mddev;
4167
4168 }
4169
4170 static void md_seq_stop(struct seq_file *seq, void *v)
4171 {
4172         mddev_t *mddev = v;
4173
4174         if (mddev && v != (void*)1 && v != (void*)2)
4175                 mddev_put(mddev);
4176 }
4177
4178 struct mdstat_info {
4179         int event;
4180 };
4181
4182 static int md_seq_show(struct seq_file *seq, void *v)
4183 {
4184         mddev_t *mddev = v;
4185         sector_t size;
4186         struct list_head *tmp2;
4187         mdk_rdev_t *rdev;
4188         struct mdstat_info *mi = seq->private;
4189         struct bitmap *bitmap;
4190
4191         if (v == (void*)1) {
4192                 struct mdk_personality *pers;
4193                 seq_printf(seq, "Personalities : ");
4194                 spin_lock(&pers_lock);
4195                 list_for_each_entry(pers, &pers_list, list)
4196                         seq_printf(seq, "[%s] ", pers->name);
4197
4198                 spin_unlock(&pers_lock);
4199                 seq_printf(seq, "\n");
4200                 mi->event = atomic_read(&md_event_count);
4201                 return 0;
4202         }
4203         if (v == (void*)2) {
4204                 status_unused(seq);
4205                 return 0;
4206         }
4207
4208         if (mddev_lock(mddev)!=0) 
4209                 return -EINTR;
4210         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
4211                 seq_printf(seq, "%s : %sactive", mdname(mddev),
4212                                                 mddev->pers ? "" : "in");
4213                 if (mddev->pers) {
4214                         if (mddev->ro==1)
4215                                 seq_printf(seq, " (read-only)");
4216                         if (mddev->ro==2)
4217                                 seq_printf(seq, "(auto-read-only)");
4218                         seq_printf(seq, " %s", mddev->pers->name);
4219                 }
4220
4221                 size = 0;
4222                 ITERATE_RDEV(mddev,rdev,tmp2) {
4223                         char b[BDEVNAME_SIZE];
4224                         seq_printf(seq, " %s[%d]",
4225                                 bdevname(rdev->bdev,b), rdev->desc_nr);
4226                         if (test_bit(WriteMostly, &rdev->flags))
4227                                 seq_printf(seq, "(W)");
4228                         if (test_bit(Faulty, &rdev->flags)) {
4229                                 seq_printf(seq, "(F)");
4230                                 continue;
4231                         } else if (rdev->raid_disk < 0)
4232                                 seq_printf(seq, "(S)"); /* spare */
4233                         size += rdev->size;
4234                 }
4235
4236                 if (!list_empty(&mddev->disks)) {
4237                         if (mddev->pers)
4238                                 seq_printf(seq, "\n      %llu blocks",
4239                                         (unsigned long long)mddev->array_size);
4240                         else
4241                                 seq_printf(seq, "\n      %llu blocks",
4242                                         (unsigned long long)size);
4243                 }
4244                 if (mddev->persistent) {
4245                         if (mddev->major_version != 0 ||
4246                             mddev->minor_version != 90) {
4247                                 seq_printf(seq," super %d.%d",
4248                                            mddev->major_version,
4249                                            mddev->minor_version);
4250                         }
4251                 } else
4252                         seq_printf(seq, " super non-persistent");
4253
4254                 if (mddev->pers) {
4255                         mddev->pers->status (seq, mddev);
4256                         seq_printf(seq, "\n      ");
4257                         if (mddev->pers->sync_request) {
4258                                 if (mddev->curr_resync > 2) {
4259                                         status_resync (seq, mddev);
4260                                         seq_printf(seq, "\n      ");
4261                                 } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
4262                                         seq_printf(seq, "\tresync=DELAYED\n      ");
4263                                 else if (mddev->recovery_cp < MaxSector)
4264                                         seq_printf(seq, "\tresync=PENDING\n      ");
4265                         }
4266                 } else
4267                         seq_printf(seq, "\n       ");
4268
4269                 if ((bitmap = mddev->bitmap)) {
4270                         unsigned long chunk_kb;
4271                         unsigned long flags;
4272                         spin_lock_irqsave(&bitmap->lock, flags);
4273                         chunk_kb = bitmap->chunksize >> 10;
4274                         seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
4275                                 "%lu%s chunk",
4276                                 bitmap->pages - bitmap->missing_pages,
4277                                 bitmap->pages,
4278                                 (bitmap->pages - bitmap->missing_pages)
4279                                         << (PAGE_SHIFT - 10),
4280                                 chunk_kb ? chunk_kb : bitmap->chunksize,
4281                                 chunk_kb ? "KB" : "B");
4282                         if (bitmap->file) {
4283                                 seq_printf(seq, ", file: ");
4284                                 seq_path(seq, bitmap->file->f_vfsmnt,
4285                                          bitmap->file->f_dentry," \t\n");
4286                         }
4287
4288                         seq_printf(seq, "\n");
4289                         spin_unlock_irqrestore(&bitmap->lock, flags);
4290                 }
4291
4292                 seq_printf(seq, "\n");
4293         }
4294         mddev_unlock(mddev);
4295         
4296         return 0;
4297 }
4298
4299 static struct seq_operations md_seq_ops = {
4300         .start  = md_seq_start,
4301         .next   = md_seq_next,
4302         .stop   = md_seq_stop,
4303         .show   = md_seq_show,
4304 };
4305
4306 static int md_seq_open(struct inode *inode, struct file *file)
4307 {
4308         int error;
4309         struct mdstat_info *mi = kmalloc(sizeof(*mi), GFP_KERNEL);
4310         if (mi == NULL)
4311                 return -ENOMEM;
4312
4313         error = seq_open(file, &md_seq_ops);
4314         if (error)
4315                 kfree(mi);
4316         else {
4317                 struct seq_file *p = file->private_data;
4318                 p->private = mi;
4319                 mi->event = atomic_read(&md_event_count);
4320         }
4321         return error;
4322 }
4323
4324 static int md_seq_release(struct inode *inode, struct file *file)
4325 {
4326         struct seq_file *m = file->private_data;
4327         struct mdstat_info *mi = m->private;
4328         m->private = NULL;
4329         kfree(mi);
4330         return seq_release(inode, file);
4331 }
4332
4333 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
4334 {
4335         struct seq_file *m = filp->private_data;
4336         struct mdstat_info *mi = m->private;
4337         int mask;
4338
4339         poll_wait(filp, &md_event_waiters, wait);
4340
4341         /* always allow read */
4342         mask = POLLIN | POLLRDNORM;
4343
4344         if (mi->event != atomic_read(&md_event_count))
4345                 mask |= POLLERR | POLLPRI;
4346         return mask;
4347 }
4348
4349 static struct file_operations md_seq_fops = {
4350         .open           = md_seq_open,
4351         .read           = seq_read,
4352         .llseek         = seq_lseek,
4353         .release        = md_seq_release,
4354         .poll           = mdstat_poll,
4355 };
4356
4357 int register_md_personality(struct mdk_personality *p)
4358 {
4359         spin_lock(&pers_lock);
4360         list_add_tail(&p->list, &pers_list);
4361         printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
4362         spin_unlock(&pers_lock);
4363         return 0;
4364 }
4365
4366 int unregister_md_personality(struct mdk_personality *p)
4367 {
4368         printk(KERN_INFO "md: %s personality unregistered\n", p->name);
4369         spin_lock(&pers_lock);
4370         list_del_init(&p->list);
4371         spin_unlock(&pers_lock);
4372         return 0;
4373 }
4374
4375 static int is_mddev_idle(mddev_t *mddev)
4376 {
4377         mdk_rdev_t * rdev;
4378         struct list_head *tmp;
4379         int idle;
4380         unsigned long curr_events;
4381
4382         idle = 1;
4383         ITERATE_RDEV(mddev,rdev,tmp) {
4384                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
4385                 curr_events = disk_stat_read(disk, sectors[0]) + 
4386                                 disk_stat_read(disk, sectors[1]) - 
4387                                 atomic_read(&disk->sync_io);
4388                 /* The difference between curr_events and last_events
4389                  * will be affected by any new non-sync IO (making
4390                  * curr_events bigger) and any difference in the amount of
4391                  * in-flight syncio (making current_events bigger or smaller)
4392                  * The amount in-flight is currently limited to
4393                  * 32*64K in raid1/10 and 256*PAGE_SIZE in raid5/6
4394                  * which is at most 4096 sectors.
4395                  * These numbers are fairly fragile and should be made
4396                  * more robust, probably by enforcing the
4397                  * 'window size' that md_do_sync sort-of uses.
4398                  *
4399                  * Note: the following is an unsigned comparison.
4400                  */
4401                 if ((curr_events - rdev->last_events + 4096) > 8192) {
4402                         rdev->last_events = curr_events;
4403                         idle = 0;
4404                 }
4405         }
4406         return idle;
4407 }
4408
4409 void md_done_sync(mddev_t *mddev, int blocks, int ok)
4410 {
4411         /* another "blocks" (512byte) blocks have been synced */
4412         atomic_sub(blocks, &mddev->recovery_active);
4413         wake_up(&mddev->recovery_wait);
4414         if (!ok) {
4415                 set_bit(MD_RECOVERY_ERR, &mddev->recovery);
4416                 md_wakeup_thread(mddev->thread);
4417                 // stop recovery, signal do_sync ....
4418         }
4419 }
4420
4421
4422 /* md_write_start(mddev, bi)
4423  * If we need to update some array metadata (e.g. 'active' flag
4424  * in superblock) before writing, schedule a superblock update
4425  * and wait for it to complete.
4426  */
4427 void md_write_start(mddev_t *mddev, struct bio *bi)
4428 {
4429         if (bio_data_dir(bi) != WRITE)
4430                 return;
4431
4432         BUG_ON(mddev->ro == 1);
4433         if (mddev->ro == 2) {
4434                 /* need to switch to read/write */
4435                 mddev->ro = 0;
4436                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4437                 md_wakeup_thread(mddev->thread);
4438         }
4439         atomic_inc(&mddev->writes_pending);
4440         if (mddev->in_sync) {
4441                 spin_lock_irq(&mddev->write_lock);
4442                 if (mddev->in_sync) {
4443                         mddev->in_sync = 0;
4444                         mddev->sb_dirty = 1;
4445                         md_wakeup_thread(mddev->thread);
4446                 }
4447                 spin_unlock_irq(&mddev->write_lock);
4448         }
4449         wait_event(mddev->sb_wait, mddev->sb_dirty==0);
4450 }
4451
4452 void md_write_end(mddev_t *mddev)
4453 {
4454         if (atomic_dec_and_test(&mddev->writes_pending)) {
4455                 if (mddev->safemode == 2)
4456                         md_wakeup_thread(mddev->thread);
4457                 else
4458                         mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
4459         }
4460 }
4461
4462 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
4463
4464 #define SYNC_MARKS      10
4465 #define SYNC_MARK_STEP  (3*HZ)
4466 static void md_do_sync(mddev_t *mddev)
4467 {
4468         mddev_t *mddev2;
4469         unsigned int currspeed = 0,
4470                  window;
4471         sector_t max_sectors,j, io_sectors;
4472         unsigned long mark[SYNC_MARKS];
4473         sector_t mark_cnt[SYNC_MARKS];
4474         int last_mark,m;
4475         struct list_head *tmp;
4476         sector_t last_check;
4477         int skipped = 0;
4478
4479         /* just incase thread restarts... */
4480         if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
4481                 return;
4482
4483         /* we overload curr_resync somewhat here.
4484          * 0 == not engaged in resync at all
4485          * 2 == checking that there is no conflict with another sync
4486          * 1 == like 2, but have yielded to allow conflicting resync to
4487          *              commense
4488          * other == active in resync - this many blocks
4489          *
4490          * Before starting a resync we must have set curr_resync to
4491          * 2, and then checked that every "conflicting" array has curr_resync
4492          * less than ours.  When we find one that is the same or higher
4493          * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
4494          * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
4495          * This will mean we have to start checking from the beginning again.
4496          *
4497          */
4498
4499         do {
4500                 mddev->curr_resync = 2;
4501
4502         try_again:
4503                 if (kthread_should_stop()) {
4504                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4505                         goto skip;
4506                 }
4507                 ITERATE_MDDEV(mddev2,tmp) {
4508                         if (mddev2 == mddev)
4509                                 continue;
4510                         if (mddev2->curr_resync && 
4511                             match_mddev_units(mddev,mddev2)) {
4512                                 DEFINE_WAIT(wq);
4513                                 if (mddev < mddev2 && mddev->curr_resync == 2) {
4514                                         /* arbitrarily yield */
4515                                         mddev->curr_resync = 1;
4516                                         wake_up(&resync_wait);
4517                                 }
4518                                 if (mddev > mddev2 && mddev->curr_resync == 1)
4519                                         /* no need to wait here, we can wait the next
4520                                          * time 'round when curr_resync == 2
4521                                          */
4522                                         continue;
4523                                 prepare_to_wait(&resync_wait, &wq, TASK_UNINTERRUPTIBLE);
4524                                 if (!kthread_should_stop() &&
4525                                     mddev2->curr_resync >= mddev->curr_resync) {
4526                                         printk(KERN_INFO "md: delaying resync of %s"
4527                                                " until %s has finished resync (they"
4528                                                " share one or more physical units)\n",
4529                                                mdname(mddev), mdname(mddev2));
4530                                         mddev_put(mddev2);
4531                                         schedule();
4532                                         finish_wait(&resync_wait, &wq);
4533                                         goto try_again;
4534                                 }
4535                                 finish_wait(&resync_wait, &wq);
4536                         }
4537                 }
4538         } while (mddev->curr_resync < 2);
4539
4540         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4541                 /* resync follows the size requested by the personality,
4542                  * which defaults to physical size, but can be virtual size
4543                  */
4544                 max_sectors = mddev->resync_max_sectors;
4545                 mddev->resync_mismatches = 0;
4546         } else
4547                 /* recovery follows the physical size of devices */
4548                 max_sectors = mddev->size << 1;
4549
4550         printk(KERN_INFO "md: syncing RAID array %s\n", mdname(mddev));
4551         printk(KERN_INFO "md: minimum _guaranteed_ reconstruction speed:"
4552                 " %d KB/sec/disc.\n", speed_min(mddev));
4553         printk(KERN_INFO "md: using maximum available idle IO bandwidth "
4554                "(but not more than %d KB/sec) for reconstruction.\n",
4555                speed_max(mddev));
4556
4557         is_mddev_idle(mddev); /* this also initializes IO event counters */
4558         /* we don't use the checkpoint if there's a bitmap */
4559         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) && !mddev->bitmap
4560             && ! test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
4561                 j = mddev->recovery_cp;
4562         else
4563                 j = 0;
4564         io_sectors = 0;
4565         for (m = 0; m < SYNC_MARKS; m++) {
4566                 mark[m] = jiffies;
4567                 mark_cnt[m] = io_sectors;
4568         }
4569         last_mark = 0;
4570         mddev->resync_mark = mark[last_mark];
4571         mddev->resync_mark_cnt = mark_cnt[last_mark];
4572
4573         /*
4574          * Tune reconstruction:
4575          */
4576         window = 32*(PAGE_SIZE/512);
4577         printk(KERN_INFO "md: using %dk window, over a total of %llu blocks.\n",
4578                 window/2,(unsigned long long) max_sectors/2);
4579
4580         atomic_set(&mddev->recovery_active, 0);
4581         init_waitqueue_head(&mddev->recovery_wait);
4582         last_check = 0;
4583
4584         if (j>2) {
4585                 printk(KERN_INFO 
4586                         "md: resuming recovery of %s from checkpoint.\n",
4587                         mdname(mddev));
4588                 mddev->curr_resync = j;
4589         }
4590
4591         while (j < max_sectors) {
4592                 sector_t sectors;
4593
4594                 skipped = 0;
4595                 sectors = mddev->pers->sync_request(mddev, j, &skipped,
4596                                             currspeed < speed_min(mddev));
4597                 if (sectors == 0) {
4598                         set_bit(MD_RECOVERY_ERR, &mddev->recovery);
4599                         goto out;
4600                 }
4601
4602                 if (!skipped) { /* actual IO requested */
4603                         io_sectors += sectors;
4604                         atomic_add(sectors, &mddev->recovery_active);
4605                 }
4606
4607                 j += sectors;
4608                 if (j>1) mddev->curr_resync = j;
4609                 if (last_check == 0)
4610                         /* this is the earliers that rebuilt will be
4611                          * visible in /proc/mdstat
4612                          */
4613                         md_new_event(mddev);
4614
4615                 if (last_check + window > io_sectors || j == max_sectors)
4616                         continue;
4617
4618                 last_check = io_sectors;
4619
4620                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery) ||
4621                     test_bit(MD_RECOVERY_ERR, &mddev->recovery))
4622                         break;
4623
4624         repeat:
4625                 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
4626                         /* step marks */
4627                         int next = (last_mark+1) % SYNC_MARKS;
4628
4629                         mddev->resync_mark = mark[next];
4630                         mddev->resync_mark_cnt = mark_cnt[next];
4631                         mark[next] = jiffies;
4632                         mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
4633                         last_mark = next;
4634                 }
4635
4636
4637                 if (kthread_should_stop()) {
4638                         /*
4639                          * got a signal, exit.
4640                          */
4641                         printk(KERN_INFO 
4642                                 "md: md_do_sync() got signal ... exiting\n");
4643                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4644                         goto out;
4645                 }
4646
4647                 /*
4648                  * this loop exits only if either when we are slower than
4649                  * the 'hard' speed limit, or the system was IO-idle for
4650                  * a jiffy.
4651                  * the system might be non-idle CPU-wise, but we only care
4652                  * about not overloading the IO subsystem. (things like an
4653                  * e2fsck being done on the RAID array should execute fast)
4654                  */
4655                 mddev->queue->unplug_fn(mddev->queue);
4656                 cond_resched();
4657
4658                 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
4659                         /((jiffies-mddev->resync_mark)/HZ +1) +1;
4660
4661                 if (currspeed > speed_min(mddev)) {
4662                         if ((currspeed > speed_max(mddev)) ||
4663                                         !is_mddev_idle(mddev)) {
4664                                 msleep(500);
4665                                 goto repeat;
4666                         }
4667                 }
4668         }
4669         printk(KERN_INFO "md: %s: sync done.\n",mdname(mddev));
4670         /*
4671          * this also signals 'finished resyncing' to md_stop
4672          */
4673  out:
4674         mddev->queue->unplug_fn(mddev->queue);
4675
4676         wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
4677
4678         /* tell personality that we are finished */
4679         mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
4680
4681         if (!test_bit(MD_RECOVERY_ERR, &mddev->recovery) &&
4682             mddev->curr_resync > 2 &&
4683             mddev->curr_resync >= mddev->recovery_cp) {
4684                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
4685                         printk(KERN_INFO 
4686                                 "md: checkpointing recovery of %s.\n",
4687                                 mdname(mddev));
4688                         mddev->recovery_cp = mddev->curr_resync;
4689                 } else
4690                         mddev->recovery_cp = MaxSector;
4691         }
4692
4693  skip:
4694         mddev->curr_resync = 0;
4695         wake_up(&resync_wait);
4696         set_bit(MD_RECOVERY_DONE, &mddev->recovery);
4697         md_wakeup_thread(mddev->thread);
4698 }
4699
4700
4701 /*
4702  * This routine is regularly called by all per-raid-array threads to
4703  * deal with generic issues like resync and super-block update.
4704  * Raid personalities that don't have a thread (linear/raid0) do not
4705  * need this as they never do any recovery or update the superblock.
4706  *
4707  * It does not do any resync itself, but rather "forks" off other threads
4708  * to do that as needed.
4709  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
4710  * "->recovery" and create a thread at ->sync_thread.
4711  * When the thread finishes it sets MD_RECOVERY_DONE (and might set MD_RECOVERY_ERR)
4712  * and wakeups up this thread which will reap the thread and finish up.
4713  * This thread also removes any faulty devices (with nr_pending == 0).
4714  *
4715  * The overall approach is:
4716  *  1/ if the superblock needs updating, update it.
4717  *  2/ If a recovery thread is running, don't do anything else.
4718  *  3/ If recovery has finished, clean up, possibly marking spares active.
4719  *  4/ If there are any faulty devices, remove them.
4720  *  5/ If array is degraded, try to add spares devices
4721  *  6/ If array has spares or is not in-sync, start a resync thread.
4722  */
4723 void md_check_recovery(mddev_t *mddev)
4724 {
4725         mdk_rdev_t *rdev;
4726         struct list_head *rtmp;
4727
4728
4729         if (mddev->bitmap)
4730                 bitmap_daemon_work(mddev->bitmap);
4731
4732         if (mddev->ro)
4733                 return;
4734
4735         if (signal_pending(current)) {
4736                 if (mddev->pers->sync_request) {
4737                         printk(KERN_INFO "md: %s in immediate safe mode\n",
4738                                mdname(mddev));
4739                         mddev->safemode = 2;
4740                 }
4741                 flush_signals(current);
4742         }
4743
4744         if ( ! (
4745                 mddev->sb_dirty ||
4746                 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
4747                 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
4748                 (mddev->safemode == 1) ||
4749                 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
4750                  && !mddev->in_sync && mddev->recovery_cp == MaxSector)
4751                 ))
4752                 return;
4753
4754         if (mddev_trylock(mddev)==0) {
4755                 int spares =0;
4756
4757                 spin_lock_irq(&mddev->write_lock);
4758                 if (mddev->safemode && !atomic_read(&mddev->writes_pending) &&
4759                     !mddev->in_sync && mddev->recovery_cp == MaxSector) {
4760                         mddev->in_sync = 1;
4761                         mddev->sb_dirty = 1;
4762                 }
4763                 if (mddev->safemode == 1)
4764                         mddev->safemode = 0;
4765                 spin_unlock_irq(&mddev->write_lock);
4766
4767                 if (mddev->sb_dirty)
4768                         md_update_sb(mddev);
4769
4770
4771                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
4772                     !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
4773                         /* resync/recovery still happening */
4774                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4775                         goto unlock;
4776                 }
4777                 if (mddev->sync_thread) {
4778                         /* resync has finished, collect result */
4779                         md_unregister_thread(mddev->sync_thread);
4780                         mddev->sync_thread = NULL;
4781                         if (!test_bit(MD_RECOVERY_ERR, &mddev->recovery) &&
4782                             !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
4783                                 /* success...*/
4784                                 /* activate any spares */
4785                                 mddev->pers->spare_active(mddev);
4786                         }
4787                         md_update_sb(mddev);
4788
4789                         /* if array is no-longer degraded, then any saved_raid_disk
4790                          * information must be scrapped
4791                          */
4792                         if (!mddev->degraded)
4793                                 ITERATE_RDEV(mddev,rdev,rtmp)
4794                                         rdev->saved_raid_disk = -1;
4795
4796                         mddev->recovery = 0;
4797                         /* flag recovery needed just to double check */
4798                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4799                         md_new_event(mddev);
4800                         goto unlock;
4801                 }
4802                 /* Clear some bits that don't mean anything, but
4803                  * might be left set
4804                  */
4805                 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4806                 clear_bit(MD_RECOVERY_ERR, &mddev->recovery);
4807                 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
4808                 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
4809
4810                 /* no recovery is running.
4811                  * remove any failed drives, then
4812                  * add spares if possible.
4813                  * Spare are also removed and re-added, to allow
4814                  * the personality to fail the re-add.
4815                  */
4816                 ITERATE_RDEV(mddev,rdev,rtmp)
4817                         if (rdev->raid_disk >= 0 &&
4818                             (test_bit(Faulty, &rdev->flags) || ! test_bit(In_sync, &rdev->flags)) &&
4819                             atomic_read(&rdev->nr_pending)==0) {
4820                                 if (mddev->pers->hot_remove_disk(mddev, rdev->raid_disk)==0) {
4821                                         char nm[20];
4822                                         sprintf(nm,"rd%d", rdev->raid_disk);
4823                                         sysfs_remove_link(&mddev->kobj, nm);
4824                                         rdev->raid_disk = -1;
4825                                 }
4826                         }
4827
4828                 if (mddev->degraded) {
4829                         ITERATE_RDEV(mddev,rdev,rtmp)
4830                                 if (rdev->raid_disk < 0
4831                                     && !test_bit(Faulty, &rdev->flags)) {
4832                                         if (mddev->pers->hot_add_disk(mddev,rdev)) {
4833                                                 char nm[20];
4834                                                 sprintf(nm, "rd%d", rdev->raid_disk);
4835                                                 sysfs_create_link(&mddev->kobj, &rdev->kobj, nm);
4836                                                 spares++;
4837                                                 md_new_event(mddev);
4838                                         } else
4839                                                 break;
4840                                 }
4841                 }
4842
4843                 if (spares) {
4844                         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4845                         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4846                 } else if (mddev->recovery_cp < MaxSector) {
4847                         set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4848                 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
4849                         /* nothing to be done ... */
4850                         goto unlock;
4851
4852                 if (mddev->pers->sync_request) {
4853                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4854                         if (spares && mddev->bitmap && ! mddev->bitmap->file) {
4855                                 /* We are adding a device or devices to an array
4856                                  * which has the bitmap stored on all devices.
4857                                  * So make sure all bitmap pages get written
4858                                  */
4859                                 bitmap_write_all(mddev->bitmap);
4860                         }
4861                         mddev->sync_thread = md_register_thread(md_do_sync,
4862                                                                 mddev,
4863                                                                 "%s_resync");
4864                         if (!mddev->sync_thread) {
4865                                 printk(KERN_ERR "%s: could not start resync"
4866                                         " thread...\n", 
4867                                         mdname(mddev));
4868                                 /* leave the spares where they are, it shouldn't hurt */
4869                                 mddev->recovery = 0;
4870                         } else
4871                                 md_wakeup_thread(mddev->sync_thread);
4872                         md_new_event(mddev);
4873                 }
4874         unlock:
4875                 mddev_unlock(mddev);
4876         }
4877 }
4878
4879 static int md_notify_reboot(struct notifier_block *this,
4880                             unsigned long code, void *x)
4881 {
4882         struct list_head *tmp;
4883         mddev_t *mddev;
4884
4885         if ((code == SYS_DOWN) || (code == SYS_HALT) || (code == SYS_POWER_OFF)) {
4886
4887                 printk(KERN_INFO "md: stopping all md devices.\n");
4888
4889                 ITERATE_MDDEV(mddev,tmp)
4890                         if (mddev_trylock(mddev)==0)
4891                                 do_md_stop (mddev, 1);
4892                 /*
4893                  * certain more exotic SCSI devices are known to be
4894                  * volatile wrt too early system reboots. While the
4895                  * right place to handle this issue is the given
4896                  * driver, we do want to have a safe RAID driver ...
4897                  */
4898                 mdelay(1000*1);
4899         }
4900         return NOTIFY_DONE;
4901 }
4902
4903 static struct notifier_block md_notifier = {
4904         .notifier_call  = md_notify_reboot,
4905         .next           = NULL,
4906         .priority       = INT_MAX, /* before any real devices */
4907 };
4908
4909 static void md_geninit(void)
4910 {
4911         struct proc_dir_entry *p;
4912
4913         dprintk("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
4914
4915         p = create_proc_entry("mdstat", S_IRUGO, NULL);
4916         if (p)
4917                 p->proc_fops = &md_seq_fops;
4918 }
4919
4920 static int __init md_init(void)
4921 {
4922         int minor;
4923
4924         printk(KERN_INFO "md: md driver %d.%d.%d MAX_MD_DEVS=%d,"
4925                         " MD_SB_DISKS=%d\n",
4926                         MD_MAJOR_VERSION, MD_MINOR_VERSION,
4927                         MD_PATCHLEVEL_VERSION, MAX_MD_DEVS, MD_SB_DISKS);
4928         printk(KERN_INFO "md: bitmap version %d.%d\n", BITMAP_MAJOR_HI,
4929                         BITMAP_MINOR);
4930
4931         if (register_blkdev(MAJOR_NR, "md"))
4932                 return -1;
4933         if ((mdp_major=register_blkdev(0, "mdp"))<=0) {
4934                 unregister_blkdev(MAJOR_NR, "md");
4935                 return -1;
4936         }
4937         devfs_mk_dir("md");
4938         blk_register_region(MKDEV(MAJOR_NR, 0), MAX_MD_DEVS, THIS_MODULE,
4939                                 md_probe, NULL, NULL);
4940         blk_register_region(MKDEV(mdp_major, 0), MAX_MD_DEVS<<MdpMinorShift, THIS_MODULE,
4941                             md_probe, NULL, NULL);
4942
4943         for (minor=0; minor < MAX_MD_DEVS; ++minor)
4944                 devfs_mk_bdev(MKDEV(MAJOR_NR, minor),
4945                                 S_IFBLK|S_IRUSR|S_IWUSR,
4946                                 "md/%d", minor);
4947
4948         for (minor=0; minor < MAX_MD_DEVS; ++minor)
4949                 devfs_mk_bdev(MKDEV(mdp_major, minor<<MdpMinorShift),
4950                               S_IFBLK|S_IRUSR|S_IWUSR,
4951                               "md/mdp%d", minor);
4952
4953
4954         register_reboot_notifier(&md_notifier);
4955         raid_table_header = register_sysctl_table(raid_root_table, 1);
4956
4957         md_geninit();
4958         return (0);
4959 }
4960
4961
4962 #ifndef MODULE
4963
4964 /*
4965  * Searches all registered partitions for autorun RAID arrays
4966  * at boot time.
4967  */
4968 static dev_t detected_devices[128];
4969 static int dev_cnt;
4970
4971 void md_autodetect_dev(dev_t dev)
4972 {
4973         if (dev_cnt >= 0 && dev_cnt < 127)
4974                 detected_devices[dev_cnt++] = dev;
4975 }
4976
4977
4978 static void autostart_arrays(int part)
4979 {
4980         mdk_rdev_t *rdev;
4981         int i;
4982
4983         printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
4984
4985         for (i = 0; i < dev_cnt; i++) {
4986                 dev_t dev = detected_devices[i];
4987
4988                 rdev = md_import_device(dev,0, 0);
4989                 if (IS_ERR(rdev))
4990                         continue;
4991
4992                 if (test_bit(Faulty, &rdev->flags)) {
4993                         MD_BUG();
4994                         continue;
4995                 }
4996                 list_add(&rdev->same_set, &pending_raid_disks);
4997         }
4998         dev_cnt = 0;
4999
5000         autorun_devices(part);
5001 }
5002
5003 #endif
5004
5005 static __exit void md_exit(void)
5006 {
5007         mddev_t *mddev;
5008         struct list_head *tmp;
5009         int i;
5010         blk_unregister_region(MKDEV(MAJOR_NR,0), MAX_MD_DEVS);
5011         blk_unregister_region(MKDEV(mdp_major,0), MAX_MD_DEVS << MdpMinorShift);
5012         for (i=0; i < MAX_MD_DEVS; i++)
5013                 devfs_remove("md/%d", i);
5014         for (i=0; i < MAX_MD_DEVS; i++)
5015                 devfs_remove("md/d%d", i);
5016
5017         devfs_remove("md");
5018
5019         unregister_blkdev(MAJOR_NR,"md");
5020         unregister_blkdev(mdp_major, "mdp");
5021         unregister_reboot_notifier(&md_notifier);
5022         unregister_sysctl_table(raid_table_header);
5023         remove_proc_entry("mdstat", NULL);
5024         ITERATE_MDDEV(mddev,tmp) {
5025                 struct gendisk *disk = mddev->gendisk;
5026                 if (!disk)
5027                         continue;
5028                 export_array(mddev);
5029                 del_gendisk(disk);
5030                 put_disk(disk);
5031                 mddev->gendisk = NULL;
5032                 mddev_put(mddev);
5033         }
5034 }
5035
5036 module_init(md_init)
5037 module_exit(md_exit)
5038
5039 static int get_ro(char *buffer, struct kernel_param *kp)
5040 {
5041         return sprintf(buffer, "%d", start_readonly);
5042 }
5043 static int set_ro(const char *val, struct kernel_param *kp)
5044 {
5045         char *e;
5046         int num = simple_strtoul(val, &e, 10);
5047         if (*val && (*e == '\0' || *e == '\n')) {
5048                 start_readonly = num;
5049                 return 0;
5050         }
5051         return -EINVAL;
5052 }
5053
5054 module_param_call(start_ro, set_ro, get_ro, NULL, 0600);
5055 module_param(start_dirty_degraded, int, 0644);
5056
5057
5058 EXPORT_SYMBOL(register_md_personality);
5059 EXPORT_SYMBOL(unregister_md_personality);
5060 EXPORT_SYMBOL(md_error);
5061 EXPORT_SYMBOL(md_done_sync);
5062 EXPORT_SYMBOL(md_write_start);
5063 EXPORT_SYMBOL(md_write_end);
5064 EXPORT_SYMBOL(md_register_thread);
5065 EXPORT_SYMBOL(md_unregister_thread);
5066 EXPORT_SYMBOL(md_wakeup_thread);
5067 EXPORT_SYMBOL(md_print_devices);
5068 EXPORT_SYMBOL(md_check_recovery);
5069 MODULE_LICENSE("GPL");
5070 MODULE_ALIAS("md");
5071 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);