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