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