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