[PATCH] md: new sysfs interface for setting bits in the write-intent-bitmap
[sfrench/cifs-2.6.git] / drivers / md / md.c
1 /*
2    md.c : Multiple Devices driver for Linux
3           Copyright (C) 1998, 1999, 2000 Ingo Molnar
4
5      completely rewritten, based on the MD driver code from Marc Zyngier
6
7    Changes:
8
9    - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
10    - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
11    - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
12    - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
13    - kmod support by: Cyrus Durgin
14    - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
15    - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
16
17    - lots of fixes and improvements to the RAID1/RAID5 and generic
18      RAID code (such as request based resynchronization):
19
20      Neil Brown <neilb@cse.unsw.edu.au>.
21
22    - persistent bitmap code
23      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
24
25    This program is free software; you can redistribute it and/or modify
26    it under the terms of the GNU General Public License as published by
27    the Free Software Foundation; either version 2, or (at your option)
28    any later version.
29
30    You should have received a copy of the GNU General Public License
31    (for example /usr/src/linux/COPYING); if not, write to the Free
32    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 */
34
35 #include <linux/module.h>
36 #include <linux/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/suspend.h>
43 #include <linux/poll.h>
44 #include <linux/mutex.h>
45 #include <linux/ctype.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                 md_error(mddev, rdev);
394
395         if (atomic_dec_and_test(&mddev->pending_writes))
396                 wake_up(&mddev->sb_wait);
397         bio_put(bio);
398         return 0;
399 }
400
401 static int super_written_barrier(struct bio *bio, unsigned int bytes_done, int error)
402 {
403         struct bio *bio2 = bio->bi_private;
404         mdk_rdev_t *rdev = bio2->bi_private;
405         mddev_t *mddev = rdev->mddev;
406         if (bio->bi_size)
407                 return 1;
408
409         if (!test_bit(BIO_UPTODATE, &bio->bi_flags) &&
410             error == -EOPNOTSUPP) {
411                 unsigned long flags;
412                 /* barriers don't appear to be supported :-( */
413                 set_bit(BarriersNotsupp, &rdev->flags);
414                 mddev->barriers_work = 0;
415                 spin_lock_irqsave(&mddev->write_lock, flags);
416                 bio2->bi_next = mddev->biolist;
417                 mddev->biolist = bio2;
418                 spin_unlock_irqrestore(&mddev->write_lock, flags);
419                 wake_up(&mddev->sb_wait);
420                 bio_put(bio);
421                 return 0;
422         }
423         bio_put(bio2);
424         bio->bi_private = rdev;
425         return super_written(bio, bytes_done, error);
426 }
427
428 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
429                    sector_t sector, int size, struct page *page)
430 {
431         /* write first size bytes of page to sector of rdev
432          * Increment mddev->pending_writes before returning
433          * and decrement it on completion, waking up sb_wait
434          * if zero is reached.
435          * If an error occurred, call md_error
436          *
437          * As we might need to resubmit the request if BIO_RW_BARRIER
438          * causes ENOTSUPP, we allocate a spare bio...
439          */
440         struct bio *bio = bio_alloc(GFP_NOIO, 1);
441         int rw = (1<<BIO_RW) | (1<<BIO_RW_SYNC);
442
443         bio->bi_bdev = rdev->bdev;
444         bio->bi_sector = sector;
445         bio_add_page(bio, page, size, 0);
446         bio->bi_private = rdev;
447         bio->bi_end_io = super_written;
448         bio->bi_rw = rw;
449
450         atomic_inc(&mddev->pending_writes);
451         if (!test_bit(BarriersNotsupp, &rdev->flags)) {
452                 struct bio *rbio;
453                 rw |= (1<<BIO_RW_BARRIER);
454                 rbio = bio_clone(bio, GFP_NOIO);
455                 rbio->bi_private = bio;
456                 rbio->bi_end_io = super_written_barrier;
457                 submit_bio(rw, rbio);
458         } else
459                 submit_bio(rw, bio);
460 }
461
462 void md_super_wait(mddev_t *mddev)
463 {
464         /* wait for all superblock writes that were scheduled to complete.
465          * if any had to be retried (due to BARRIER problems), retry them
466          */
467         DEFINE_WAIT(wq);
468         for(;;) {
469                 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
470                 if (atomic_read(&mddev->pending_writes)==0)
471                         break;
472                 while (mddev->biolist) {
473                         struct bio *bio;
474                         spin_lock_irq(&mddev->write_lock);
475                         bio = mddev->biolist;
476                         mddev->biolist = bio->bi_next ;
477                         bio->bi_next = NULL;
478                         spin_unlock_irq(&mddev->write_lock);
479                         submit_bio(bio->bi_rw, bio);
480                 }
481                 schedule();
482         }
483         finish_wait(&mddev->sb_wait, &wq);
484 }
485
486 static int bi_complete(struct bio *bio, unsigned int bytes_done, int error)
487 {
488         if (bio->bi_size)
489                 return 1;
490
491         complete((struct completion*)bio->bi_private);
492         return 0;
493 }
494
495 int sync_page_io(struct block_device *bdev, sector_t sector, int size,
496                    struct page *page, int rw)
497 {
498         struct bio *bio = bio_alloc(GFP_NOIO, 1);
499         struct completion event;
500         int ret;
501
502         rw |= (1 << BIO_RW_SYNC);
503
504         bio->bi_bdev = bdev;
505         bio->bi_sector = sector;
506         bio_add_page(bio, page, size, 0);
507         init_completion(&event);
508         bio->bi_private = &event;
509         bio->bi_end_io = bi_complete;
510         submit_bio(rw, bio);
511         wait_for_completion(&event);
512
513         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
514         bio_put(bio);
515         return ret;
516 }
517 EXPORT_SYMBOL_GPL(sync_page_io);
518
519 static int read_disk_sb(mdk_rdev_t * rdev, int size)
520 {
521         char b[BDEVNAME_SIZE];
522         if (!rdev->sb_page) {
523                 MD_BUG();
524                 return -EINVAL;
525         }
526         if (rdev->sb_loaded)
527                 return 0;
528
529
530         if (!sync_page_io(rdev->bdev, rdev->sb_offset<<1, size, rdev->sb_page, READ))
531                 goto fail;
532         rdev->sb_loaded = 1;
533         return 0;
534
535 fail:
536         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
537                 bdevname(rdev->bdev,b));
538         return -EINVAL;
539 }
540
541 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
542 {
543         if (    (sb1->set_uuid0 == sb2->set_uuid0) &&
544                 (sb1->set_uuid1 == sb2->set_uuid1) &&
545                 (sb1->set_uuid2 == sb2->set_uuid2) &&
546                 (sb1->set_uuid3 == sb2->set_uuid3))
547
548                 return 1;
549
550         return 0;
551 }
552
553
554 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
555 {
556         int ret;
557         mdp_super_t *tmp1, *tmp2;
558
559         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
560         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
561
562         if (!tmp1 || !tmp2) {
563                 ret = 0;
564                 printk(KERN_INFO "md.c: sb1 is not equal to sb2!\n");
565                 goto abort;
566         }
567
568         *tmp1 = *sb1;
569         *tmp2 = *sb2;
570
571         /*
572          * nr_disks is not constant
573          */
574         tmp1->nr_disks = 0;
575         tmp2->nr_disks = 0;
576
577         if (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4))
578                 ret = 0;
579         else
580                 ret = 1;
581
582 abort:
583         kfree(tmp1);
584         kfree(tmp2);
585         return ret;
586 }
587
588 static unsigned int calc_sb_csum(mdp_super_t * sb)
589 {
590         unsigned int disk_csum, csum;
591
592         disk_csum = sb->sb_csum;
593         sb->sb_csum = 0;
594         csum = csum_partial((void *)sb, MD_SB_BYTES, 0);
595         sb->sb_csum = disk_csum;
596         return csum;
597 }
598
599
600 /*
601  * Handle superblock details.
602  * We want to be able to handle multiple superblock formats
603  * so we have a common interface to them all, and an array of
604  * different handlers.
605  * We rely on user-space to write the initial superblock, and support
606  * reading and updating of superblocks.
607  * Interface methods are:
608  *   int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
609  *      loads and validates a superblock on dev.
610  *      if refdev != NULL, compare superblocks on both devices
611  *    Return:
612  *      0 - dev has a superblock that is compatible with refdev
613  *      1 - dev has a superblock that is compatible and newer than refdev
614  *          so dev should be used as the refdev in future
615  *     -EINVAL superblock incompatible or invalid
616  *     -othererror e.g. -EIO
617  *
618  *   int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
619  *      Verify that dev is acceptable into mddev.
620  *       The first time, mddev->raid_disks will be 0, and data from
621  *       dev should be merged in.  Subsequent calls check that dev
622  *       is new enough.  Return 0 or -EINVAL
623  *
624  *   void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
625  *     Update the superblock for rdev with data in mddev
626  *     This does not write to disc.
627  *
628  */
629
630 struct super_type  {
631         char            *name;
632         struct module   *owner;
633         int             (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version);
634         int             (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
635         void            (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
636 };
637
638 /*
639  * load_super for 0.90.0 
640  */
641 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
642 {
643         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
644         mdp_super_t *sb;
645         int ret;
646         sector_t sb_offset;
647
648         /*
649          * Calculate the position of the superblock,
650          * it's at the end of the disk.
651          *
652          * It also happens to be a multiple of 4Kb.
653          */
654         sb_offset = calc_dev_sboffset(rdev->bdev);
655         rdev->sb_offset = sb_offset;
656
657         ret = read_disk_sb(rdev, MD_SB_BYTES);
658         if (ret) return ret;
659
660         ret = -EINVAL;
661
662         bdevname(rdev->bdev, b);
663         sb = (mdp_super_t*)page_address(rdev->sb_page);
664
665         if (sb->md_magic != MD_SB_MAGIC) {
666                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
667                        b);
668                 goto abort;
669         }
670
671         if (sb->major_version != 0 ||
672             sb->minor_version < 90 ||
673             sb->minor_version > 91) {
674                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
675                         sb->major_version, sb->minor_version,
676                         b);
677                 goto abort;
678         }
679
680         if (sb->raid_disks <= 0)
681                 goto abort;
682
683         if (csum_fold(calc_sb_csum(sb)) != csum_fold(sb->sb_csum)) {
684                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
685                         b);
686                 goto abort;
687         }
688
689         rdev->preferred_minor = sb->md_minor;
690         rdev->data_offset = 0;
691         rdev->sb_size = MD_SB_BYTES;
692
693         if (sb->level == LEVEL_MULTIPATH)
694                 rdev->desc_nr = -1;
695         else
696                 rdev->desc_nr = sb->this_disk.number;
697
698         if (refdev == 0)
699                 ret = 1;
700         else {
701                 __u64 ev1, ev2;
702                 mdp_super_t *refsb = (mdp_super_t*)page_address(refdev->sb_page);
703                 if (!uuid_equal(refsb, sb)) {
704                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
705                                 b, bdevname(refdev->bdev,b2));
706                         goto abort;
707                 }
708                 if (!sb_equal(refsb, sb)) {
709                         printk(KERN_WARNING "md: %s has same UUID"
710                                " but different superblock to %s\n",
711                                b, bdevname(refdev->bdev, b2));
712                         goto abort;
713                 }
714                 ev1 = md_event(sb);
715                 ev2 = md_event(refsb);
716                 if (ev1 > ev2)
717                         ret = 1;
718                 else 
719                         ret = 0;
720         }
721         rdev->size = calc_dev_size(rdev, sb->chunk_size);
722
723         if (rdev->size < sb->size && sb->level > 1)
724                 /* "this cannot possibly happen" ... */
725                 ret = -EINVAL;
726
727  abort:
728         return ret;
729 }
730
731 /*
732  * validate_super for 0.90.0
733  */
734 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
735 {
736         mdp_disk_t *desc;
737         mdp_super_t *sb = (mdp_super_t *)page_address(rdev->sb_page);
738         __u64 ev1 = md_event(sb);
739
740         rdev->raid_disk = -1;
741         rdev->flags = 0;
742         if (mddev->raid_disks == 0) {
743                 mddev->major_version = 0;
744                 mddev->minor_version = sb->minor_version;
745                 mddev->patch_version = sb->patch_version;
746                 mddev->persistent = ! sb->not_persistent;
747                 mddev->chunk_size = sb->chunk_size;
748                 mddev->ctime = sb->ctime;
749                 mddev->utime = sb->utime;
750                 mddev->level = sb->level;
751                 mddev->clevel[0] = 0;
752                 mddev->layout = sb->layout;
753                 mddev->raid_disks = sb->raid_disks;
754                 mddev->size = sb->size;
755                 mddev->events = ev1;
756                 mddev->bitmap_offset = 0;
757                 mddev->default_bitmap_offset = MD_SB_BYTES >> 9;
758
759                 if (mddev->minor_version >= 91) {
760                         mddev->reshape_position = sb->reshape_position;
761                         mddev->delta_disks = sb->delta_disks;
762                         mddev->new_level = sb->new_level;
763                         mddev->new_layout = sb->new_layout;
764                         mddev->new_chunk = sb->new_chunk;
765                 } else {
766                         mddev->reshape_position = MaxSector;
767                         mddev->delta_disks = 0;
768                         mddev->new_level = mddev->level;
769                         mddev->new_layout = mddev->layout;
770                         mddev->new_chunk = mddev->chunk_size;
771                 }
772
773                 if (sb->state & (1<<MD_SB_CLEAN))
774                         mddev->recovery_cp = MaxSector;
775                 else {
776                         if (sb->events_hi == sb->cp_events_hi && 
777                                 sb->events_lo == sb->cp_events_lo) {
778                                 mddev->recovery_cp = sb->recovery_cp;
779                         } else
780                                 mddev->recovery_cp = 0;
781                 }
782
783                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
784                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
785                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
786                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
787
788                 mddev->max_disks = MD_SB_DISKS;
789
790                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
791                     mddev->bitmap_file == NULL) {
792                         if (mddev->level != 1 && mddev->level != 4
793                             && mddev->level != 5 && mddev->level != 6
794                             && mddev->level != 10) {
795                                 /* FIXME use a better test */
796                                 printk(KERN_WARNING "md: bitmaps not supported for this level.\n");
797                                 return -EINVAL;
798                         }
799                         mddev->bitmap_offset = mddev->default_bitmap_offset;
800                 }
801
802         } else if (mddev->pers == NULL) {
803                 /* Insist on good event counter while assembling */
804                 ++ev1;
805                 if (ev1 < mddev->events) 
806                         return -EINVAL;
807         } else if (mddev->bitmap) {
808                 /* if adding to array with a bitmap, then we can accept an
809                  * older device ... but not too old.
810                  */
811                 if (ev1 < mddev->bitmap->events_cleared)
812                         return 0;
813         } else {
814                 if (ev1 < mddev->events)
815                         /* just a hot-add of a new device, leave raid_disk at -1 */
816                         return 0;
817         }
818
819         if (mddev->level != LEVEL_MULTIPATH) {
820                 desc = sb->disks + rdev->desc_nr;
821
822                 if (desc->state & (1<<MD_DISK_FAULTY))
823                         set_bit(Faulty, &rdev->flags);
824                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
825                             desc->raid_disk < mddev->raid_disks */) {
826                         set_bit(In_sync, &rdev->flags);
827                         rdev->raid_disk = desc->raid_disk;
828                 }
829                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
830                         set_bit(WriteMostly, &rdev->flags);
831         } else /* MULTIPATH are always insync */
832                 set_bit(In_sync, &rdev->flags);
833         return 0;
834 }
835
836 /*
837  * sync_super for 0.90.0
838  */
839 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
840 {
841         mdp_super_t *sb;
842         struct list_head *tmp;
843         mdk_rdev_t *rdev2;
844         int next_spare = mddev->raid_disks;
845
846
847         /* make rdev->sb match mddev data..
848          *
849          * 1/ zero out disks
850          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
851          * 3/ any empty disks < next_spare become removed
852          *
853          * disks[0] gets initialised to REMOVED because
854          * we cannot be sure from other fields if it has
855          * been initialised or not.
856          */
857         int i;
858         int active=0, working=0,failed=0,spare=0,nr_disks=0;
859
860         rdev->sb_size = MD_SB_BYTES;
861
862         sb = (mdp_super_t*)page_address(rdev->sb_page);
863
864         memset(sb, 0, sizeof(*sb));
865
866         sb->md_magic = MD_SB_MAGIC;
867         sb->major_version = mddev->major_version;
868         sb->patch_version = mddev->patch_version;
869         sb->gvalid_words  = 0; /* ignored */
870         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
871         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
872         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
873         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
874
875         sb->ctime = mddev->ctime;
876         sb->level = mddev->level;
877         sb->size  = mddev->size;
878         sb->raid_disks = mddev->raid_disks;
879         sb->md_minor = mddev->md_minor;
880         sb->not_persistent = !mddev->persistent;
881         sb->utime = mddev->utime;
882         sb->state = 0;
883         sb->events_hi = (mddev->events>>32);
884         sb->events_lo = (u32)mddev->events;
885
886         if (mddev->reshape_position == MaxSector)
887                 sb->minor_version = 90;
888         else {
889                 sb->minor_version = 91;
890                 sb->reshape_position = mddev->reshape_position;
891                 sb->new_level = mddev->new_level;
892                 sb->delta_disks = mddev->delta_disks;
893                 sb->new_layout = mddev->new_layout;
894                 sb->new_chunk = mddev->new_chunk;
895         }
896         mddev->minor_version = sb->minor_version;
897         if (mddev->in_sync)
898         {
899                 sb->recovery_cp = mddev->recovery_cp;
900                 sb->cp_events_hi = (mddev->events>>32);
901                 sb->cp_events_lo = (u32)mddev->events;
902                 if (mddev->recovery_cp == MaxSector)
903                         sb->state = (1<< MD_SB_CLEAN);
904         } else
905                 sb->recovery_cp = 0;
906
907         sb->layout = mddev->layout;
908         sb->chunk_size = mddev->chunk_size;
909
910         if (mddev->bitmap && mddev->bitmap_file == NULL)
911                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
912
913         sb->disks[0].state = (1<<MD_DISK_REMOVED);
914         ITERATE_RDEV(mddev,rdev2,tmp) {
915                 mdp_disk_t *d;
916                 int desc_nr;
917                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
918                     && !test_bit(Faulty, &rdev2->flags))
919                         desc_nr = rdev2->raid_disk;
920                 else
921                         desc_nr = next_spare++;
922                 rdev2->desc_nr = desc_nr;
923                 d = &sb->disks[rdev2->desc_nr];
924                 nr_disks++;
925                 d->number = rdev2->desc_nr;
926                 d->major = MAJOR(rdev2->bdev->bd_dev);
927                 d->minor = MINOR(rdev2->bdev->bd_dev);
928                 if (rdev2->raid_disk >= 0 && test_bit(In_sync, &rdev2->flags)
929                     && !test_bit(Faulty, &rdev2->flags))
930                         d->raid_disk = rdev2->raid_disk;
931                 else
932                         d->raid_disk = rdev2->desc_nr; /* compatibility */
933                 if (test_bit(Faulty, &rdev2->flags))
934                         d->state = (1<<MD_DISK_FAULTY);
935                 else if (test_bit(In_sync, &rdev2->flags)) {
936                         d->state = (1<<MD_DISK_ACTIVE);
937                         d->state |= (1<<MD_DISK_SYNC);
938                         active++;
939                         working++;
940                 } else {
941                         d->state = 0;
942                         spare++;
943                         working++;
944                 }
945                 if (test_bit(WriteMostly, &rdev2->flags))
946                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
947         }
948         /* now set the "removed" and "faulty" bits on any missing devices */
949         for (i=0 ; i < mddev->raid_disks ; i++) {
950                 mdp_disk_t *d = &sb->disks[i];
951                 if (d->state == 0 && d->number == 0) {
952                         d->number = i;
953                         d->raid_disk = i;
954                         d->state = (1<<MD_DISK_REMOVED);
955                         d->state |= (1<<MD_DISK_FAULTY);
956                         failed++;
957                 }
958         }
959         sb->nr_disks = nr_disks;
960         sb->active_disks = active;
961         sb->working_disks = working;
962         sb->failed_disks = failed;
963         sb->spare_disks = spare;
964
965         sb->this_disk = sb->disks[rdev->desc_nr];
966         sb->sb_csum = calc_sb_csum(sb);
967 }
968
969 /*
970  * version 1 superblock
971  */
972
973 static unsigned int calc_sb_1_csum(struct mdp_superblock_1 * sb)
974 {
975         unsigned int disk_csum, csum;
976         unsigned long long newcsum;
977         int size = 256 + le32_to_cpu(sb->max_dev)*2;
978         unsigned int *isuper = (unsigned int*)sb;
979         int i;
980
981         disk_csum = sb->sb_csum;
982         sb->sb_csum = 0;
983         newcsum = 0;
984         for (i=0; size>=4; size -= 4 )
985                 newcsum += le32_to_cpu(*isuper++);
986
987         if (size == 2)
988                 newcsum += le16_to_cpu(*(unsigned short*) isuper);
989
990         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
991         sb->sb_csum = disk_csum;
992         return cpu_to_le32(csum);
993 }
994
995 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
996 {
997         struct mdp_superblock_1 *sb;
998         int ret;
999         sector_t sb_offset;
1000         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1001         int bmask;
1002
1003         /*
1004          * Calculate the position of the superblock.
1005          * It is always aligned to a 4K boundary and
1006          * depeding on minor_version, it can be:
1007          * 0: At least 8K, but less than 12K, from end of device
1008          * 1: At start of device
1009          * 2: 4K from start of device.
1010          */
1011         switch(minor_version) {
1012         case 0:
1013                 sb_offset = rdev->bdev->bd_inode->i_size >> 9;
1014                 sb_offset -= 8*2;
1015                 sb_offset &= ~(sector_t)(4*2-1);
1016                 /* convert from sectors to K */
1017                 sb_offset /= 2;
1018                 break;
1019         case 1:
1020                 sb_offset = 0;
1021                 break;
1022         case 2:
1023                 sb_offset = 4;
1024                 break;
1025         default:
1026                 return -EINVAL;
1027         }
1028         rdev->sb_offset = sb_offset;
1029
1030         /* superblock is rarely larger than 1K, but it can be larger,
1031          * and it is safe to read 4k, so we do that
1032          */
1033         ret = read_disk_sb(rdev, 4096);
1034         if (ret) return ret;
1035
1036
1037         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1038
1039         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1040             sb->major_version != cpu_to_le32(1) ||
1041             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1042             le64_to_cpu(sb->super_offset) != (rdev->sb_offset<<1) ||
1043             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1044                 return -EINVAL;
1045
1046         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1047                 printk("md: invalid superblock checksum on %s\n",
1048                         bdevname(rdev->bdev,b));
1049                 return -EINVAL;
1050         }
1051         if (le64_to_cpu(sb->data_size) < 10) {
1052                 printk("md: data_size too small on %s\n",
1053                        bdevname(rdev->bdev,b));
1054                 return -EINVAL;
1055         }
1056         rdev->preferred_minor = 0xffff;
1057         rdev->data_offset = le64_to_cpu(sb->data_offset);
1058         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1059
1060         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1061         bmask = queue_hardsect_size(rdev->bdev->bd_disk->queue)-1;
1062         if (rdev->sb_size & bmask)
1063                 rdev-> sb_size = (rdev->sb_size | bmask)+1;
1064
1065         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1066                 rdev->desc_nr = -1;
1067         else
1068                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1069
1070         if (refdev == 0)
1071                 ret = 1;
1072         else {
1073                 __u64 ev1, ev2;
1074                 struct mdp_superblock_1 *refsb = 
1075                         (struct mdp_superblock_1*)page_address(refdev->sb_page);
1076
1077                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1078                     sb->level != refsb->level ||
1079                     sb->layout != refsb->layout ||
1080                     sb->chunksize != refsb->chunksize) {
1081                         printk(KERN_WARNING "md: %s has strangely different"
1082                                 " superblock to %s\n",
1083                                 bdevname(rdev->bdev,b),
1084                                 bdevname(refdev->bdev,b2));
1085                         return -EINVAL;
1086                 }
1087                 ev1 = le64_to_cpu(sb->events);
1088                 ev2 = le64_to_cpu(refsb->events);
1089
1090                 if (ev1 > ev2)
1091                         ret = 1;
1092                 else
1093                         ret = 0;
1094         }
1095         if (minor_version) 
1096                 rdev->size = ((rdev->bdev->bd_inode->i_size>>9) - le64_to_cpu(sb->data_offset)) / 2;
1097         else
1098                 rdev->size = rdev->sb_offset;
1099         if (rdev->size < le64_to_cpu(sb->data_size)/2)
1100                 return -EINVAL;
1101         rdev->size = le64_to_cpu(sb->data_size)/2;
1102         if (le32_to_cpu(sb->chunksize))
1103                 rdev->size &= ~((sector_t)le32_to_cpu(sb->chunksize)/2 - 1);
1104
1105         if (le32_to_cpu(sb->size) > rdev->size*2)
1106                 return -EINVAL;
1107         return ret;
1108 }
1109
1110 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1111 {
1112         struct mdp_superblock_1 *sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1113         __u64 ev1 = le64_to_cpu(sb->events);
1114
1115         rdev->raid_disk = -1;
1116         rdev->flags = 0;
1117         if (mddev->raid_disks == 0) {
1118                 mddev->major_version = 1;
1119                 mddev->patch_version = 0;
1120                 mddev->persistent = 1;
1121                 mddev->chunk_size = le32_to_cpu(sb->chunksize) << 9;
1122                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1123                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1124                 mddev->level = le32_to_cpu(sb->level);
1125                 mddev->clevel[0] = 0;
1126                 mddev->layout = le32_to_cpu(sb->layout);
1127                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1128                 mddev->size = le64_to_cpu(sb->size)/2;
1129                 mddev->events = ev1;
1130                 mddev->bitmap_offset = 0;
1131                 mddev->default_bitmap_offset = 1024 >> 9;
1132                 
1133                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1134                 memcpy(mddev->uuid, sb->set_uuid, 16);
1135
1136                 mddev->max_disks =  (4096-256)/2;
1137
1138                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1139                     mddev->bitmap_file == NULL ) {
1140                         if (mddev->level != 1 && mddev->level != 5 && mddev->level != 6
1141                             && mddev->level != 10) {
1142                                 printk(KERN_WARNING "md: bitmaps not supported for this level.\n");
1143                                 return -EINVAL;
1144                         }
1145                         mddev->bitmap_offset = (__s32)le32_to_cpu(sb->bitmap_offset);
1146                 }
1147                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1148                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1149                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1150                         mddev->new_level = le32_to_cpu(sb->new_level);
1151                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1152                         mddev->new_chunk = le32_to_cpu(sb->new_chunk)<<9;
1153                 } else {
1154                         mddev->reshape_position = MaxSector;
1155                         mddev->delta_disks = 0;
1156                         mddev->new_level = mddev->level;
1157                         mddev->new_layout = mddev->layout;
1158                         mddev->new_chunk = mddev->chunk_size;
1159                 }
1160
1161         } else if (mddev->pers == NULL) {
1162                 /* Insist of good event counter while assembling */
1163                 ++ev1;
1164                 if (ev1 < mddev->events)
1165                         return -EINVAL;
1166         } else if (mddev->bitmap) {
1167                 /* If adding to array with a bitmap, then we can accept an
1168                  * older device, but not too old.
1169                  */
1170                 if (ev1 < mddev->bitmap->events_cleared)
1171                         return 0;
1172         } else {
1173                 if (ev1 < mddev->events)
1174                         /* just a hot-add of a new device, leave raid_disk at -1 */
1175                         return 0;
1176         }
1177         if (mddev->level != LEVEL_MULTIPATH) {
1178                 int role;
1179                 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1180                 switch(role) {
1181                 case 0xffff: /* spare */
1182                         break;
1183                 case 0xfffe: /* faulty */
1184                         set_bit(Faulty, &rdev->flags);
1185                         break;
1186                 default:
1187                         if ((le32_to_cpu(sb->feature_map) &
1188                              MD_FEATURE_RECOVERY_OFFSET))
1189                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1190                         else
1191                                 set_bit(In_sync, &rdev->flags);
1192                         rdev->raid_disk = role;
1193                         break;
1194                 }
1195                 if (sb->devflags & WriteMostly1)
1196                         set_bit(WriteMostly, &rdev->flags);
1197         } else /* MULTIPATH are always insync */
1198                 set_bit(In_sync, &rdev->flags);
1199
1200         return 0;
1201 }
1202
1203 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1204 {
1205         struct mdp_superblock_1 *sb;
1206         struct list_head *tmp;
1207         mdk_rdev_t *rdev2;
1208         int max_dev, i;
1209         /* make rdev->sb match mddev and rdev data. */
1210
1211         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1212
1213         sb->feature_map = 0;
1214         sb->pad0 = 0;
1215         sb->recovery_offset = cpu_to_le64(0);
1216         memset(sb->pad1, 0, sizeof(sb->pad1));
1217         memset(sb->pad2, 0, sizeof(sb->pad2));
1218         memset(sb->pad3, 0, sizeof(sb->pad3));
1219
1220         sb->utime = cpu_to_le64((__u64)mddev->utime);
1221         sb->events = cpu_to_le64(mddev->events);
1222         if (mddev->in_sync)
1223                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1224         else
1225                 sb->resync_offset = cpu_to_le64(0);
1226
1227         sb->cnt_corrected_read = atomic_read(&rdev->corrected_errors);
1228
1229         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1230         sb->size = cpu_to_le64(mddev->size<<1);
1231
1232         if (mddev->bitmap && mddev->bitmap_file == NULL) {
1233                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_offset);
1234                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1235         }
1236
1237         if (rdev->raid_disk >= 0 &&
1238             !test_bit(In_sync, &rdev->flags) &&
1239             rdev->recovery_offset > 0) {
1240                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1241                 sb->recovery_offset = cpu_to_le64(rdev->recovery_offset);
1242         }
1243
1244         if (mddev->reshape_position != MaxSector) {
1245                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1246                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1247                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1248                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1249                 sb->new_level = cpu_to_le32(mddev->new_level);
1250                 sb->new_chunk = cpu_to_le32(mddev->new_chunk>>9);
1251         }
1252
1253         max_dev = 0;
1254         ITERATE_RDEV(mddev,rdev2,tmp)
1255                 if (rdev2->desc_nr+1 > max_dev)
1256                         max_dev = rdev2->desc_nr+1;
1257         
1258         sb->max_dev = cpu_to_le32(max_dev);
1259         for (i=0; i<max_dev;i++)
1260                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1261         
1262         ITERATE_RDEV(mddev,rdev2,tmp) {
1263                 i = rdev2->desc_nr;
1264                 if (test_bit(Faulty, &rdev2->flags))
1265                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1266                 else if (test_bit(In_sync, &rdev2->flags))
1267                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1268                 else if (rdev2->raid_disk >= 0 && rdev2->recovery_offset > 0)
1269                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1270                 else
1271                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1272         }
1273
1274         sb->sb_csum = calc_sb_1_csum(sb);
1275 }
1276
1277
1278 static struct super_type super_types[] = {
1279         [0] = {
1280                 .name   = "0.90.0",
1281                 .owner  = THIS_MODULE,
1282                 .load_super     = super_90_load,
1283                 .validate_super = super_90_validate,
1284                 .sync_super     = super_90_sync,
1285         },
1286         [1] = {
1287                 .name   = "md-1",
1288                 .owner  = THIS_MODULE,
1289                 .load_super     = super_1_load,
1290                 .validate_super = super_1_validate,
1291                 .sync_super     = super_1_sync,
1292         },
1293 };
1294         
1295 static mdk_rdev_t * match_dev_unit(mddev_t *mddev, mdk_rdev_t *dev)
1296 {
1297         struct list_head *tmp;
1298         mdk_rdev_t *rdev;
1299
1300         ITERATE_RDEV(mddev,rdev,tmp)
1301                 if (rdev->bdev->bd_contains == dev->bdev->bd_contains)
1302                         return rdev;
1303
1304         return NULL;
1305 }
1306
1307 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1308 {
1309         struct list_head *tmp;
1310         mdk_rdev_t *rdev;
1311
1312         ITERATE_RDEV(mddev1,rdev,tmp)
1313                 if (match_dev_unit(mddev2, rdev))
1314                         return 1;
1315
1316         return 0;
1317 }
1318
1319 static LIST_HEAD(pending_raid_disks);
1320
1321 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1322 {
1323         mdk_rdev_t *same_pdev;
1324         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1325         struct kobject *ko;
1326         char *s;
1327
1328         if (rdev->mddev) {
1329                 MD_BUG();
1330                 return -EINVAL;
1331         }
1332         /* make sure rdev->size exceeds mddev->size */
1333         if (rdev->size && (mddev->size == 0 || rdev->size < mddev->size)) {
1334                 if (mddev->pers)
1335                         /* Cannot change size, so fail */
1336                         return -ENOSPC;
1337                 else
1338                         mddev->size = rdev->size;
1339         }
1340         same_pdev = match_dev_unit(mddev, rdev);
1341         if (same_pdev)
1342                 printk(KERN_WARNING
1343                         "%s: WARNING: %s appears to be on the same physical"
1344                         " disk as %s. True\n     protection against single-disk"
1345                         " failure might be compromised.\n",
1346                         mdname(mddev), bdevname(rdev->bdev,b),
1347                         bdevname(same_pdev->bdev,b2));
1348
1349         /* Verify rdev->desc_nr is unique.
1350          * If it is -1, assign a free number, else
1351          * check number is not in use
1352          */
1353         if (rdev->desc_nr < 0) {
1354                 int choice = 0;
1355                 if (mddev->pers) choice = mddev->raid_disks;
1356                 while (find_rdev_nr(mddev, choice))
1357                         choice++;
1358                 rdev->desc_nr = choice;
1359         } else {
1360                 if (find_rdev_nr(mddev, rdev->desc_nr))
1361                         return -EBUSY;
1362         }
1363         bdevname(rdev->bdev,b);
1364         if (kobject_set_name(&rdev->kobj, "dev-%s", b) < 0)
1365                 return -ENOMEM;
1366         while ( (s=strchr(rdev->kobj.k_name, '/')) != NULL)
1367                 *s = '!';
1368                         
1369         list_add(&rdev->same_set, &mddev->disks);
1370         rdev->mddev = mddev;
1371         printk(KERN_INFO "md: bind<%s>\n", b);
1372
1373         rdev->kobj.parent = &mddev->kobj;
1374         kobject_add(&rdev->kobj);
1375
1376         if (rdev->bdev->bd_part)
1377                 ko = &rdev->bdev->bd_part->kobj;
1378         else
1379                 ko = &rdev->bdev->bd_disk->kobj;
1380         sysfs_create_link(&rdev->kobj, ko, "block");
1381         bd_claim_by_disk(rdev->bdev, rdev, mddev->gendisk);
1382         return 0;
1383 }
1384
1385 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
1386 {
1387         char b[BDEVNAME_SIZE];
1388         if (!rdev->mddev) {
1389                 MD_BUG();
1390                 return;
1391         }
1392         bd_release_from_disk(rdev->bdev, rdev->mddev->gendisk);
1393         list_del_init(&rdev->same_set);
1394         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
1395         rdev->mddev = NULL;
1396         sysfs_remove_link(&rdev->kobj, "block");
1397         kobject_del(&rdev->kobj);
1398 }
1399
1400 /*
1401  * prevent the device from being mounted, repartitioned or
1402  * otherwise reused by a RAID array (or any other kernel
1403  * subsystem), by bd_claiming the device.
1404  */
1405 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev)
1406 {
1407         int err = 0;
1408         struct block_device *bdev;
1409         char b[BDEVNAME_SIZE];
1410
1411         bdev = open_partition_by_devnum(dev, FMODE_READ|FMODE_WRITE);
1412         if (IS_ERR(bdev)) {
1413                 printk(KERN_ERR "md: could not open %s.\n",
1414                         __bdevname(dev, b));
1415                 return PTR_ERR(bdev);
1416         }
1417         err = bd_claim(bdev, rdev);
1418         if (err) {
1419                 printk(KERN_ERR "md: could not bd_claim %s.\n",
1420                         bdevname(bdev, b));
1421                 blkdev_put_partition(bdev);
1422                 return err;
1423         }
1424         rdev->bdev = bdev;
1425         return err;
1426 }
1427
1428 static void unlock_rdev(mdk_rdev_t *rdev)
1429 {
1430         struct block_device *bdev = rdev->bdev;
1431         rdev->bdev = NULL;
1432         if (!bdev)
1433                 MD_BUG();
1434         bd_release(bdev);
1435         blkdev_put_partition(bdev);
1436 }
1437
1438 void md_autodetect_dev(dev_t dev);
1439
1440 static void export_rdev(mdk_rdev_t * rdev)
1441 {
1442         char b[BDEVNAME_SIZE];
1443         printk(KERN_INFO "md: export_rdev(%s)\n",
1444                 bdevname(rdev->bdev,b));
1445         if (rdev->mddev)
1446                 MD_BUG();
1447         free_disk_sb(rdev);
1448         list_del_init(&rdev->same_set);
1449 #ifndef MODULE
1450         md_autodetect_dev(rdev->bdev->bd_dev);
1451 #endif
1452         unlock_rdev(rdev);
1453         kobject_put(&rdev->kobj);
1454 }
1455
1456 static void kick_rdev_from_array(mdk_rdev_t * rdev)
1457 {
1458         unbind_rdev_from_array(rdev);
1459         export_rdev(rdev);
1460 }
1461
1462 static void export_array(mddev_t *mddev)
1463 {
1464         struct list_head *tmp;
1465         mdk_rdev_t *rdev;
1466
1467         ITERATE_RDEV(mddev,rdev,tmp) {
1468                 if (!rdev->mddev) {
1469                         MD_BUG();
1470                         continue;
1471                 }
1472                 kick_rdev_from_array(rdev);
1473         }
1474         if (!list_empty(&mddev->disks))
1475                 MD_BUG();
1476         mddev->raid_disks = 0;
1477         mddev->major_version = 0;
1478 }
1479
1480 static void print_desc(mdp_disk_t *desc)
1481 {
1482         printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
1483                 desc->major,desc->minor,desc->raid_disk,desc->state);
1484 }
1485
1486 static void print_sb(mdp_super_t *sb)
1487 {
1488         int i;
1489
1490         printk(KERN_INFO 
1491                 "md:  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
1492                 sb->major_version, sb->minor_version, sb->patch_version,
1493                 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
1494                 sb->ctime);
1495         printk(KERN_INFO "md:     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
1496                 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
1497                 sb->md_minor, sb->layout, sb->chunk_size);
1498         printk(KERN_INFO "md:     UT:%08x ST:%d AD:%d WD:%d"
1499                 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
1500                 sb->utime, sb->state, sb->active_disks, sb->working_disks,
1501                 sb->failed_disks, sb->spare_disks,
1502                 sb->sb_csum, (unsigned long)sb->events_lo);
1503
1504         printk(KERN_INFO);
1505         for (i = 0; i < MD_SB_DISKS; i++) {
1506                 mdp_disk_t *desc;
1507
1508                 desc = sb->disks + i;
1509                 if (desc->number || desc->major || desc->minor ||
1510                     desc->raid_disk || (desc->state && (desc->state != 4))) {
1511                         printk("     D %2d: ", i);
1512                         print_desc(desc);
1513                 }
1514         }
1515         printk(KERN_INFO "md:     THIS: ");
1516         print_desc(&sb->this_disk);
1517
1518 }
1519
1520 static void print_rdev(mdk_rdev_t *rdev)
1521 {
1522         char b[BDEVNAME_SIZE];
1523         printk(KERN_INFO "md: rdev %s, SZ:%08llu F:%d S:%d DN:%u\n",
1524                 bdevname(rdev->bdev,b), (unsigned long long)rdev->size,
1525                 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
1526                 rdev->desc_nr);
1527         if (rdev->sb_loaded) {
1528                 printk(KERN_INFO "md: rdev superblock:\n");
1529                 print_sb((mdp_super_t*)page_address(rdev->sb_page));
1530         } else
1531                 printk(KERN_INFO "md: no rdev superblock!\n");
1532 }
1533
1534 static void md_print_devices(void)
1535 {
1536         struct list_head *tmp, *tmp2;
1537         mdk_rdev_t *rdev;
1538         mddev_t *mddev;
1539         char b[BDEVNAME_SIZE];
1540
1541         printk("\n");
1542         printk("md:     **********************************\n");
1543         printk("md:     * <COMPLETE RAID STATE PRINTOUT> *\n");
1544         printk("md:     **********************************\n");
1545         ITERATE_MDDEV(mddev,tmp) {
1546
1547                 if (mddev->bitmap)
1548                         bitmap_print_sb(mddev->bitmap);
1549                 else
1550                         printk("%s: ", mdname(mddev));
1551                 ITERATE_RDEV(mddev,rdev,tmp2)
1552                         printk("<%s>", bdevname(rdev->bdev,b));
1553                 printk("\n");
1554
1555                 ITERATE_RDEV(mddev,rdev,tmp2)
1556                         print_rdev(rdev);
1557         }
1558         printk("md:     **********************************\n");
1559         printk("\n");
1560 }
1561
1562
1563 static void sync_sbs(mddev_t * mddev, int nospares)
1564 {
1565         /* Update each superblock (in-memory image), but
1566          * if we are allowed to, skip spares which already
1567          * have the right event counter, or have one earlier
1568          * (which would mean they aren't being marked as dirty
1569          * with the rest of the array)
1570          */
1571         mdk_rdev_t *rdev;
1572         struct list_head *tmp;
1573
1574         ITERATE_RDEV(mddev,rdev,tmp) {
1575                 if (rdev->sb_events == mddev->events ||
1576                     (nospares &&
1577                      rdev->raid_disk < 0 &&
1578                      (rdev->sb_events&1)==0 &&
1579                      rdev->sb_events+1 == mddev->events)) {
1580                         /* Don't update this superblock */
1581                         rdev->sb_loaded = 2;
1582                 } else {
1583                         super_types[mddev->major_version].
1584                                 sync_super(mddev, rdev);
1585                         rdev->sb_loaded = 1;
1586                 }
1587         }
1588 }
1589
1590 static void md_update_sb(mddev_t * mddev, int force_change)
1591 {
1592         int err;
1593         struct list_head *tmp;
1594         mdk_rdev_t *rdev;
1595         int sync_req;
1596         int nospares = 0;
1597
1598 repeat:
1599         spin_lock_irq(&mddev->write_lock);
1600
1601         set_bit(MD_CHANGE_PENDING, &mddev->flags);
1602         if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
1603                 force_change = 1;
1604         if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
1605                 /* just a clean<-> dirty transition, possibly leave spares alone,
1606                  * though if events isn't the right even/odd, we will have to do
1607                  * spares after all
1608                  */
1609                 nospares = 1;
1610         if (force_change)
1611                 nospares = 0;
1612         if (mddev->degraded)
1613                 /* If the array is degraded, then skipping spares is both
1614                  * dangerous and fairly pointless.
1615                  * Dangerous because a device that was removed from the array
1616                  * might have a event_count that still looks up-to-date,
1617                  * so it can be re-added without a resync.
1618                  * Pointless because if there are any spares to skip,
1619                  * then a recovery will happen and soon that array won't
1620                  * be degraded any more and the spare can go back to sleep then.
1621                  */
1622                 nospares = 0;
1623
1624         sync_req = mddev->in_sync;
1625         mddev->utime = get_seconds();
1626
1627         /* If this is just a dirty<->clean transition, and the array is clean
1628          * and 'events' is odd, we can roll back to the previous clean state */
1629         if (nospares
1630             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
1631             && (mddev->events & 1))
1632                 mddev->events--;
1633         else {
1634                 /* otherwise we have to go forward and ... */
1635                 mddev->events ++;
1636                 if (!mddev->in_sync || mddev->recovery_cp != MaxSector) { /* not clean */
1637                         /* .. if the array isn't clean, insist on an odd 'events' */
1638                         if ((mddev->events&1)==0) {
1639                                 mddev->events++;
1640                                 nospares = 0;
1641                         }
1642                 } else {
1643                         /* otherwise insist on an even 'events' (for clean states) */
1644                         if ((mddev->events&1)) {
1645                                 mddev->events++;
1646                                 nospares = 0;
1647                         }
1648                 }
1649         }
1650
1651         if (!mddev->events) {
1652                 /*
1653                  * oops, this 64-bit counter should never wrap.
1654                  * Either we are in around ~1 trillion A.C., assuming
1655                  * 1 reboot per second, or we have a bug:
1656                  */
1657                 MD_BUG();
1658                 mddev->events --;
1659         }
1660         sync_sbs(mddev, nospares);
1661
1662         /*
1663          * do not write anything to disk if using
1664          * nonpersistent superblocks
1665          */
1666         if (!mddev->persistent) {
1667                 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
1668                 spin_unlock_irq(&mddev->write_lock);
1669                 wake_up(&mddev->sb_wait);
1670                 return;
1671         }
1672         spin_unlock_irq(&mddev->write_lock);
1673
1674         dprintk(KERN_INFO 
1675                 "md: updating %s RAID superblock on device (in sync %d)\n",
1676                 mdname(mddev),mddev->in_sync);
1677
1678         err = bitmap_update_sb(mddev->bitmap);
1679         ITERATE_RDEV(mddev,rdev,tmp) {
1680                 char b[BDEVNAME_SIZE];
1681                 dprintk(KERN_INFO "md: ");
1682                 if (rdev->sb_loaded != 1)
1683                         continue; /* no noise on spare devices */
1684                 if (test_bit(Faulty, &rdev->flags))
1685                         dprintk("(skipping faulty ");
1686
1687                 dprintk("%s ", bdevname(rdev->bdev,b));
1688                 if (!test_bit(Faulty, &rdev->flags)) {
1689                         md_super_write(mddev,rdev,
1690                                        rdev->sb_offset<<1, rdev->sb_size,
1691                                        rdev->sb_page);
1692                         dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
1693                                 bdevname(rdev->bdev,b),
1694                                 (unsigned long long)rdev->sb_offset);
1695                         rdev->sb_events = mddev->events;
1696
1697                 } else
1698                         dprintk(")\n");
1699                 if (mddev->level == LEVEL_MULTIPATH)
1700                         /* only need to write one superblock... */
1701                         break;
1702         }
1703         md_super_wait(mddev);
1704         /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
1705
1706         spin_lock_irq(&mddev->write_lock);
1707         if (mddev->in_sync != sync_req ||
1708             test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
1709                 /* have to write it out again */
1710                 spin_unlock_irq(&mddev->write_lock);
1711                 goto repeat;
1712         }
1713         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
1714         spin_unlock_irq(&mddev->write_lock);
1715         wake_up(&mddev->sb_wait);
1716
1717 }
1718
1719 /* words written to sysfs files may, or my not, be \n terminated.
1720  * We want to accept with case. For this we use cmd_match.
1721  */
1722 static int cmd_match(const char *cmd, const char *str)
1723 {
1724         /* See if cmd, written into a sysfs file, matches
1725          * str.  They must either be the same, or cmd can
1726          * have a trailing newline
1727          */
1728         while (*cmd && *str && *cmd == *str) {
1729                 cmd++;
1730                 str++;
1731         }
1732         if (*cmd == '\n')
1733                 cmd++;
1734         if (*str || *cmd)
1735                 return 0;
1736         return 1;
1737 }
1738
1739 struct rdev_sysfs_entry {
1740         struct attribute attr;
1741         ssize_t (*show)(mdk_rdev_t *, char *);
1742         ssize_t (*store)(mdk_rdev_t *, const char *, size_t);
1743 };
1744
1745 static ssize_t
1746 state_show(mdk_rdev_t *rdev, char *page)
1747 {
1748         char *sep = "";
1749         int len=0;
1750
1751         if (test_bit(Faulty, &rdev->flags)) {
1752                 len+= sprintf(page+len, "%sfaulty",sep);
1753                 sep = ",";
1754         }
1755         if (test_bit(In_sync, &rdev->flags)) {
1756                 len += sprintf(page+len, "%sin_sync",sep);
1757                 sep = ",";
1758         }
1759         if (test_bit(WriteMostly, &rdev->flags)) {
1760                 len += sprintf(page+len, "%swrite_mostly",sep);
1761                 sep = ",";
1762         }
1763         if (!test_bit(Faulty, &rdev->flags) &&
1764             !test_bit(In_sync, &rdev->flags)) {
1765                 len += sprintf(page+len, "%sspare", sep);
1766                 sep = ",";
1767         }
1768         return len+sprintf(page+len, "\n");
1769 }
1770
1771 static ssize_t
1772 state_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1773 {
1774         /* can write
1775          *  faulty  - simulates and error
1776          *  remove  - disconnects the device
1777          *  writemostly - sets write_mostly
1778          *  -writemostly - clears write_mostly
1779          */
1780         int err = -EINVAL;
1781         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
1782                 md_error(rdev->mddev, rdev);
1783                 err = 0;
1784         } else if (cmd_match(buf, "remove")) {
1785                 if (rdev->raid_disk >= 0)
1786                         err = -EBUSY;
1787                 else {
1788                         mddev_t *mddev = rdev->mddev;
1789                         kick_rdev_from_array(rdev);
1790                         md_update_sb(mddev, 1);
1791                         md_new_event(mddev);
1792                         err = 0;
1793                 }
1794         } else if (cmd_match(buf, "writemostly")) {
1795                 set_bit(WriteMostly, &rdev->flags);
1796                 err = 0;
1797         } else if (cmd_match(buf, "-writemostly")) {
1798                 clear_bit(WriteMostly, &rdev->flags);
1799                 err = 0;
1800         }
1801         return err ? err : len;
1802 }
1803 static struct rdev_sysfs_entry rdev_state =
1804 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
1805
1806 static ssize_t
1807 super_show(mdk_rdev_t *rdev, char *page)
1808 {
1809         if (rdev->sb_loaded && rdev->sb_size) {
1810                 memcpy(page, page_address(rdev->sb_page), rdev->sb_size);
1811                 return rdev->sb_size;
1812         } else
1813                 return 0;
1814 }
1815 static struct rdev_sysfs_entry rdev_super = __ATTR_RO(super);
1816
1817 static ssize_t
1818 errors_show(mdk_rdev_t *rdev, char *page)
1819 {
1820         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
1821 }
1822
1823 static ssize_t
1824 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1825 {
1826         char *e;
1827         unsigned long n = simple_strtoul(buf, &e, 10);
1828         if (*buf && (*e == 0 || *e == '\n')) {
1829                 atomic_set(&rdev->corrected_errors, n);
1830                 return len;
1831         }
1832         return -EINVAL;
1833 }
1834 static struct rdev_sysfs_entry rdev_errors =
1835 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
1836
1837 static ssize_t
1838 slot_show(mdk_rdev_t *rdev, char *page)
1839 {
1840         if (rdev->raid_disk < 0)
1841                 return sprintf(page, "none\n");
1842         else
1843                 return sprintf(page, "%d\n", rdev->raid_disk);
1844 }
1845
1846 static ssize_t
1847 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1848 {
1849         char *e;
1850         int slot = simple_strtoul(buf, &e, 10);
1851         if (strncmp(buf, "none", 4)==0)
1852                 slot = -1;
1853         else if (e==buf || (*e && *e!= '\n'))
1854                 return -EINVAL;
1855         if (rdev->mddev->pers)
1856                 /* Cannot set slot in active array (yet) */
1857                 return -EBUSY;
1858         if (slot >= rdev->mddev->raid_disks)
1859                 return -ENOSPC;
1860         rdev->raid_disk = slot;
1861         /* assume it is working */
1862         rdev->flags = 0;
1863         set_bit(In_sync, &rdev->flags);
1864         return len;
1865 }
1866
1867
1868 static struct rdev_sysfs_entry rdev_slot =
1869 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
1870
1871 static ssize_t
1872 offset_show(mdk_rdev_t *rdev, char *page)
1873 {
1874         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
1875 }
1876
1877 static ssize_t
1878 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1879 {
1880         char *e;
1881         unsigned long long offset = simple_strtoull(buf, &e, 10);
1882         if (e==buf || (*e && *e != '\n'))
1883                 return -EINVAL;
1884         if (rdev->mddev->pers)
1885                 return -EBUSY;
1886         rdev->data_offset = offset;
1887         return len;
1888 }
1889
1890 static struct rdev_sysfs_entry rdev_offset =
1891 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
1892
1893 static ssize_t
1894 rdev_size_show(mdk_rdev_t *rdev, char *page)
1895 {
1896         return sprintf(page, "%llu\n", (unsigned long long)rdev->size);
1897 }
1898
1899 static ssize_t
1900 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
1901 {
1902         char *e;
1903         unsigned long long size = simple_strtoull(buf, &e, 10);
1904         if (e==buf || (*e && *e != '\n'))
1905                 return -EINVAL;
1906         if (rdev->mddev->pers)
1907                 return -EBUSY;
1908         rdev->size = size;
1909         if (size < rdev->mddev->size || rdev->mddev->size == 0)
1910                 rdev->mddev->size = size;
1911         return len;
1912 }
1913
1914 static struct rdev_sysfs_entry rdev_size =
1915 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
1916
1917 static struct attribute *rdev_default_attrs[] = {
1918         &rdev_state.attr,
1919         &rdev_super.attr,
1920         &rdev_errors.attr,
1921         &rdev_slot.attr,
1922         &rdev_offset.attr,
1923         &rdev_size.attr,
1924         NULL,
1925 };
1926 static ssize_t
1927 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
1928 {
1929         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
1930         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
1931
1932         if (!entry->show)
1933                 return -EIO;
1934         return entry->show(rdev, page);
1935 }
1936
1937 static ssize_t
1938 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
1939               const char *page, size_t length)
1940 {
1941         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
1942         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
1943
1944         if (!entry->store)
1945                 return -EIO;
1946         if (!capable(CAP_SYS_ADMIN))
1947                 return -EACCES;
1948         return entry->store(rdev, page, length);
1949 }
1950
1951 static void rdev_free(struct kobject *ko)
1952 {
1953         mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
1954         kfree(rdev);
1955 }
1956 static struct sysfs_ops rdev_sysfs_ops = {
1957         .show           = rdev_attr_show,
1958         .store          = rdev_attr_store,
1959 };
1960 static struct kobj_type rdev_ktype = {
1961         .release        = rdev_free,
1962         .sysfs_ops      = &rdev_sysfs_ops,
1963         .default_attrs  = rdev_default_attrs,
1964 };
1965
1966 /*
1967  * Import a device. If 'super_format' >= 0, then sanity check the superblock
1968  *
1969  * mark the device faulty if:
1970  *
1971  *   - the device is nonexistent (zero size)
1972  *   - the device has no valid superblock
1973  *
1974  * a faulty rdev _never_ has rdev->sb set.
1975  */
1976 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
1977 {
1978         char b[BDEVNAME_SIZE];
1979         int err;
1980         mdk_rdev_t *rdev;
1981         sector_t size;
1982
1983         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
1984         if (!rdev) {
1985                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
1986                 return ERR_PTR(-ENOMEM);
1987         }
1988
1989         if ((err = alloc_disk_sb(rdev)))
1990                 goto abort_free;
1991
1992         err = lock_rdev(rdev, newdev);
1993         if (err)
1994                 goto abort_free;
1995
1996         rdev->kobj.parent = NULL;
1997         rdev->kobj.ktype = &rdev_ktype;
1998         kobject_init(&rdev->kobj);
1999
2000         rdev->desc_nr = -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         /* can only set raid_disks if array is not yet active */
2231         char *e;
2232         int rv = 0;
2233         unsigned long n = simple_strtoul(buf, &e, 10);
2234
2235         if (!*buf || (*e && *e != '\n'))
2236                 return -EINVAL;
2237
2238         if (mddev->pers)
2239                 rv = update_raid_disks(mddev, n);
2240         else
2241                 mddev->raid_disks = n;
2242         return rv ? rv : len;
2243 }
2244 static struct md_sysfs_entry md_raid_disks =
2245 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
2246
2247 static ssize_t
2248 chunk_size_show(mddev_t *mddev, char *page)
2249 {
2250         return sprintf(page, "%d\n", mddev->chunk_size);
2251 }
2252
2253 static ssize_t
2254 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
2255 {
2256         /* can only set chunk_size if array is not yet active */
2257         char *e;
2258         unsigned long n = simple_strtoul(buf, &e, 10);
2259
2260         if (mddev->pers)
2261                 return -EBUSY;
2262         if (!*buf || (*e && *e != '\n'))
2263                 return -EINVAL;
2264
2265         mddev->chunk_size = n;
2266         return len;
2267 }
2268 static struct md_sysfs_entry md_chunk_size =
2269 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
2270
2271 static ssize_t
2272 resync_start_show(mddev_t *mddev, char *page)
2273 {
2274         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
2275 }
2276
2277 static ssize_t
2278 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
2279 {
2280         /* can only set chunk_size if array is not yet active */
2281         char *e;
2282         unsigned long long n = simple_strtoull(buf, &e, 10);
2283
2284         if (mddev->pers)
2285                 return -EBUSY;
2286         if (!*buf || (*e && *e != '\n'))
2287                 return -EINVAL;
2288
2289         mddev->recovery_cp = n;
2290         return len;
2291 }
2292 static struct md_sysfs_entry md_resync_start =
2293 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
2294
2295 /*
2296  * The array state can be:
2297  *
2298  * clear
2299  *     No devices, no size, no level
2300  *     Equivalent to STOP_ARRAY ioctl
2301  * inactive
2302  *     May have some settings, but array is not active
2303  *        all IO results in error
2304  *     When written, doesn't tear down array, but just stops it
2305  * suspended (not supported yet)
2306  *     All IO requests will block. The array can be reconfigured.
2307  *     Writing this, if accepted, will block until array is quiessent
2308  * readonly
2309  *     no resync can happen.  no superblocks get written.
2310  *     write requests fail
2311  * read-auto
2312  *     like readonly, but behaves like 'clean' on a write request.
2313  *
2314  * clean - no pending writes, but otherwise active.
2315  *     When written to inactive array, starts without resync
2316  *     If a write request arrives then
2317  *       if metadata is known, mark 'dirty' and switch to 'active'.
2318  *       if not known, block and switch to write-pending
2319  *     If written to an active array that has pending writes, then fails.
2320  * active
2321  *     fully active: IO and resync can be happening.
2322  *     When written to inactive array, starts with resync
2323  *
2324  * write-pending
2325  *     clean, but writes are blocked waiting for 'active' to be written.
2326  *
2327  * active-idle
2328  *     like active, but no writes have been seen for a while (100msec).
2329  *
2330  */
2331 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
2332                    write_pending, active_idle, bad_word};
2333 static char *array_states[] = {
2334         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
2335         "write-pending", "active-idle", NULL };
2336
2337 static int match_word(const char *word, char **list)
2338 {
2339         int n;
2340         for (n=0; list[n]; n++)
2341                 if (cmd_match(word, list[n]))
2342                         break;
2343         return n;
2344 }
2345
2346 static ssize_t
2347 array_state_show(mddev_t *mddev, char *page)
2348 {
2349         enum array_state st = inactive;
2350
2351         if (mddev->pers)
2352                 switch(mddev->ro) {
2353                 case 1:
2354                         st = readonly;
2355                         break;
2356                 case 2:
2357                         st = read_auto;
2358                         break;
2359                 case 0:
2360                         if (mddev->in_sync)
2361                                 st = clean;
2362                         else if (mddev->safemode)
2363                                 st = active_idle;
2364                         else
2365                                 st = active;
2366                 }
2367         else {
2368                 if (list_empty(&mddev->disks) &&
2369                     mddev->raid_disks == 0 &&
2370                     mddev->size == 0)
2371                         st = clear;
2372                 else
2373                         st = inactive;
2374         }
2375         return sprintf(page, "%s\n", array_states[st]);
2376 }
2377
2378 static int do_md_stop(mddev_t * mddev, int ro);
2379 static int do_md_run(mddev_t * mddev);
2380 static int restart_array(mddev_t *mddev);
2381
2382 static ssize_t
2383 array_state_store(mddev_t *mddev, const char *buf, size_t len)
2384 {
2385         int err = -EINVAL;
2386         enum array_state st = match_word(buf, array_states);
2387         switch(st) {
2388         case bad_word:
2389                 break;
2390         case clear:
2391                 /* stopping an active array */
2392                 if (mddev->pers) {
2393                         if (atomic_read(&mddev->active) > 1)
2394                                 return -EBUSY;
2395                         err = do_md_stop(mddev, 0);
2396                 }
2397                 break;
2398         case inactive:
2399                 /* stopping an active array */
2400                 if (mddev->pers) {
2401                         if (atomic_read(&mddev->active) > 1)
2402                                 return -EBUSY;
2403                         err = do_md_stop(mddev, 2);
2404                 }
2405                 break;
2406         case suspended:
2407                 break; /* not supported yet */
2408         case readonly:
2409                 if (mddev->pers)
2410                         err = do_md_stop(mddev, 1);
2411                 else {
2412                         mddev->ro = 1;
2413                         err = do_md_run(mddev);
2414                 }
2415                 break;
2416         case read_auto:
2417                 /* stopping an active array */
2418                 if (mddev->pers) {
2419                         err = do_md_stop(mddev, 1);
2420                         if (err == 0)
2421                                 mddev->ro = 2; /* FIXME mark devices writable */
2422                 } else {
2423                         mddev->ro = 2;
2424                         err = do_md_run(mddev);
2425                 }
2426                 break;
2427         case clean:
2428                 if (mddev->pers) {
2429                         restart_array(mddev);
2430                         spin_lock_irq(&mddev->write_lock);
2431                         if (atomic_read(&mddev->writes_pending) == 0) {
2432                                 mddev->in_sync = 1;
2433                                 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
2434                         }
2435                         spin_unlock_irq(&mddev->write_lock);
2436                 } else {
2437                         mddev->ro = 0;
2438                         mddev->recovery_cp = MaxSector;
2439                         err = do_md_run(mddev);
2440                 }
2441                 break;
2442         case active:
2443                 if (mddev->pers) {
2444                         restart_array(mddev);
2445                         clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2446                         wake_up(&mddev->sb_wait);
2447                         err = 0;
2448                 } else {
2449                         mddev->ro = 0;
2450                         err = do_md_run(mddev);
2451                 }
2452                 break;
2453         case write_pending:
2454         case active_idle:
2455                 /* these cannot be set */
2456                 break;
2457         }
2458         if (err)
2459                 return err;
2460         else
2461                 return len;
2462 }
2463 static struct md_sysfs_entry md_array_state =
2464 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
2465
2466 static ssize_t
2467 null_show(mddev_t *mddev, char *page)
2468 {
2469         return -EINVAL;
2470 }
2471
2472 static ssize_t
2473 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
2474 {
2475         /* buf must be %d:%d\n? giving major and minor numbers */
2476         /* The new device is added to the array.
2477          * If the array has a persistent superblock, we read the
2478          * superblock to initialise info and check validity.
2479          * Otherwise, only checking done is that in bind_rdev_to_array,
2480          * which mainly checks size.
2481          */
2482         char *e;
2483         int major = simple_strtoul(buf, &e, 10);
2484         int minor;
2485         dev_t dev;
2486         mdk_rdev_t *rdev;
2487         int err;
2488
2489         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
2490                 return -EINVAL;
2491         minor = simple_strtoul(e+1, &e, 10);
2492         if (*e && *e != '\n')
2493                 return -EINVAL;
2494         dev = MKDEV(major, minor);
2495         if (major != MAJOR(dev) ||
2496             minor != MINOR(dev))
2497                 return -EOVERFLOW;
2498
2499
2500         if (mddev->persistent) {
2501                 rdev = md_import_device(dev, mddev->major_version,
2502                                         mddev->minor_version);
2503                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
2504                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
2505                                                        mdk_rdev_t, same_set);
2506                         err = super_types[mddev->major_version]
2507                                 .load_super(rdev, rdev0, mddev->minor_version);
2508                         if (err < 0)
2509                                 goto out;
2510                 }
2511         } else
2512                 rdev = md_import_device(dev, -1, -1);
2513
2514         if (IS_ERR(rdev))
2515                 return PTR_ERR(rdev);
2516         err = bind_rdev_to_array(rdev, mddev);
2517  out:
2518         if (err)
2519                 export_rdev(rdev);
2520         return err ? err : len;
2521 }
2522
2523 static struct md_sysfs_entry md_new_device =
2524 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
2525
2526 static ssize_t
2527 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
2528 {
2529         char *end;
2530         unsigned long chunk, end_chunk;
2531
2532         if (!mddev->bitmap)
2533                 goto out;
2534         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
2535         while (*buf) {
2536                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
2537                 if (buf == end) break;
2538                 if (*end == '-') { /* range */
2539                         buf = end + 1;
2540                         end_chunk = simple_strtoul(buf, &end, 0);
2541                         if (buf == end) break;
2542                 }
2543                 if (*end && !isspace(*end)) break;
2544                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
2545                 buf = end;
2546                 while (isspace(*buf)) buf++;
2547         }
2548         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
2549 out:
2550         return len;
2551 }
2552
2553 static struct md_sysfs_entry md_bitmap =
2554 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
2555
2556 static ssize_t
2557 size_show(mddev_t *mddev, char *page)
2558 {
2559         return sprintf(page, "%llu\n", (unsigned long long)mddev->size);
2560 }
2561
2562 static int update_size(mddev_t *mddev, unsigned long size);
2563
2564 static ssize_t
2565 size_store(mddev_t *mddev, const char *buf, size_t len)
2566 {
2567         /* If array is inactive, we can reduce the component size, but
2568          * not increase it (except from 0).
2569          * If array is active, we can try an on-line resize
2570          */
2571         char *e;
2572         int err = 0;
2573         unsigned long long size = simple_strtoull(buf, &e, 10);
2574         if (!*buf || *buf == '\n' ||
2575             (*e && *e != '\n'))
2576                 return -EINVAL;
2577
2578         if (mddev->pers) {
2579                 err = update_size(mddev, size);
2580                 md_update_sb(mddev, 1);
2581         } else {
2582                 if (mddev->size == 0 ||
2583                     mddev->size > size)
2584                         mddev->size = size;
2585                 else
2586                         err = -ENOSPC;
2587         }
2588         return err ? err : len;
2589 }
2590
2591 static struct md_sysfs_entry md_size =
2592 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
2593
2594
2595 /* Metdata version.
2596  * This is either 'none' for arrays with externally managed metadata,
2597  * or N.M for internally known formats
2598  */
2599 static ssize_t
2600 metadata_show(mddev_t *mddev, char *page)
2601 {
2602         if (mddev->persistent)
2603                 return sprintf(page, "%d.%d\n",
2604                                mddev->major_version, mddev->minor_version);
2605         else
2606                 return sprintf(page, "none\n");
2607 }
2608
2609 static ssize_t
2610 metadata_store(mddev_t *mddev, const char *buf, size_t len)
2611 {
2612         int major, minor;
2613         char *e;
2614         if (!list_empty(&mddev->disks))
2615                 return -EBUSY;
2616
2617         if (cmd_match(buf, "none")) {
2618                 mddev->persistent = 0;
2619                 mddev->major_version = 0;
2620                 mddev->minor_version = 90;
2621                 return len;
2622         }
2623         major = simple_strtoul(buf, &e, 10);
2624         if (e==buf || *e != '.')
2625                 return -EINVAL;
2626         buf = e+1;
2627         minor = simple_strtoul(buf, &e, 10);
2628         if (e==buf || *e != '\n')
2629                 return -EINVAL;
2630         if (major >= sizeof(super_types)/sizeof(super_types[0]) ||
2631             super_types[major].name == NULL)
2632                 return -ENOENT;
2633         mddev->major_version = major;
2634         mddev->minor_version = minor;
2635         mddev->persistent = 1;
2636         return len;
2637 }
2638
2639 static struct md_sysfs_entry md_metadata =
2640 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
2641
2642 static ssize_t
2643 action_show(mddev_t *mddev, char *page)
2644 {
2645         char *type = "idle";
2646         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2647             test_bit(MD_RECOVERY_NEEDED, &mddev->recovery)) {
2648                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2649                         type = "reshape";
2650                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2651                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2652                                 type = "resync";
2653                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2654                                 type = "check";
2655                         else
2656                                 type = "repair";
2657                 } else
2658                         type = "recover";
2659         }
2660         return sprintf(page, "%s\n", type);
2661 }
2662
2663 static ssize_t
2664 action_store(mddev_t *mddev, const char *page, size_t len)
2665 {
2666         if (!mddev->pers || !mddev->pers->sync_request)
2667                 return -EINVAL;
2668
2669         if (cmd_match(page, "idle")) {
2670                 if (mddev->sync_thread) {
2671                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2672                         md_unregister_thread(mddev->sync_thread);
2673                         mddev->sync_thread = NULL;
2674                         mddev->recovery = 0;
2675                 }
2676         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2677                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
2678                 return -EBUSY;
2679         else if (cmd_match(page, "resync") || cmd_match(page, "recover"))
2680                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2681         else if (cmd_match(page, "reshape")) {
2682                 int err;
2683                 if (mddev->pers->start_reshape == NULL)
2684                         return -EINVAL;
2685                 err = mddev->pers->start_reshape(mddev);
2686                 if (err)
2687                         return err;
2688         } else {
2689                 if (cmd_match(page, "check"))
2690                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
2691                 else if (!cmd_match(page, "repair"))
2692                         return -EINVAL;
2693                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
2694                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
2695         }
2696         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2697         md_wakeup_thread(mddev->thread);
2698         return len;
2699 }
2700
2701 static ssize_t
2702 mismatch_cnt_show(mddev_t *mddev, char *page)
2703 {
2704         return sprintf(page, "%llu\n",
2705                        (unsigned long long) mddev->resync_mismatches);
2706 }
2707
2708 static struct md_sysfs_entry md_scan_mode =
2709 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
2710
2711
2712 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
2713
2714 static ssize_t
2715 sync_min_show(mddev_t *mddev, char *page)
2716 {
2717         return sprintf(page, "%d (%s)\n", speed_min(mddev),
2718                        mddev->sync_speed_min ? "local": "system");
2719 }
2720
2721 static ssize_t
2722 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
2723 {
2724         int min;
2725         char *e;
2726         if (strncmp(buf, "system", 6)==0) {
2727                 mddev->sync_speed_min = 0;
2728                 return len;
2729         }
2730         min = simple_strtoul(buf, &e, 10);
2731         if (buf == e || (*e && *e != '\n') || min <= 0)
2732                 return -EINVAL;
2733         mddev->sync_speed_min = min;
2734         return len;
2735 }
2736
2737 static struct md_sysfs_entry md_sync_min =
2738 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
2739
2740 static ssize_t
2741 sync_max_show(mddev_t *mddev, char *page)
2742 {
2743         return sprintf(page, "%d (%s)\n", speed_max(mddev),
2744                        mddev->sync_speed_max ? "local": "system");
2745 }
2746
2747 static ssize_t
2748 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
2749 {
2750         int max;
2751         char *e;
2752         if (strncmp(buf, "system", 6)==0) {
2753                 mddev->sync_speed_max = 0;
2754                 return len;
2755         }
2756         max = simple_strtoul(buf, &e, 10);
2757         if (buf == e || (*e && *e != '\n') || max <= 0)
2758                 return -EINVAL;
2759         mddev->sync_speed_max = max;
2760         return len;
2761 }
2762
2763 static struct md_sysfs_entry md_sync_max =
2764 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
2765
2766
2767 static ssize_t
2768 sync_speed_show(mddev_t *mddev, char *page)
2769 {
2770         unsigned long resync, dt, db;
2771         resync = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active));
2772         dt = ((jiffies - mddev->resync_mark) / HZ);
2773         if (!dt) dt++;
2774         db = resync - (mddev->resync_mark_cnt);
2775         return sprintf(page, "%ld\n", db/dt/2); /* K/sec */
2776 }
2777
2778 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
2779
2780 static ssize_t
2781 sync_completed_show(mddev_t *mddev, char *page)
2782 {
2783         unsigned long max_blocks, resync;
2784
2785         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2786                 max_blocks = mddev->resync_max_sectors;
2787         else
2788                 max_blocks = mddev->size << 1;
2789
2790         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active));
2791         return sprintf(page, "%lu / %lu\n", resync, max_blocks);
2792 }
2793
2794 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
2795
2796 static ssize_t
2797 suspend_lo_show(mddev_t *mddev, char *page)
2798 {
2799         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
2800 }
2801
2802 static ssize_t
2803 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
2804 {
2805         char *e;
2806         unsigned long long new = simple_strtoull(buf, &e, 10);
2807
2808         if (mddev->pers->quiesce == NULL)
2809                 return -EINVAL;
2810         if (buf == e || (*e && *e != '\n'))
2811                 return -EINVAL;
2812         if (new >= mddev->suspend_hi ||
2813             (new > mddev->suspend_lo && new < mddev->suspend_hi)) {
2814                 mddev->suspend_lo = new;
2815                 mddev->pers->quiesce(mddev, 2);
2816                 return len;
2817         } else
2818                 return -EINVAL;
2819 }
2820 static struct md_sysfs_entry md_suspend_lo =
2821 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
2822
2823
2824 static ssize_t
2825 suspend_hi_show(mddev_t *mddev, char *page)
2826 {
2827         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
2828 }
2829
2830 static ssize_t
2831 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
2832 {
2833         char *e;
2834         unsigned long long new = simple_strtoull(buf, &e, 10);
2835
2836         if (mddev->pers->quiesce == NULL)
2837                 return -EINVAL;
2838         if (buf == e || (*e && *e != '\n'))
2839                 return -EINVAL;
2840         if ((new <= mddev->suspend_lo && mddev->suspend_lo >= mddev->suspend_hi) ||
2841             (new > mddev->suspend_lo && new > mddev->suspend_hi)) {
2842                 mddev->suspend_hi = new;
2843                 mddev->pers->quiesce(mddev, 1);
2844                 mddev->pers->quiesce(mddev, 0);
2845                 return len;
2846         } else
2847                 return -EINVAL;
2848 }
2849 static struct md_sysfs_entry md_suspend_hi =
2850 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
2851
2852
2853 static struct attribute *md_default_attrs[] = {
2854         &md_level.attr,
2855         &md_layout.attr,
2856         &md_raid_disks.attr,
2857         &md_chunk_size.attr,
2858         &md_size.attr,
2859         &md_resync_start.attr,
2860         &md_metadata.attr,
2861         &md_new_device.attr,
2862         &md_safe_delay.attr,
2863         &md_array_state.attr,
2864         NULL,
2865 };
2866
2867 static struct attribute *md_redundancy_attrs[] = {
2868         &md_scan_mode.attr,
2869         &md_mismatches.attr,
2870         &md_sync_min.attr,
2871         &md_sync_max.attr,
2872         &md_sync_speed.attr,
2873         &md_sync_completed.attr,
2874         &md_suspend_lo.attr,
2875         &md_suspend_hi.attr,
2876         &md_bitmap.attr,
2877         NULL,
2878 };
2879 static struct attribute_group md_redundancy_group = {
2880         .name = NULL,
2881         .attrs = md_redundancy_attrs,
2882 };
2883
2884
2885 static ssize_t
2886 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2887 {
2888         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
2889         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
2890         ssize_t rv;
2891
2892         if (!entry->show)
2893                 return -EIO;
2894         rv = mddev_lock(mddev);
2895         if (!rv) {
2896                 rv = entry->show(mddev, page);
2897                 mddev_unlock(mddev);
2898         }
2899         return rv;
2900 }
2901
2902 static ssize_t
2903 md_attr_store(struct kobject *kobj, struct attribute *attr,
2904               const char *page, size_t length)
2905 {
2906         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
2907         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
2908         ssize_t rv;
2909
2910         if (!entry->store)
2911                 return -EIO;
2912         if (!capable(CAP_SYS_ADMIN))
2913                 return -EACCES;
2914         rv = mddev_lock(mddev);
2915         if (!rv) {
2916                 rv = entry->store(mddev, page, length);
2917                 mddev_unlock(mddev);
2918         }
2919         return rv;
2920 }
2921
2922 static void md_free(struct kobject *ko)
2923 {
2924         mddev_t *mddev = container_of(ko, mddev_t, kobj);
2925         kfree(mddev);
2926 }
2927
2928 static struct sysfs_ops md_sysfs_ops = {
2929         .show   = md_attr_show,
2930         .store  = md_attr_store,
2931 };
2932 static struct kobj_type md_ktype = {
2933         .release        = md_free,
2934         .sysfs_ops      = &md_sysfs_ops,
2935         .default_attrs  = md_default_attrs,
2936 };
2937
2938 int mdp_major = 0;
2939
2940 static struct kobject *md_probe(dev_t dev, int *part, void *data)
2941 {
2942         static DEFINE_MUTEX(disks_mutex);
2943         mddev_t *mddev = mddev_find(dev);
2944         struct gendisk *disk;
2945         int partitioned = (MAJOR(dev) != MD_MAJOR);
2946         int shift = partitioned ? MdpMinorShift : 0;
2947         int unit = MINOR(dev) >> shift;
2948
2949         if (!mddev)
2950                 return NULL;
2951
2952         mutex_lock(&disks_mutex);
2953         if (mddev->gendisk) {
2954                 mutex_unlock(&disks_mutex);
2955                 mddev_put(mddev);
2956                 return NULL;
2957         }
2958         disk = alloc_disk(1 << shift);
2959         if (!disk) {
2960                 mutex_unlock(&disks_mutex);
2961                 mddev_put(mddev);
2962                 return NULL;
2963         }
2964         disk->major = MAJOR(dev);
2965         disk->first_minor = unit << shift;
2966         if (partitioned)
2967                 sprintf(disk->disk_name, "md_d%d", unit);
2968         else
2969                 sprintf(disk->disk_name, "md%d", unit);
2970         disk->fops = &md_fops;
2971         disk->private_data = mddev;
2972         disk->queue = mddev->queue;
2973         add_disk(disk);
2974         mddev->gendisk = disk;
2975         mutex_unlock(&disks_mutex);
2976         mddev->kobj.parent = &disk->kobj;
2977         mddev->kobj.k_name = NULL;
2978         snprintf(mddev->kobj.name, KOBJ_NAME_LEN, "%s", "md");
2979         mddev->kobj.ktype = &md_ktype;
2980         kobject_register(&mddev->kobj);
2981         return NULL;
2982 }
2983
2984 static void md_safemode_timeout(unsigned long data)
2985 {
2986         mddev_t *mddev = (mddev_t *) data;
2987
2988         mddev->safemode = 1;
2989         md_wakeup_thread(mddev->thread);
2990 }
2991
2992 static int start_dirty_degraded;
2993
2994 static int do_md_run(mddev_t * mddev)
2995 {
2996         int err;
2997         int chunk_size;
2998         struct list_head *tmp;
2999         mdk_rdev_t *rdev;
3000         struct gendisk *disk;
3001         struct mdk_personality *pers;
3002         char b[BDEVNAME_SIZE];
3003
3004         if (list_empty(&mddev->disks))
3005                 /* cannot run an array with no devices.. */
3006                 return -EINVAL;
3007
3008         if (mddev->pers)
3009                 return -EBUSY;
3010
3011         /*
3012          * Analyze all RAID superblock(s)
3013          */
3014         if (!mddev->raid_disks)
3015                 analyze_sbs(mddev);
3016
3017         chunk_size = mddev->chunk_size;
3018
3019         if (chunk_size) {
3020                 if (chunk_size > MAX_CHUNK_SIZE) {
3021                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
3022                                 chunk_size, MAX_CHUNK_SIZE);
3023                         return -EINVAL;
3024                 }
3025                 /*
3026                  * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
3027                  */
3028                 if ( (1 << ffz(~chunk_size)) != chunk_size) {
3029                         printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
3030                         return -EINVAL;
3031                 }
3032                 if (chunk_size < PAGE_SIZE) {
3033                         printk(KERN_ERR "too small chunk_size: %d < %ld\n",
3034                                 chunk_size, PAGE_SIZE);
3035                         return -EINVAL;
3036                 }
3037
3038                 /* devices must have minimum size of one chunk */
3039                 ITERATE_RDEV(mddev,rdev,tmp) {
3040                         if (test_bit(Faulty, &rdev->flags))
3041                                 continue;
3042                         if (rdev->size < chunk_size / 1024) {
3043                                 printk(KERN_WARNING
3044                                         "md: Dev %s smaller than chunk_size:"
3045                                         " %lluk < %dk\n",
3046                                         bdevname(rdev->bdev,b),
3047                                         (unsigned long long)rdev->size,
3048                                         chunk_size / 1024);
3049                                 return -EINVAL;
3050                         }
3051                 }
3052         }
3053
3054 #ifdef CONFIG_KMOD
3055         if (mddev->level != LEVEL_NONE)
3056                 request_module("md-level-%d", mddev->level);
3057         else if (mddev->clevel[0])
3058                 request_module("md-%s", mddev->clevel);
3059 #endif
3060
3061         /*
3062          * Drop all container device buffers, from now on
3063          * the only valid external interface is through the md
3064          * device.
3065          * Also find largest hardsector size
3066          */
3067         ITERATE_RDEV(mddev,rdev,tmp) {
3068                 if (test_bit(Faulty, &rdev->flags))
3069                         continue;
3070                 sync_blockdev(rdev->bdev);
3071                 invalidate_bdev(rdev->bdev, 0);
3072         }
3073
3074         md_probe(mddev->unit, NULL, NULL);
3075         disk = mddev->gendisk;
3076         if (!disk)
3077                 return -ENOMEM;
3078
3079         spin_lock(&pers_lock);
3080         pers = find_pers(mddev->level, mddev->clevel);
3081         if (!pers || !try_module_get(pers->owner)) {
3082                 spin_unlock(&pers_lock);
3083                 if (mddev->level != LEVEL_NONE)
3084                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
3085                                mddev->level);
3086                 else
3087                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
3088                                mddev->clevel);
3089                 return -EINVAL;
3090         }
3091         mddev->pers = pers;
3092         spin_unlock(&pers_lock);
3093         mddev->level = pers->level;
3094         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3095
3096         if (mddev->reshape_position != MaxSector &&
3097             pers->start_reshape == NULL) {
3098                 /* This personality cannot handle reshaping... */
3099                 mddev->pers = NULL;
3100                 module_put(pers->owner);
3101                 return -EINVAL;
3102         }
3103
3104         mddev->recovery = 0;
3105         mddev->resync_max_sectors = mddev->size << 1; /* may be over-ridden by personality */
3106         mddev->barriers_work = 1;
3107         mddev->ok_start_degraded = start_dirty_degraded;
3108
3109         if (start_readonly)
3110                 mddev->ro = 2; /* read-only, but switch on first write */
3111
3112         err = mddev->pers->run(mddev);
3113         if (!err && mddev->pers->sync_request) {
3114                 err = bitmap_create(mddev);
3115                 if (err) {
3116                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
3117                                mdname(mddev), err);
3118                         mddev->pers->stop(mddev);
3119                 }
3120         }
3121         if (err) {
3122                 printk(KERN_ERR "md: pers->run() failed ...\n");
3123                 module_put(mddev->pers->owner);
3124                 mddev->pers = NULL;
3125                 bitmap_destroy(mddev);
3126                 return err;
3127         }
3128         if (mddev->pers->sync_request)
3129                 sysfs_create_group(&mddev->kobj, &md_redundancy_group);
3130         else if (mddev->ro == 2) /* auto-readonly not meaningful */
3131                 mddev->ro = 0;
3132
3133         atomic_set(&mddev->writes_pending,0);
3134         mddev->safemode = 0;
3135         mddev->safemode_timer.function = md_safemode_timeout;
3136         mddev->safemode_timer.data = (unsigned long) mddev;
3137         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
3138         mddev->in_sync = 1;
3139
3140         ITERATE_RDEV(mddev,rdev,tmp)
3141                 if (rdev->raid_disk >= 0) {
3142                         char nm[20];
3143                         sprintf(nm, "rd%d", rdev->raid_disk);
3144                         sysfs_create_link(&mddev->kobj, &rdev->kobj, nm);
3145                 }
3146         
3147         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3148         
3149         if (mddev->flags)
3150                 md_update_sb(mddev, 0);
3151
3152         set_capacity(disk, mddev->array_size<<1);
3153
3154         /* If we call blk_queue_make_request here, it will
3155          * re-initialise max_sectors etc which may have been
3156          * refined inside -> run.  So just set the bits we need to set.
3157          * Most initialisation happended when we called
3158          * blk_queue_make_request(..., md_fail_request)
3159          * earlier.
3160          */
3161         mddev->queue->queuedata = mddev;
3162         mddev->queue->make_request_fn = mddev->pers->make_request;
3163
3164         /* If there is a partially-recovered drive we need to
3165          * start recovery here.  If we leave it to md_check_recovery,
3166          * it will remove the drives and not do the right thing
3167          */
3168         if (mddev->degraded && !mddev->sync_thread) {
3169                 struct list_head *rtmp;
3170                 int spares = 0;
3171                 ITERATE_RDEV(mddev,rdev,rtmp)
3172                         if (rdev->raid_disk >= 0 &&
3173                             !test_bit(In_sync, &rdev->flags) &&
3174                             !test_bit(Faulty, &rdev->flags))
3175                                 /* complete an interrupted recovery */
3176                                 spares++;
3177                 if (spares && mddev->pers->sync_request) {
3178                         mddev->recovery = 0;
3179                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3180                         mddev->sync_thread = md_register_thread(md_do_sync,
3181                                                                 mddev,
3182                                                                 "%s_resync");
3183                         if (!mddev->sync_thread) {
3184                                 printk(KERN_ERR "%s: could not start resync"
3185                                        " thread...\n",
3186                                        mdname(mddev));
3187                                 /* leave the spares where they are, it shouldn't hurt */
3188                                 mddev->recovery = 0;
3189                         }
3190                 }
3191         }
3192         md_wakeup_thread(mddev->thread);
3193         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
3194
3195         mddev->changed = 1;
3196         md_new_event(mddev);
3197         return 0;
3198 }
3199
3200 static int restart_array(mddev_t *mddev)
3201 {
3202         struct gendisk *disk = mddev->gendisk;
3203         int err;
3204
3205         /*
3206          * Complain if it has no devices
3207          */
3208         err = -ENXIO;
3209         if (list_empty(&mddev->disks))
3210                 goto out;
3211
3212         if (mddev->pers) {
3213                 err = -EBUSY;
3214                 if (!mddev->ro)
3215                         goto out;
3216
3217                 mddev->safemode = 0;
3218                 mddev->ro = 0;
3219                 set_disk_ro(disk, 0);
3220
3221                 printk(KERN_INFO "md: %s switched to read-write mode.\n",
3222                         mdname(mddev));
3223                 /*
3224                  * Kick recovery or resync if necessary
3225                  */
3226                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3227                 md_wakeup_thread(mddev->thread);
3228                 md_wakeup_thread(mddev->sync_thread);
3229                 err = 0;
3230         } else
3231                 err = -EINVAL;
3232
3233 out:
3234         return err;
3235 }
3236
3237 /* similar to deny_write_access, but accounts for our holding a reference
3238  * to the file ourselves */
3239 static int deny_bitmap_write_access(struct file * file)
3240 {
3241         struct inode *inode = file->f_mapping->host;
3242
3243         spin_lock(&inode->i_lock);
3244         if (atomic_read(&inode->i_writecount) > 1) {
3245                 spin_unlock(&inode->i_lock);
3246                 return -ETXTBSY;
3247         }
3248         atomic_set(&inode->i_writecount, -1);
3249         spin_unlock(&inode->i_lock);
3250
3251         return 0;
3252 }
3253
3254 static void restore_bitmap_write_access(struct file *file)
3255 {
3256         struct inode *inode = file->f_mapping->host;
3257
3258         spin_lock(&inode->i_lock);
3259         atomic_set(&inode->i_writecount, 1);
3260         spin_unlock(&inode->i_lock);
3261 }
3262
3263 /* mode:
3264  *   0 - completely stop and dis-assemble array
3265  *   1 - switch to readonly
3266  *   2 - stop but do not disassemble array
3267  */
3268 static int do_md_stop(mddev_t * mddev, int mode)
3269 {
3270         int err = 0;
3271         struct gendisk *disk = mddev->gendisk;
3272
3273         if (mddev->pers) {
3274                 if (atomic_read(&mddev->active)>2) {
3275                         printk("md: %s still in use.\n",mdname(mddev));
3276                         return -EBUSY;
3277                 }
3278
3279                 if (mddev->sync_thread) {
3280                         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3281                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3282                         md_unregister_thread(mddev->sync_thread);
3283                         mddev->sync_thread = NULL;
3284                 }
3285
3286                 del_timer_sync(&mddev->safemode_timer);
3287
3288                 invalidate_partition(disk, 0);
3289
3290                 switch(mode) {
3291                 case 1: /* readonly */
3292                         err  = -ENXIO;
3293                         if (mddev->ro==1)
3294                                 goto out;
3295                         mddev->ro = 1;
3296                         break;
3297                 case 0: /* disassemble */
3298                 case 2: /* stop */
3299                         bitmap_flush(mddev);
3300                         md_super_wait(mddev);
3301                         if (mddev->ro)
3302                                 set_disk_ro(disk, 0);
3303                         blk_queue_make_request(mddev->queue, md_fail_request);
3304                         mddev->pers->stop(mddev);
3305                         if (mddev->pers->sync_request)
3306                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
3307
3308                         module_put(mddev->pers->owner);
3309                         mddev->pers = NULL;
3310                         if (mddev->ro)
3311                                 mddev->ro = 0;
3312                 }
3313                 if (!mddev->in_sync || mddev->flags) {
3314                         /* mark array as shutdown cleanly */
3315                         mddev->in_sync = 1;
3316                         md_update_sb(mddev, 1);
3317                 }
3318                 if (mode == 1)
3319                         set_disk_ro(disk, 1);
3320                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3321         }
3322
3323         /*