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