Merge tag 'md/3.14' of git://neil.brown.name/md
[kernel/kernel-generic.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/fs.h>
40 #include <linux/poll.h>
41 #include <linux/ctype.h>
42 #include <linux/string.h>
43 #include <linux/hdreg.h>
44 #include <linux/proc_fs.h>
45 #include <linux/random.h>
46 #include <linux/module.h>
47 #include <linux/reboot.h>
48 #include <linux/file.h>
49 #include <linux/compat.h>
50 #include <linux/delay.h>
51 #include <linux/raid/md_p.h>
52 #include <linux/raid/md_u.h>
53 #include <linux/slab.h>
54 #include "md.h"
55 #include "bitmap.h"
56
57 #ifndef MODULE
58 static void autostart_arrays(int part);
59 #endif
60
61 /* pers_list is a list of registered personalities protected
62  * by pers_lock.
63  * pers_lock does extra service to protect accesses to
64  * mddev->thread when the mutex cannot be held.
65  */
66 static LIST_HEAD(pers_list);
67 static DEFINE_SPINLOCK(pers_lock);
68
69 static void md_print_devices(void);
70
71 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
72 static struct workqueue_struct *md_wq;
73 static struct workqueue_struct *md_misc_wq;
74
75 static int remove_and_add_spares(struct mddev *mddev,
76                                  struct md_rdev *this);
77
78 #define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
79
80 /*
81  * Default number of read corrections we'll attempt on an rdev
82  * before ejecting it from the array. We divide the read error
83  * count by 2 for every hour elapsed between read errors.
84  */
85 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
86 /*
87  * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
88  * is 1000 KB/sec, so the extra system load does not show up that much.
89  * Increase it if you want to have more _guaranteed_ speed. Note that
90  * the RAID driver will use the maximum available bandwidth if the IO
91  * subsystem is idle. There is also an 'absolute maximum' reconstruction
92  * speed limit - in case reconstruction slows down your system despite
93  * idle IO detection.
94  *
95  * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
96  * or /sys/block/mdX/md/sync_speed_{min,max}
97  */
98
99 static int sysctl_speed_limit_min = 1000;
100 static int sysctl_speed_limit_max = 200000;
101 static inline int speed_min(struct mddev *mddev)
102 {
103         return mddev->sync_speed_min ?
104                 mddev->sync_speed_min : sysctl_speed_limit_min;
105 }
106
107 static inline int speed_max(struct mddev *mddev)
108 {
109         return mddev->sync_speed_max ?
110                 mddev->sync_speed_max : sysctl_speed_limit_max;
111 }
112
113 static struct ctl_table_header *raid_table_header;
114
115 static struct ctl_table raid_table[] = {
116         {
117                 .procname       = "speed_limit_min",
118                 .data           = &sysctl_speed_limit_min,
119                 .maxlen         = sizeof(int),
120                 .mode           = S_IRUGO|S_IWUSR,
121                 .proc_handler   = proc_dointvec,
122         },
123         {
124                 .procname       = "speed_limit_max",
125                 .data           = &sysctl_speed_limit_max,
126                 .maxlen         = sizeof(int),
127                 .mode           = S_IRUGO|S_IWUSR,
128                 .proc_handler   = proc_dointvec,
129         },
130         { }
131 };
132
133 static struct ctl_table raid_dir_table[] = {
134         {
135                 .procname       = "raid",
136                 .maxlen         = 0,
137                 .mode           = S_IRUGO|S_IXUGO,
138                 .child          = raid_table,
139         },
140         { }
141 };
142
143 static struct ctl_table raid_root_table[] = {
144         {
145                 .procname       = "dev",
146                 .maxlen         = 0,
147                 .mode           = 0555,
148                 .child          = raid_dir_table,
149         },
150         {  }
151 };
152
153 static const struct block_device_operations md_fops;
154
155 static int start_readonly;
156
157 /* bio_clone_mddev
158  * like bio_clone, but with a local bio set
159  */
160
161 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
162                             struct mddev *mddev)
163 {
164         struct bio *b;
165
166         if (!mddev || !mddev->bio_set)
167                 return bio_alloc(gfp_mask, nr_iovecs);
168
169         b = bio_alloc_bioset(gfp_mask, nr_iovecs, mddev->bio_set);
170         if (!b)
171                 return NULL;
172         return b;
173 }
174 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
175
176 struct bio *bio_clone_mddev(struct bio *bio, gfp_t gfp_mask,
177                             struct mddev *mddev)
178 {
179         if (!mddev || !mddev->bio_set)
180                 return bio_clone(bio, gfp_mask);
181
182         return bio_clone_bioset(bio, gfp_mask, mddev->bio_set);
183 }
184 EXPORT_SYMBOL_GPL(bio_clone_mddev);
185
186 /*
187  * We have a system wide 'event count' that is incremented
188  * on any 'interesting' event, and readers of /proc/mdstat
189  * can use 'poll' or 'select' to find out when the event
190  * count increases.
191  *
192  * Events are:
193  *  start array, stop array, error, add device, remove device,
194  *  start build, activate spare
195  */
196 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
197 static atomic_t md_event_count;
198 void md_new_event(struct mddev *mddev)
199 {
200         atomic_inc(&md_event_count);
201         wake_up(&md_event_waiters);
202 }
203 EXPORT_SYMBOL_GPL(md_new_event);
204
205 /* Alternate version that can be called from interrupts
206  * when calling sysfs_notify isn't needed.
207  */
208 static void md_new_event_inintr(struct mddev *mddev)
209 {
210         atomic_inc(&md_event_count);
211         wake_up(&md_event_waiters);
212 }
213
214 /*
215  * Enables to iterate over all existing md arrays
216  * all_mddevs_lock protects this list.
217  */
218 static LIST_HEAD(all_mddevs);
219 static DEFINE_SPINLOCK(all_mddevs_lock);
220
221
222 /*
223  * iterates through all used mddevs in the system.
224  * We take care to grab the all_mddevs_lock whenever navigating
225  * the list, and to always hold a refcount when unlocked.
226  * Any code which breaks out of this loop while own
227  * a reference to the current mddev and must mddev_put it.
228  */
229 #define for_each_mddev(_mddev,_tmp)                                     \
230                                                                         \
231         for (({ spin_lock(&all_mddevs_lock);                            \
232                 _tmp = all_mddevs.next;                                 \
233                 _mddev = NULL;});                                       \
234              ({ if (_tmp != &all_mddevs)                                \
235                         mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
236                 spin_unlock(&all_mddevs_lock);                          \
237                 if (_mddev) mddev_put(_mddev);                          \
238                 _mddev = list_entry(_tmp, struct mddev, all_mddevs);    \
239                 _tmp != &all_mddevs;});                                 \
240              ({ spin_lock(&all_mddevs_lock);                            \
241                 _tmp = _tmp->next;})                                    \
242                 )
243
244
245 /* Rather than calling directly into the personality make_request function,
246  * IO requests come here first so that we can check if the device is
247  * being suspended pending a reconfiguration.
248  * We hold a refcount over the call to ->make_request.  By the time that
249  * call has finished, the bio has been linked into some internal structure
250  * and so is visible to ->quiesce(), so we don't need the refcount any more.
251  */
252 static void md_make_request(struct request_queue *q, struct bio *bio)
253 {
254         const int rw = bio_data_dir(bio);
255         struct mddev *mddev = q->queuedata;
256         int cpu;
257         unsigned int sectors;
258
259         if (mddev == NULL || mddev->pers == NULL
260             || !mddev->ready) {
261                 bio_io_error(bio);
262                 return;
263         }
264         if (mddev->ro == 1 && unlikely(rw == WRITE)) {
265                 bio_endio(bio, bio_sectors(bio) == 0 ? 0 : -EROFS);
266                 return;
267         }
268         smp_rmb(); /* Ensure implications of  'active' are visible */
269         rcu_read_lock();
270         if (mddev->suspended) {
271                 DEFINE_WAIT(__wait);
272                 for (;;) {
273                         prepare_to_wait(&mddev->sb_wait, &__wait,
274                                         TASK_UNINTERRUPTIBLE);
275                         if (!mddev->suspended)
276                                 break;
277                         rcu_read_unlock();
278                         schedule();
279                         rcu_read_lock();
280                 }
281                 finish_wait(&mddev->sb_wait, &__wait);
282         }
283         atomic_inc(&mddev->active_io);
284         rcu_read_unlock();
285
286         /*
287          * save the sectors now since our bio can
288          * go away inside make_request
289          */
290         sectors = bio_sectors(bio);
291         mddev->pers->make_request(mddev, bio);
292
293         cpu = part_stat_lock();
294         part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
295         part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
296         part_stat_unlock();
297
298         if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
299                 wake_up(&mddev->sb_wait);
300 }
301
302 /* mddev_suspend makes sure no new requests are submitted
303  * to the device, and that any requests that have been submitted
304  * are completely handled.
305  * Once ->stop is called and completes, the module will be completely
306  * unused.
307  */
308 void mddev_suspend(struct mddev *mddev)
309 {
310         BUG_ON(mddev->suspended);
311         mddev->suspended = 1;
312         synchronize_rcu();
313         wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
314         mddev->pers->quiesce(mddev, 1);
315
316         del_timer_sync(&mddev->safemode_timer);
317 }
318 EXPORT_SYMBOL_GPL(mddev_suspend);
319
320 void mddev_resume(struct mddev *mddev)
321 {
322         mddev->suspended = 0;
323         wake_up(&mddev->sb_wait);
324         mddev->pers->quiesce(mddev, 0);
325
326         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
327         md_wakeup_thread(mddev->thread);
328         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
329 }
330 EXPORT_SYMBOL_GPL(mddev_resume);
331
332 int mddev_congested(struct mddev *mddev, int bits)
333 {
334         return mddev->suspended;
335 }
336 EXPORT_SYMBOL(mddev_congested);
337
338 /*
339  * Generic flush handling for md
340  */
341
342 static void md_end_flush(struct bio *bio, int err)
343 {
344         struct md_rdev *rdev = bio->bi_private;
345         struct mddev *mddev = rdev->mddev;
346
347         rdev_dec_pending(rdev, mddev);
348
349         if (atomic_dec_and_test(&mddev->flush_pending)) {
350                 /* The pre-request flush has finished */
351                 queue_work(md_wq, &mddev->flush_work);
352         }
353         bio_put(bio);
354 }
355
356 static void md_submit_flush_data(struct work_struct *ws);
357
358 static void submit_flushes(struct work_struct *ws)
359 {
360         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
361         struct md_rdev *rdev;
362
363         INIT_WORK(&mddev->flush_work, md_submit_flush_data);
364         atomic_set(&mddev->flush_pending, 1);
365         rcu_read_lock();
366         rdev_for_each_rcu(rdev, mddev)
367                 if (rdev->raid_disk >= 0 &&
368                     !test_bit(Faulty, &rdev->flags)) {
369                         /* Take two references, one is dropped
370                          * when request finishes, one after
371                          * we reclaim rcu_read_lock
372                          */
373                         struct bio *bi;
374                         atomic_inc(&rdev->nr_pending);
375                         atomic_inc(&rdev->nr_pending);
376                         rcu_read_unlock();
377                         bi = bio_alloc_mddev(GFP_NOIO, 0, mddev);
378                         bi->bi_end_io = md_end_flush;
379                         bi->bi_private = rdev;
380                         bi->bi_bdev = rdev->bdev;
381                         atomic_inc(&mddev->flush_pending);
382                         submit_bio(WRITE_FLUSH, bi);
383                         rcu_read_lock();
384                         rdev_dec_pending(rdev, mddev);
385                 }
386         rcu_read_unlock();
387         if (atomic_dec_and_test(&mddev->flush_pending))
388                 queue_work(md_wq, &mddev->flush_work);
389 }
390
391 static void md_submit_flush_data(struct work_struct *ws)
392 {
393         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
394         struct bio *bio = mddev->flush_bio;
395
396         if (bio->bi_size == 0)
397                 /* an empty barrier - all done */
398                 bio_endio(bio, 0);
399         else {
400                 bio->bi_rw &= ~REQ_FLUSH;
401                 mddev->pers->make_request(mddev, bio);
402         }
403
404         mddev->flush_bio = NULL;
405         wake_up(&mddev->sb_wait);
406 }
407
408 void md_flush_request(struct mddev *mddev, struct bio *bio)
409 {
410         spin_lock_irq(&mddev->write_lock);
411         wait_event_lock_irq(mddev->sb_wait,
412                             !mddev->flush_bio,
413                             mddev->write_lock);
414         mddev->flush_bio = bio;
415         spin_unlock_irq(&mddev->write_lock);
416
417         INIT_WORK(&mddev->flush_work, submit_flushes);
418         queue_work(md_wq, &mddev->flush_work);
419 }
420 EXPORT_SYMBOL(md_flush_request);
421
422 void md_unplug(struct blk_plug_cb *cb, bool from_schedule)
423 {
424         struct mddev *mddev = cb->data;
425         md_wakeup_thread(mddev->thread);
426         kfree(cb);
427 }
428 EXPORT_SYMBOL(md_unplug);
429
430 static inline struct mddev *mddev_get(struct mddev *mddev)
431 {
432         atomic_inc(&mddev->active);
433         return mddev;
434 }
435
436 static void mddev_delayed_delete(struct work_struct *ws);
437
438 static void mddev_put(struct mddev *mddev)
439 {
440         struct bio_set *bs = NULL;
441
442         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
443                 return;
444         if (!mddev->raid_disks && list_empty(&mddev->disks) &&
445             mddev->ctime == 0 && !mddev->hold_active) {
446                 /* Array is not configured at all, and not held active,
447                  * so destroy it */
448                 list_del_init(&mddev->all_mddevs);
449                 bs = mddev->bio_set;
450                 mddev->bio_set = NULL;
451                 if (mddev->gendisk) {
452                         /* We did a probe so need to clean up.  Call
453                          * queue_work inside the spinlock so that
454                          * flush_workqueue() after mddev_find will
455                          * succeed in waiting for the work to be done.
456                          */
457                         INIT_WORK(&mddev->del_work, mddev_delayed_delete);
458                         queue_work(md_misc_wq, &mddev->del_work);
459                 } else
460                         kfree(mddev);
461         }
462         spin_unlock(&all_mddevs_lock);
463         if (bs)
464                 bioset_free(bs);
465 }
466
467 void mddev_init(struct mddev *mddev)
468 {
469         mutex_init(&mddev->open_mutex);
470         mutex_init(&mddev->reconfig_mutex);
471         mutex_init(&mddev->bitmap_info.mutex);
472         INIT_LIST_HEAD(&mddev->disks);
473         INIT_LIST_HEAD(&mddev->all_mddevs);
474         init_timer(&mddev->safemode_timer);
475         atomic_set(&mddev->active, 1);
476         atomic_set(&mddev->openers, 0);
477         atomic_set(&mddev->active_io, 0);
478         spin_lock_init(&mddev->write_lock);
479         atomic_set(&mddev->flush_pending, 0);
480         init_waitqueue_head(&mddev->sb_wait);
481         init_waitqueue_head(&mddev->recovery_wait);
482         mddev->reshape_position = MaxSector;
483         mddev->reshape_backwards = 0;
484         mddev->last_sync_action = "none";
485         mddev->resync_min = 0;
486         mddev->resync_max = MaxSector;
487         mddev->level = LEVEL_NONE;
488 }
489 EXPORT_SYMBOL_GPL(mddev_init);
490
491 static struct mddev * mddev_find(dev_t unit)
492 {
493         struct mddev *mddev, *new = NULL;
494
495         if (unit && MAJOR(unit) != MD_MAJOR)
496                 unit &= ~((1<<MdpMinorShift)-1);
497
498  retry:
499         spin_lock(&all_mddevs_lock);
500
501         if (unit) {
502                 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
503                         if (mddev->unit == unit) {
504                                 mddev_get(mddev);
505                                 spin_unlock(&all_mddevs_lock);
506                                 kfree(new);
507                                 return mddev;
508                         }
509
510                 if (new) {
511                         list_add(&new->all_mddevs, &all_mddevs);
512                         spin_unlock(&all_mddevs_lock);
513                         new->hold_active = UNTIL_IOCTL;
514                         return new;
515                 }
516         } else if (new) {
517                 /* find an unused unit number */
518                 static int next_minor = 512;
519                 int start = next_minor;
520                 int is_free = 0;
521                 int dev = 0;
522                 while (!is_free) {
523                         dev = MKDEV(MD_MAJOR, next_minor);
524                         next_minor++;
525                         if (next_minor > MINORMASK)
526                                 next_minor = 0;
527                         if (next_minor == start) {
528                                 /* Oh dear, all in use. */
529                                 spin_unlock(&all_mddevs_lock);
530                                 kfree(new);
531                                 return NULL;
532                         }
533                                 
534                         is_free = 1;
535                         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
536                                 if (mddev->unit == dev) {
537                                         is_free = 0;
538                                         break;
539                                 }
540                 }
541                 new->unit = dev;
542                 new->md_minor = MINOR(dev);
543                 new->hold_active = UNTIL_STOP;
544                 list_add(&new->all_mddevs, &all_mddevs);
545                 spin_unlock(&all_mddevs_lock);
546                 return new;
547         }
548         spin_unlock(&all_mddevs_lock);
549
550         new = kzalloc(sizeof(*new), GFP_KERNEL);
551         if (!new)
552                 return NULL;
553
554         new->unit = unit;
555         if (MAJOR(unit) == MD_MAJOR)
556                 new->md_minor = MINOR(unit);
557         else
558                 new->md_minor = MINOR(unit) >> MdpMinorShift;
559
560         mddev_init(new);
561
562         goto retry;
563 }
564
565 static inline int __must_check mddev_lock(struct mddev * mddev)
566 {
567         return mutex_lock_interruptible(&mddev->reconfig_mutex);
568 }
569
570 /* Sometimes we need to take the lock in a situation where
571  * failure due to interrupts is not acceptable.
572  */
573 static inline void mddev_lock_nointr(struct mddev * mddev)
574 {
575         mutex_lock(&mddev->reconfig_mutex);
576 }
577
578 static inline int mddev_is_locked(struct mddev *mddev)
579 {
580         return mutex_is_locked(&mddev->reconfig_mutex);
581 }
582
583 static inline int mddev_trylock(struct mddev * mddev)
584 {
585         return mutex_trylock(&mddev->reconfig_mutex);
586 }
587
588 static struct attribute_group md_redundancy_group;
589
590 static void mddev_unlock(struct mddev * mddev)
591 {
592         if (mddev->to_remove) {
593                 /* These cannot be removed under reconfig_mutex as
594                  * an access to the files will try to take reconfig_mutex
595                  * while holding the file unremovable, which leads to
596                  * a deadlock.
597                  * So hold set sysfs_active while the remove in happeing,
598                  * and anything else which might set ->to_remove or my
599                  * otherwise change the sysfs namespace will fail with
600                  * -EBUSY if sysfs_active is still set.
601                  * We set sysfs_active under reconfig_mutex and elsewhere
602                  * test it under the same mutex to ensure its correct value
603                  * is seen.
604                  */
605                 struct attribute_group *to_remove = mddev->to_remove;
606                 mddev->to_remove = NULL;
607                 mddev->sysfs_active = 1;
608                 mutex_unlock(&mddev->reconfig_mutex);
609
610                 if (mddev->kobj.sd) {
611                         if (to_remove != &md_redundancy_group)
612                                 sysfs_remove_group(&mddev->kobj, to_remove);
613                         if (mddev->pers == NULL ||
614                             mddev->pers->sync_request == NULL) {
615                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
616                                 if (mddev->sysfs_action)
617                                         sysfs_put(mddev->sysfs_action);
618                                 mddev->sysfs_action = NULL;
619                         }
620                 }
621                 mddev->sysfs_active = 0;
622         } else
623                 mutex_unlock(&mddev->reconfig_mutex);
624
625         /* As we've dropped the mutex we need a spinlock to
626          * make sure the thread doesn't disappear
627          */
628         spin_lock(&pers_lock);
629         md_wakeup_thread(mddev->thread);
630         spin_unlock(&pers_lock);
631 }
632
633 static struct md_rdev * find_rdev_nr(struct mddev *mddev, int nr)
634 {
635         struct md_rdev *rdev;
636
637         rdev_for_each(rdev, mddev)
638                 if (rdev->desc_nr == nr)
639                         return rdev;
640
641         return NULL;
642 }
643
644 static struct md_rdev *find_rdev_nr_rcu(struct mddev *mddev, int nr)
645 {
646         struct md_rdev *rdev;
647
648         rdev_for_each_rcu(rdev, mddev)
649                 if (rdev->desc_nr == nr)
650                         return rdev;
651
652         return NULL;
653 }
654
655 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
656 {
657         struct md_rdev *rdev;
658
659         rdev_for_each(rdev, mddev)
660                 if (rdev->bdev->bd_dev == dev)
661                         return rdev;
662
663         return NULL;
664 }
665
666 static struct md_rdev *find_rdev_rcu(struct mddev *mddev, dev_t dev)
667 {
668         struct md_rdev *rdev;
669
670         rdev_for_each_rcu(rdev, mddev)
671                 if (rdev->bdev->bd_dev == dev)
672                         return rdev;
673
674         return NULL;
675 }
676
677 static struct md_personality *find_pers(int level, char *clevel)
678 {
679         struct md_personality *pers;
680         list_for_each_entry(pers, &pers_list, list) {
681                 if (level != LEVEL_NONE && pers->level == level)
682                         return pers;
683                 if (strcmp(pers->name, clevel)==0)
684                         return pers;
685         }
686         return NULL;
687 }
688
689 /* return the offset of the super block in 512byte sectors */
690 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
691 {
692         sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
693         return MD_NEW_SIZE_SECTORS(num_sectors);
694 }
695
696 static int alloc_disk_sb(struct md_rdev * rdev)
697 {
698         if (rdev->sb_page)
699                 MD_BUG();
700
701         rdev->sb_page = alloc_page(GFP_KERNEL);
702         if (!rdev->sb_page) {
703                 printk(KERN_ALERT "md: out of memory.\n");
704                 return -ENOMEM;
705         }
706
707         return 0;
708 }
709
710 void md_rdev_clear(struct md_rdev *rdev)
711 {
712         if (rdev->sb_page) {
713                 put_page(rdev->sb_page);
714                 rdev->sb_loaded = 0;
715                 rdev->sb_page = NULL;
716                 rdev->sb_start = 0;
717                 rdev->sectors = 0;
718         }
719         if (rdev->bb_page) {
720                 put_page(rdev->bb_page);
721                 rdev->bb_page = NULL;
722         }
723         kfree(rdev->badblocks.page);
724         rdev->badblocks.page = NULL;
725 }
726 EXPORT_SYMBOL_GPL(md_rdev_clear);
727
728 static void super_written(struct bio *bio, int error)
729 {
730         struct md_rdev *rdev = bio->bi_private;
731         struct mddev *mddev = rdev->mddev;
732
733         if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
734                 printk("md: super_written gets error=%d, uptodate=%d\n",
735                        error, test_bit(BIO_UPTODATE, &bio->bi_flags));
736                 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
737                 md_error(mddev, rdev);
738         }
739
740         if (atomic_dec_and_test(&mddev->pending_writes))
741                 wake_up(&mddev->sb_wait);
742         bio_put(bio);
743 }
744
745 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
746                    sector_t sector, int size, struct page *page)
747 {
748         /* write first size bytes of page to sector of rdev
749          * Increment mddev->pending_writes before returning
750          * and decrement it on completion, waking up sb_wait
751          * if zero is reached.
752          * If an error occurred, call md_error
753          */
754         struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, mddev);
755
756         bio->bi_bdev = rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev;
757         bio->bi_sector = sector;
758         bio_add_page(bio, page, size, 0);
759         bio->bi_private = rdev;
760         bio->bi_end_io = super_written;
761
762         atomic_inc(&mddev->pending_writes);
763         submit_bio(WRITE_FLUSH_FUA, bio);
764 }
765
766 void md_super_wait(struct mddev *mddev)
767 {
768         /* wait for all superblock writes that were scheduled to complete */
769         DEFINE_WAIT(wq);
770         for(;;) {
771                 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
772                 if (atomic_read(&mddev->pending_writes)==0)
773                         break;
774                 schedule();
775         }
776         finish_wait(&mddev->sb_wait, &wq);
777 }
778
779 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
780                  struct page *page, int rw, bool metadata_op)
781 {
782         struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, rdev->mddev);
783         int ret;
784
785         rw |= REQ_SYNC;
786
787         bio->bi_bdev = (metadata_op && rdev->meta_bdev) ?
788                 rdev->meta_bdev : rdev->bdev;
789         if (metadata_op)
790                 bio->bi_sector = sector + rdev->sb_start;
791         else if (rdev->mddev->reshape_position != MaxSector &&
792                  (rdev->mddev->reshape_backwards ==
793                   (sector >= rdev->mddev->reshape_position)))
794                 bio->bi_sector = sector + rdev->new_data_offset;
795         else
796                 bio->bi_sector = sector + rdev->data_offset;
797         bio_add_page(bio, page, size, 0);
798         submit_bio_wait(rw, bio);
799
800         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
801         bio_put(bio);
802         return ret;
803 }
804 EXPORT_SYMBOL_GPL(sync_page_io);
805
806 static int read_disk_sb(struct md_rdev * rdev, int size)
807 {
808         char b[BDEVNAME_SIZE];
809         if (!rdev->sb_page) {
810                 MD_BUG();
811                 return -EINVAL;
812         }
813         if (rdev->sb_loaded)
814                 return 0;
815
816
817         if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, true))
818                 goto fail;
819         rdev->sb_loaded = 1;
820         return 0;
821
822 fail:
823         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
824                 bdevname(rdev->bdev,b));
825         return -EINVAL;
826 }
827
828 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
829 {
830         return  sb1->set_uuid0 == sb2->set_uuid0 &&
831                 sb1->set_uuid1 == sb2->set_uuid1 &&
832                 sb1->set_uuid2 == sb2->set_uuid2 &&
833                 sb1->set_uuid3 == sb2->set_uuid3;
834 }
835
836 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
837 {
838         int ret;
839         mdp_super_t *tmp1, *tmp2;
840
841         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
842         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
843
844         if (!tmp1 || !tmp2) {
845                 ret = 0;
846                 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
847                 goto abort;
848         }
849
850         *tmp1 = *sb1;
851         *tmp2 = *sb2;
852
853         /*
854          * nr_disks is not constant
855          */
856         tmp1->nr_disks = 0;
857         tmp2->nr_disks = 0;
858
859         ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
860 abort:
861         kfree(tmp1);
862         kfree(tmp2);
863         return ret;
864 }
865
866
867 static u32 md_csum_fold(u32 csum)
868 {
869         csum = (csum & 0xffff) + (csum >> 16);
870         return (csum & 0xffff) + (csum >> 16);
871 }
872
873 static unsigned int calc_sb_csum(mdp_super_t * sb)
874 {
875         u64 newcsum = 0;
876         u32 *sb32 = (u32*)sb;
877         int i;
878         unsigned int disk_csum, csum;
879
880         disk_csum = sb->sb_csum;
881         sb->sb_csum = 0;
882
883         for (i = 0; i < MD_SB_BYTES/4 ; i++)
884                 newcsum += sb32[i];
885         csum = (newcsum & 0xffffffff) + (newcsum>>32);
886
887
888 #ifdef CONFIG_ALPHA
889         /* This used to use csum_partial, which was wrong for several
890          * reasons including that different results are returned on
891          * different architectures.  It isn't critical that we get exactly
892          * the same return value as before (we always csum_fold before
893          * testing, and that removes any differences).  However as we
894          * know that csum_partial always returned a 16bit value on
895          * alphas, do a fold to maximise conformity to previous behaviour.
896          */
897         sb->sb_csum = md_csum_fold(disk_csum);
898 #else
899         sb->sb_csum = disk_csum;
900 #endif
901         return csum;
902 }
903
904
905 /*
906  * Handle superblock details.
907  * We want to be able to handle multiple superblock formats
908  * so we have a common interface to them all, and an array of
909  * different handlers.
910  * We rely on user-space to write the initial superblock, and support
911  * reading and updating of superblocks.
912  * Interface methods are:
913  *   int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
914  *      loads and validates a superblock on dev.
915  *      if refdev != NULL, compare superblocks on both devices
916  *    Return:
917  *      0 - dev has a superblock that is compatible with refdev
918  *      1 - dev has a superblock that is compatible and newer than refdev
919  *          so dev should be used as the refdev in future
920  *     -EINVAL superblock incompatible or invalid
921  *     -othererror e.g. -EIO
922  *
923  *   int validate_super(struct mddev *mddev, struct md_rdev *dev)
924  *      Verify that dev is acceptable into mddev.
925  *       The first time, mddev->raid_disks will be 0, and data from
926  *       dev should be merged in.  Subsequent calls check that dev
927  *       is new enough.  Return 0 or -EINVAL
928  *
929  *   void sync_super(struct mddev *mddev, struct md_rdev *dev)
930  *     Update the superblock for rdev with data in mddev
931  *     This does not write to disc.
932  *
933  */
934
935 struct super_type  {
936         char                *name;
937         struct module       *owner;
938         int                 (*load_super)(struct md_rdev *rdev,
939                                           struct md_rdev *refdev,
940                                           int minor_version);
941         int                 (*validate_super)(struct mddev *mddev,
942                                               struct md_rdev *rdev);
943         void                (*sync_super)(struct mddev *mddev,
944                                           struct md_rdev *rdev);
945         unsigned long long  (*rdev_size_change)(struct md_rdev *rdev,
946                                                 sector_t num_sectors);
947         int                 (*allow_new_offset)(struct md_rdev *rdev,
948                                                 unsigned long long new_offset);
949 };
950
951 /*
952  * Check that the given mddev has no bitmap.
953  *
954  * This function is called from the run method of all personalities that do not
955  * support bitmaps. It prints an error message and returns non-zero if mddev
956  * has a bitmap. Otherwise, it returns 0.
957  *
958  */
959 int md_check_no_bitmap(struct mddev *mddev)
960 {
961         if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
962                 return 0;
963         printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
964                 mdname(mddev), mddev->pers->name);
965         return 1;
966 }
967 EXPORT_SYMBOL(md_check_no_bitmap);
968
969 /*
970  * load_super for 0.90.0 
971  */
972 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
973 {
974         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
975         mdp_super_t *sb;
976         int ret;
977
978         /*
979          * Calculate the position of the superblock (512byte sectors),
980          * it's at the end of the disk.
981          *
982          * It also happens to be a multiple of 4Kb.
983          */
984         rdev->sb_start = calc_dev_sboffset(rdev);
985
986         ret = read_disk_sb(rdev, MD_SB_BYTES);
987         if (ret) return ret;
988
989         ret = -EINVAL;
990
991         bdevname(rdev->bdev, b);
992         sb = page_address(rdev->sb_page);
993
994         if (sb->md_magic != MD_SB_MAGIC) {
995                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
996                        b);
997                 goto abort;
998         }
999
1000         if (sb->major_version != 0 ||
1001             sb->minor_version < 90 ||
1002             sb->minor_version > 91) {
1003                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
1004                         sb->major_version, sb->minor_version,
1005                         b);
1006                 goto abort;
1007         }
1008
1009         if (sb->raid_disks <= 0)
1010                 goto abort;
1011
1012         if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1013                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
1014                         b);
1015                 goto abort;
1016         }
1017
1018         rdev->preferred_minor = sb->md_minor;
1019         rdev->data_offset = 0;
1020         rdev->new_data_offset = 0;
1021         rdev->sb_size = MD_SB_BYTES;
1022         rdev->badblocks.shift = -1;
1023
1024         if (sb->level == LEVEL_MULTIPATH)
1025                 rdev->desc_nr = -1;
1026         else
1027                 rdev->desc_nr = sb->this_disk.number;
1028
1029         if (!refdev) {
1030                 ret = 1;
1031         } else {
1032                 __u64 ev1, ev2;
1033                 mdp_super_t *refsb = page_address(refdev->sb_page);
1034                 if (!uuid_equal(refsb, sb)) {
1035                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
1036                                 b, bdevname(refdev->bdev,b2));
1037                         goto abort;
1038                 }
1039                 if (!sb_equal(refsb, sb)) {
1040                         printk(KERN_WARNING "md: %s has same UUID"
1041                                " but different superblock to %s\n",
1042                                b, bdevname(refdev->bdev, b2));
1043                         goto abort;
1044                 }
1045                 ev1 = md_event(sb);
1046                 ev2 = md_event(refsb);
1047                 if (ev1 > ev2)
1048                         ret = 1;
1049                 else 
1050                         ret = 0;
1051         }
1052         rdev->sectors = rdev->sb_start;
1053         /* Limit to 4TB as metadata cannot record more than that.
1054          * (not needed for Linear and RAID0 as metadata doesn't
1055          * record this size)
1056          */
1057         if (rdev->sectors >= (2ULL << 32) && sb->level >= 1)
1058                 rdev->sectors = (2ULL << 32) - 2;
1059
1060         if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1061                 /* "this cannot possibly happen" ... */
1062                 ret = -EINVAL;
1063
1064  abort:
1065         return ret;
1066 }
1067
1068 /*
1069  * validate_super for 0.90.0
1070  */
1071 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1072 {
1073         mdp_disk_t *desc;
1074         mdp_super_t *sb = page_address(rdev->sb_page);
1075         __u64 ev1 = md_event(sb);
1076
1077         rdev->raid_disk = -1;
1078         clear_bit(Faulty, &rdev->flags);
1079         clear_bit(In_sync, &rdev->flags);
1080         clear_bit(Bitmap_sync, &rdev->flags);
1081         clear_bit(WriteMostly, &rdev->flags);
1082
1083         if (mddev->raid_disks == 0) {
1084                 mddev->major_version = 0;
1085                 mddev->minor_version = sb->minor_version;
1086                 mddev->patch_version = sb->patch_version;
1087                 mddev->external = 0;
1088                 mddev->chunk_sectors = sb->chunk_size >> 9;
1089                 mddev->ctime = sb->ctime;
1090                 mddev->utime = sb->utime;
1091                 mddev->level = sb->level;
1092                 mddev->clevel[0] = 0;
1093                 mddev->layout = sb->layout;
1094                 mddev->raid_disks = sb->raid_disks;
1095                 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1096                 mddev->events = ev1;
1097                 mddev->bitmap_info.offset = 0;
1098                 mddev->bitmap_info.space = 0;
1099                 /* bitmap can use 60 K after the 4K superblocks */
1100                 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1101                 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1102                 mddev->reshape_backwards = 0;
1103
1104                 if (mddev->minor_version >= 91) {
1105                         mddev->reshape_position = sb->reshape_position;
1106                         mddev->delta_disks = sb->delta_disks;
1107                         mddev->new_level = sb->new_level;
1108                         mddev->new_layout = sb->new_layout;
1109                         mddev->new_chunk_sectors = sb->new_chunk >> 9;
1110                         if (mddev->delta_disks < 0)
1111                                 mddev->reshape_backwards = 1;
1112                 } else {
1113                         mddev->reshape_position = MaxSector;
1114                         mddev->delta_disks = 0;
1115                         mddev->new_level = mddev->level;
1116                         mddev->new_layout = mddev->layout;
1117                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1118                 }
1119
1120                 if (sb->state & (1<<MD_SB_CLEAN))
1121                         mddev->recovery_cp = MaxSector;
1122                 else {
1123                         if (sb->events_hi == sb->cp_events_hi && 
1124                                 sb->events_lo == sb->cp_events_lo) {
1125                                 mddev->recovery_cp = sb->recovery_cp;
1126                         } else
1127                                 mddev->recovery_cp = 0;
1128                 }
1129
1130                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1131                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1132                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1133                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1134
1135                 mddev->max_disks = MD_SB_DISKS;
1136
1137                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1138                     mddev->bitmap_info.file == NULL) {
1139                         mddev->bitmap_info.offset =
1140                                 mddev->bitmap_info.default_offset;
1141                         mddev->bitmap_info.space =
1142                                 mddev->bitmap_info.default_space;
1143                 }
1144
1145         } else if (mddev->pers == NULL) {
1146                 /* Insist on good event counter while assembling, except
1147                  * for spares (which don't need an event count) */
1148                 ++ev1;
1149                 if (sb->disks[rdev->desc_nr].state & (
1150                             (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1151                         if (ev1 < mddev->events) 
1152                                 return -EINVAL;
1153         } else if (mddev->bitmap) {
1154                 /* if adding to array with a bitmap, then we can accept an
1155                  * older device ... but not too old.
1156                  */
1157                 if (ev1 < mddev->bitmap->events_cleared)
1158                         return 0;
1159                 if (ev1 < mddev->events)
1160                         set_bit(Bitmap_sync, &rdev->flags);
1161         } else {
1162                 if (ev1 < mddev->events)
1163                         /* just a hot-add of a new device, leave raid_disk at -1 */
1164                         return 0;
1165         }
1166
1167         if (mddev->level != LEVEL_MULTIPATH) {
1168                 desc = sb->disks + rdev->desc_nr;
1169
1170                 if (desc->state & (1<<MD_DISK_FAULTY))
1171                         set_bit(Faulty, &rdev->flags);
1172                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1173                             desc->raid_disk < mddev->raid_disks */) {
1174                         set_bit(In_sync, &rdev->flags);
1175                         rdev->raid_disk = desc->raid_disk;
1176                         rdev->saved_raid_disk = desc->raid_disk;
1177                 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1178                         /* active but not in sync implies recovery up to
1179                          * reshape position.  We don't know exactly where
1180                          * that is, so set to zero for now */
1181                         if (mddev->minor_version >= 91) {
1182                                 rdev->recovery_offset = 0;
1183                                 rdev->raid_disk = desc->raid_disk;
1184                         }
1185                 }
1186                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1187                         set_bit(WriteMostly, &rdev->flags);
1188         } else /* MULTIPATH are always insync */
1189                 set_bit(In_sync, &rdev->flags);
1190         return 0;
1191 }
1192
1193 /*
1194  * sync_super for 0.90.0
1195  */
1196 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1197 {
1198         mdp_super_t *sb;
1199         struct md_rdev *rdev2;
1200         int next_spare = mddev->raid_disks;
1201
1202
1203         /* make rdev->sb match mddev data..
1204          *
1205          * 1/ zero out disks
1206          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1207          * 3/ any empty disks < next_spare become removed
1208          *
1209          * disks[0] gets initialised to REMOVED because
1210          * we cannot be sure from other fields if it has
1211          * been initialised or not.
1212          */
1213         int i;
1214         int active=0, working=0,failed=0,spare=0,nr_disks=0;
1215
1216         rdev->sb_size = MD_SB_BYTES;
1217
1218         sb = page_address(rdev->sb_page);
1219
1220         memset(sb, 0, sizeof(*sb));
1221
1222         sb->md_magic = MD_SB_MAGIC;
1223         sb->major_version = mddev->major_version;
1224         sb->patch_version = mddev->patch_version;
1225         sb->gvalid_words  = 0; /* ignored */
1226         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1227         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1228         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1229         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1230
1231         sb->ctime = mddev->ctime;
1232         sb->level = mddev->level;
1233         sb->size = mddev->dev_sectors / 2;
1234         sb->raid_disks = mddev->raid_disks;
1235         sb->md_minor = mddev->md_minor;
1236         sb->not_persistent = 0;
1237         sb->utime = mddev->utime;
1238         sb->state = 0;
1239         sb->events_hi = (mddev->events>>32);
1240         sb->events_lo = (u32)mddev->events;
1241
1242         if (mddev->reshape_position == MaxSector)
1243                 sb->minor_version = 90;
1244         else {
1245                 sb->minor_version = 91;
1246                 sb->reshape_position = mddev->reshape_position;
1247                 sb->new_level = mddev->new_level;
1248                 sb->delta_disks = mddev->delta_disks;
1249                 sb->new_layout = mddev->new_layout;
1250                 sb->new_chunk = mddev->new_chunk_sectors << 9;
1251         }
1252         mddev->minor_version = sb->minor_version;
1253         if (mddev->in_sync)
1254         {
1255                 sb->recovery_cp = mddev->recovery_cp;
1256                 sb->cp_events_hi = (mddev->events>>32);
1257                 sb->cp_events_lo = (u32)mddev->events;
1258                 if (mddev->recovery_cp == MaxSector)
1259                         sb->state = (1<< MD_SB_CLEAN);
1260         } else
1261                 sb->recovery_cp = 0;
1262
1263         sb->layout = mddev->layout;
1264         sb->chunk_size = mddev->chunk_sectors << 9;
1265
1266         if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1267                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1268
1269         sb->disks[0].state = (1<<MD_DISK_REMOVED);
1270         rdev_for_each(rdev2, mddev) {
1271                 mdp_disk_t *d;
1272                 int desc_nr;
1273                 int is_active = test_bit(In_sync, &rdev2->flags);
1274
1275                 if (rdev2->raid_disk >= 0 &&
1276                     sb->minor_version >= 91)
1277                         /* we have nowhere to store the recovery_offset,
1278                          * but if it is not below the reshape_position,
1279                          * we can piggy-back on that.
1280                          */
1281                         is_active = 1;
1282                 if (rdev2->raid_disk < 0 ||
1283                     test_bit(Faulty, &rdev2->flags))
1284                         is_active = 0;
1285                 if (is_active)
1286                         desc_nr = rdev2->raid_disk;
1287                 else
1288                         desc_nr = next_spare++;
1289                 rdev2->desc_nr = desc_nr;
1290                 d = &sb->disks[rdev2->desc_nr];
1291                 nr_disks++;
1292                 d->number = rdev2->desc_nr;
1293                 d->major = MAJOR(rdev2->bdev->bd_dev);
1294                 d->minor = MINOR(rdev2->bdev->bd_dev);
1295                 if (is_active)
1296                         d->raid_disk = rdev2->raid_disk;
1297                 else
1298                         d->raid_disk = rdev2->desc_nr; /* compatibility */
1299                 if (test_bit(Faulty, &rdev2->flags))
1300                         d->state = (1<<MD_DISK_FAULTY);
1301                 else if (is_active) {
1302                         d->state = (1<<MD_DISK_ACTIVE);
1303                         if (test_bit(In_sync, &rdev2->flags))
1304                                 d->state |= (1<<MD_DISK_SYNC);
1305                         active++;
1306                         working++;
1307                 } else {
1308                         d->state = 0;
1309                         spare++;
1310                         working++;
1311                 }
1312                 if (test_bit(WriteMostly, &rdev2->flags))
1313                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
1314         }
1315         /* now set the "removed" and "faulty" bits on any missing devices */
1316         for (i=0 ; i < mddev->raid_disks ; i++) {
1317                 mdp_disk_t *d = &sb->disks[i];
1318                 if (d->state == 0 && d->number == 0) {
1319                         d->number = i;
1320                         d->raid_disk = i;
1321                         d->state = (1<<MD_DISK_REMOVED);
1322                         d->state |= (1<<MD_DISK_FAULTY);
1323                         failed++;
1324                 }
1325         }
1326         sb->nr_disks = nr_disks;
1327         sb->active_disks = active;
1328         sb->working_disks = working;
1329         sb->failed_disks = failed;
1330         sb->spare_disks = spare;
1331
1332         sb->this_disk = sb->disks[rdev->desc_nr];
1333         sb->sb_csum = calc_sb_csum(sb);
1334 }
1335
1336 /*
1337  * rdev_size_change for 0.90.0
1338  */
1339 static unsigned long long
1340 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1341 {
1342         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1343                 return 0; /* component must fit device */
1344         if (rdev->mddev->bitmap_info.offset)
1345                 return 0; /* can't move bitmap */
1346         rdev->sb_start = calc_dev_sboffset(rdev);
1347         if (!num_sectors || num_sectors > rdev->sb_start)
1348                 num_sectors = rdev->sb_start;
1349         /* Limit to 4TB as metadata cannot record more than that.
1350          * 4TB == 2^32 KB, or 2*2^32 sectors.
1351          */
1352         if (num_sectors >= (2ULL << 32) && rdev->mddev->level >= 1)
1353                 num_sectors = (2ULL << 32) - 2;
1354         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1355                        rdev->sb_page);
1356         md_super_wait(rdev->mddev);
1357         return num_sectors;
1358 }
1359
1360 static int
1361 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1362 {
1363         /* non-zero offset changes not possible with v0.90 */
1364         return new_offset == 0;
1365 }
1366
1367 /*
1368  * version 1 superblock
1369  */
1370
1371 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1372 {
1373         __le32 disk_csum;
1374         u32 csum;
1375         unsigned long long newcsum;
1376         int size = 256 + le32_to_cpu(sb->max_dev)*2;
1377         __le32 *isuper = (__le32*)sb;
1378
1379         disk_csum = sb->sb_csum;
1380         sb->sb_csum = 0;
1381         newcsum = 0;
1382         for (; size >= 4; size -= 4)
1383                 newcsum += le32_to_cpu(*isuper++);
1384
1385         if (size == 2)
1386                 newcsum += le16_to_cpu(*(__le16*) isuper);
1387
1388         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1389         sb->sb_csum = disk_csum;
1390         return cpu_to_le32(csum);
1391 }
1392
1393 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
1394                             int acknowledged);
1395 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1396 {
1397         struct mdp_superblock_1 *sb;
1398         int ret;
1399         sector_t sb_start;
1400         sector_t sectors;
1401         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1402         int bmask;
1403
1404         /*
1405          * Calculate the position of the superblock in 512byte sectors.
1406          * It is always aligned to a 4K boundary and
1407          * depeding on minor_version, it can be:
1408          * 0: At least 8K, but less than 12K, from end of device
1409          * 1: At start of device
1410          * 2: 4K from start of device.
1411          */
1412         switch(minor_version) {
1413         case 0:
1414                 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1415                 sb_start -= 8*2;
1416                 sb_start &= ~(sector_t)(4*2-1);
1417                 break;
1418         case 1:
1419                 sb_start = 0;
1420                 break;
1421         case 2:
1422                 sb_start = 8;
1423                 break;
1424         default:
1425                 return -EINVAL;
1426         }
1427         rdev->sb_start = sb_start;
1428
1429         /* superblock is rarely larger than 1K, but it can be larger,
1430          * and it is safe to read 4k, so we do that
1431          */
1432         ret = read_disk_sb(rdev, 4096);
1433         if (ret) return ret;
1434
1435
1436         sb = page_address(rdev->sb_page);
1437
1438         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1439             sb->major_version != cpu_to_le32(1) ||
1440             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1441             le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1442             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1443                 return -EINVAL;
1444
1445         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1446                 printk("md: invalid superblock checksum on %s\n",
1447                         bdevname(rdev->bdev,b));
1448                 return -EINVAL;
1449         }
1450         if (le64_to_cpu(sb->data_size) < 10) {
1451                 printk("md: data_size too small on %s\n",
1452                        bdevname(rdev->bdev,b));
1453                 return -EINVAL;
1454         }
1455         if (sb->pad0 ||
1456             sb->pad3[0] ||
1457             memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1458                 /* Some padding is non-zero, might be a new feature */
1459                 return -EINVAL;
1460
1461         rdev->preferred_minor = 0xffff;
1462         rdev->data_offset = le64_to_cpu(sb->data_offset);
1463         rdev->new_data_offset = rdev->data_offset;
1464         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1465             (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1466                 rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1467         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1468
1469         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1470         bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1471         if (rdev->sb_size & bmask)
1472                 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1473
1474         if (minor_version
1475             && rdev->data_offset < sb_start + (rdev->sb_size/512))
1476                 return -EINVAL;
1477         if (minor_version
1478             && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1479                 return -EINVAL;
1480
1481         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1482                 rdev->desc_nr = -1;
1483         else
1484                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1485
1486         if (!rdev->bb_page) {
1487                 rdev->bb_page = alloc_page(GFP_KERNEL);
1488                 if (!rdev->bb_page)
1489                         return -ENOMEM;
1490         }
1491         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1492             rdev->badblocks.count == 0) {
1493                 /* need to load the bad block list.
1494                  * Currently we limit it to one page.
1495                  */
1496                 s32 offset;
1497                 sector_t bb_sector;
1498                 u64 *bbp;
1499                 int i;
1500                 int sectors = le16_to_cpu(sb->bblog_size);
1501                 if (sectors > (PAGE_SIZE / 512))
1502                         return -EINVAL;
1503                 offset = le32_to_cpu(sb->bblog_offset);
1504                 if (offset == 0)
1505                         return -EINVAL;
1506                 bb_sector = (long long)offset;
1507                 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1508                                   rdev->bb_page, READ, true))
1509                         return -EIO;
1510                 bbp = (u64 *)page_address(rdev->bb_page);
1511                 rdev->badblocks.shift = sb->bblog_shift;
1512                 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1513                         u64 bb = le64_to_cpu(*bbp);
1514                         int count = bb & (0x3ff);
1515                         u64 sector = bb >> 10;
1516                         sector <<= sb->bblog_shift;
1517                         count <<= sb->bblog_shift;
1518                         if (bb + 1 == 0)
1519                                 break;
1520                         if (md_set_badblocks(&rdev->badblocks,
1521                                              sector, count, 1) == 0)
1522                                 return -EINVAL;
1523                 }
1524         } else if (sb->bblog_offset != 0)
1525                 rdev->badblocks.shift = 0;
1526
1527         if (!refdev) {
1528                 ret = 1;
1529         } else {
1530                 __u64 ev1, ev2;
1531                 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1532
1533                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1534                     sb->level != refsb->level ||
1535                     sb->layout != refsb->layout ||
1536                     sb->chunksize != refsb->chunksize) {
1537                         printk(KERN_WARNING "md: %s has strangely different"
1538                                 " superblock to %s\n",
1539                                 bdevname(rdev->bdev,b),
1540                                 bdevname(refdev->bdev,b2));
1541                         return -EINVAL;
1542                 }
1543                 ev1 = le64_to_cpu(sb->events);
1544                 ev2 = le64_to_cpu(refsb->events);
1545
1546                 if (ev1 > ev2)
1547                         ret = 1;
1548                 else
1549                         ret = 0;
1550         }
1551         if (minor_version) {
1552                 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1553                 sectors -= rdev->data_offset;
1554         } else
1555                 sectors = rdev->sb_start;
1556         if (sectors < le64_to_cpu(sb->data_size))
1557                 return -EINVAL;
1558         rdev->sectors = le64_to_cpu(sb->data_size);
1559         return ret;
1560 }
1561
1562 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1563 {
1564         struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1565         __u64 ev1 = le64_to_cpu(sb->events);
1566
1567         rdev->raid_disk = -1;
1568         clear_bit(Faulty, &rdev->flags);
1569         clear_bit(In_sync, &rdev->flags);
1570         clear_bit(Bitmap_sync, &rdev->flags);
1571         clear_bit(WriteMostly, &rdev->flags);
1572
1573         if (mddev->raid_disks == 0) {
1574                 mddev->major_version = 1;
1575                 mddev->patch_version = 0;
1576                 mddev->external = 0;
1577                 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1578                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1579                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1580                 mddev->level = le32_to_cpu(sb->level);
1581                 mddev->clevel[0] = 0;
1582                 mddev->layout = le32_to_cpu(sb->layout);
1583                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1584                 mddev->dev_sectors = le64_to_cpu(sb->size);
1585                 mddev->events = ev1;
1586                 mddev->bitmap_info.offset = 0;
1587                 mddev->bitmap_info.space = 0;
1588                 /* Default location for bitmap is 1K after superblock
1589                  * using 3K - total of 4K
1590                  */
1591                 mddev->bitmap_info.default_offset = 1024 >> 9;
1592                 mddev->bitmap_info.default_space = (4096-1024) >> 9;
1593                 mddev->reshape_backwards = 0;
1594
1595                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1596                 memcpy(mddev->uuid, sb->set_uuid, 16);
1597
1598                 mddev->max_disks =  (4096-256)/2;
1599
1600                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1601                     mddev->bitmap_info.file == NULL) {
1602                         mddev->bitmap_info.offset =
1603                                 (__s32)le32_to_cpu(sb->bitmap_offset);
1604                         /* Metadata doesn't record how much space is available.
1605                          * For 1.0, we assume we can use up to the superblock
1606                          * if before, else to 4K beyond superblock.
1607                          * For others, assume no change is possible.
1608                          */
1609                         if (mddev->minor_version > 0)
1610                                 mddev->bitmap_info.space = 0;
1611                         else if (mddev->bitmap_info.offset > 0)
1612                                 mddev->bitmap_info.space =
1613                                         8 - mddev->bitmap_info.offset;
1614                         else
1615                                 mddev->bitmap_info.space =
1616                                         -mddev->bitmap_info.offset;
1617                 }
1618
1619                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1620                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1621                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1622                         mddev->new_level = le32_to_cpu(sb->new_level);
1623                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1624                         mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1625                         if (mddev->delta_disks < 0 ||
1626                             (mddev->delta_disks == 0 &&
1627                              (le32_to_cpu(sb->feature_map)
1628                               & MD_FEATURE_RESHAPE_BACKWARDS)))
1629                                 mddev->reshape_backwards = 1;
1630                 } else {
1631                         mddev->reshape_position = MaxSector;
1632                         mddev->delta_disks = 0;
1633                         mddev->new_level = mddev->level;
1634                         mddev->new_layout = mddev->layout;
1635                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1636                 }
1637
1638         } else if (mddev->pers == NULL) {
1639                 /* Insist of good event counter while assembling, except for
1640                  * spares (which don't need an event count) */
1641                 ++ev1;
1642                 if (rdev->desc_nr >= 0 &&
1643                     rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1644                     le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < 0xfffe)
1645                         if (ev1 < mddev->events)
1646                                 return -EINVAL;
1647         } else if (mddev->bitmap) {
1648                 /* If adding to array with a bitmap, then we can accept an
1649                  * older device, but not too old.
1650                  */
1651                 if (ev1 < mddev->bitmap->events_cleared)
1652                         return 0;
1653                 if (ev1 < mddev->events)
1654                         set_bit(Bitmap_sync, &rdev->flags);
1655         } else {
1656                 if (ev1 < mddev->events)
1657                         /* just a hot-add of a new device, leave raid_disk at -1 */
1658                         return 0;
1659         }
1660         if (mddev->level != LEVEL_MULTIPATH) {
1661                 int role;
1662                 if (rdev->desc_nr < 0 ||
1663                     rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1664                         role = 0xffff;
1665                         rdev->desc_nr = -1;
1666                 } else
1667                         role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1668                 switch(role) {
1669                 case 0xffff: /* spare */
1670                         break;
1671                 case 0xfffe: /* faulty */
1672                         set_bit(Faulty, &rdev->flags);
1673                         break;
1674                 default:
1675                         rdev->saved_raid_disk = role;
1676                         if ((le32_to_cpu(sb->feature_map) &
1677                              MD_FEATURE_RECOVERY_OFFSET)) {
1678                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1679                                 if (!(le32_to_cpu(sb->feature_map) &
1680                                       MD_FEATURE_RECOVERY_BITMAP))
1681                                         rdev->saved_raid_disk = -1;
1682                         } else
1683                                 set_bit(In_sync, &rdev->flags);
1684                         rdev->raid_disk = role;
1685                         break;
1686                 }
1687                 if (sb->devflags & WriteMostly1)
1688                         set_bit(WriteMostly, &rdev->flags);
1689                 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1690                         set_bit(Replacement, &rdev->flags);
1691         } else /* MULTIPATH are always insync */
1692                 set_bit(In_sync, &rdev->flags);
1693
1694         return 0;
1695 }
1696
1697 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1698 {
1699         struct mdp_superblock_1 *sb;
1700         struct md_rdev *rdev2;
1701         int max_dev, i;
1702         /* make rdev->sb match mddev and rdev data. */
1703
1704         sb = page_address(rdev->sb_page);
1705
1706         sb->feature_map = 0;
1707         sb->pad0 = 0;
1708         sb->recovery_offset = cpu_to_le64(0);
1709         memset(sb->pad3, 0, sizeof(sb->pad3));
1710
1711         sb->utime = cpu_to_le64((__u64)mddev->utime);
1712         sb->events = cpu_to_le64(mddev->events);
1713         if (mddev->in_sync)
1714                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1715         else
1716                 sb->resync_offset = cpu_to_le64(0);
1717
1718         sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1719
1720         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1721         sb->size = cpu_to_le64(mddev->dev_sectors);
1722         sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1723         sb->level = cpu_to_le32(mddev->level);
1724         sb->layout = cpu_to_le32(mddev->layout);
1725
1726         if (test_bit(WriteMostly, &rdev->flags))
1727                 sb->devflags |= WriteMostly1;
1728         else
1729                 sb->devflags &= ~WriteMostly1;
1730         sb->data_offset = cpu_to_le64(rdev->data_offset);
1731         sb->data_size = cpu_to_le64(rdev->sectors);
1732
1733         if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1734                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1735                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1736         }
1737
1738         if (rdev->raid_disk >= 0 &&
1739             !test_bit(In_sync, &rdev->flags)) {
1740                 sb->feature_map |=
1741                         cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1742                 sb->recovery_offset =
1743                         cpu_to_le64(rdev->recovery_offset);
1744                 if (rdev->saved_raid_disk >= 0 && mddev->bitmap)
1745                         sb->feature_map |=
1746                                 cpu_to_le32(MD_FEATURE_RECOVERY_BITMAP);
1747         }
1748         if (test_bit(Replacement, &rdev->flags))
1749                 sb->feature_map |=
1750                         cpu_to_le32(MD_FEATURE_REPLACEMENT);
1751
1752         if (mddev->reshape_position != MaxSector) {
1753                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1754                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1755                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1756                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1757                 sb->new_level = cpu_to_le32(mddev->new_level);
1758                 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1759                 if (mddev->delta_disks == 0 &&
1760                     mddev->reshape_backwards)
1761                         sb->feature_map
1762                                 |= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1763                 if (rdev->new_data_offset != rdev->data_offset) {
1764                         sb->feature_map
1765                                 |= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1766                         sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1767                                                              - rdev->data_offset));
1768                 }
1769         }
1770
1771         if (rdev->badblocks.count == 0)
1772                 /* Nothing to do for bad blocks*/ ;
1773         else if (sb->bblog_offset == 0)
1774                 /* Cannot record bad blocks on this device */
1775                 md_error(mddev, rdev);
1776         else {
1777                 struct badblocks *bb = &rdev->badblocks;
1778                 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1779                 u64 *p = bb->page;
1780                 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1781                 if (bb->changed) {
1782                         unsigned seq;
1783
1784 retry:
1785                         seq = read_seqbegin(&bb->lock);
1786
1787                         memset(bbp, 0xff, PAGE_SIZE);
1788
1789                         for (i = 0 ; i < bb->count ; i++) {
1790                                 u64 internal_bb = p[i];
1791                                 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1792                                                 | BB_LEN(internal_bb));
1793                                 bbp[i] = cpu_to_le64(store_bb);
1794                         }
1795                         bb->changed = 0;
1796                         if (read_seqretry(&bb->lock, seq))
1797                                 goto retry;
1798
1799                         bb->sector = (rdev->sb_start +
1800                                       (int)le32_to_cpu(sb->bblog_offset));
1801                         bb->size = le16_to_cpu(sb->bblog_size);
1802                 }
1803         }
1804
1805         max_dev = 0;
1806         rdev_for_each(rdev2, mddev)
1807                 if (rdev2->desc_nr+1 > max_dev)
1808                         max_dev = rdev2->desc_nr+1;
1809
1810         if (max_dev > le32_to_cpu(sb->max_dev)) {
1811                 int bmask;
1812                 sb->max_dev = cpu_to_le32(max_dev);
1813                 rdev->sb_size = max_dev * 2 + 256;
1814                 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1815                 if (rdev->sb_size & bmask)
1816                         rdev->sb_size = (rdev->sb_size | bmask) + 1;
1817         } else
1818                 max_dev = le32_to_cpu(sb->max_dev);
1819
1820         for (i=0; i<max_dev;i++)
1821                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1822         
1823         rdev_for_each(rdev2, mddev) {
1824                 i = rdev2->desc_nr;
1825                 if (test_bit(Faulty, &rdev2->flags))
1826                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1827                 else if (test_bit(In_sync, &rdev2->flags))
1828                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1829                 else if (rdev2->raid_disk >= 0)
1830                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1831                 else
1832                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1833         }
1834
1835         sb->sb_csum = calc_sb_1_csum(sb);
1836 }
1837
1838 static unsigned long long
1839 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1840 {
1841         struct mdp_superblock_1 *sb;
1842         sector_t max_sectors;
1843         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1844                 return 0; /* component must fit device */
1845         if (rdev->data_offset != rdev->new_data_offset)
1846                 return 0; /* too confusing */
1847         if (rdev->sb_start < rdev->data_offset) {
1848                 /* minor versions 1 and 2; superblock before data */
1849                 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1850                 max_sectors -= rdev->data_offset;
1851                 if (!num_sectors || num_sectors > max_sectors)
1852                         num_sectors = max_sectors;
1853         } else if (rdev->mddev->bitmap_info.offset) {
1854                 /* minor version 0 with bitmap we can't move */
1855                 return 0;
1856         } else {
1857                 /* minor version 0; superblock after data */
1858                 sector_t sb_start;
1859                 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1860                 sb_start &= ~(sector_t)(4*2 - 1);
1861                 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1862                 if (!num_sectors || num_sectors > max_sectors)
1863                         num_sectors = max_sectors;
1864                 rdev->sb_start = sb_start;
1865         }
1866         sb = page_address(rdev->sb_page);
1867         sb->data_size = cpu_to_le64(num_sectors);
1868         sb->super_offset = rdev->sb_start;
1869         sb->sb_csum = calc_sb_1_csum(sb);
1870         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1871                        rdev->sb_page);
1872         md_super_wait(rdev->mddev);
1873         return num_sectors;
1874
1875 }
1876
1877 static int
1878 super_1_allow_new_offset(struct md_rdev *rdev,
1879                          unsigned long long new_offset)
1880 {
1881         /* All necessary checks on new >= old have been done */
1882         struct bitmap *bitmap;
1883         if (new_offset >= rdev->data_offset)
1884                 return 1;
1885
1886         /* with 1.0 metadata, there is no metadata to tread on
1887          * so we can always move back */
1888         if (rdev->mddev->minor_version == 0)
1889                 return 1;
1890
1891         /* otherwise we must be sure not to step on
1892          * any metadata, so stay:
1893          * 36K beyond start of superblock
1894          * beyond end of badblocks
1895          * beyond write-intent bitmap
1896          */
1897         if (rdev->sb_start + (32+4)*2 > new_offset)
1898                 return 0;
1899         bitmap = rdev->mddev->bitmap;
1900         if (bitmap && !rdev->mddev->bitmap_info.file &&
1901             rdev->sb_start + rdev->mddev->bitmap_info.offset +
1902             bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
1903                 return 0;
1904         if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
1905                 return 0;
1906
1907         return 1;
1908 }
1909
1910 static struct super_type super_types[] = {
1911         [0] = {
1912                 .name   = "0.90.0",
1913                 .owner  = THIS_MODULE,
1914                 .load_super         = super_90_load,
1915                 .validate_super     = super_90_validate,
1916                 .sync_super         = super_90_sync,
1917                 .rdev_size_change   = super_90_rdev_size_change,
1918                 .allow_new_offset   = super_90_allow_new_offset,
1919         },
1920         [1] = {
1921                 .name   = "md-1",
1922                 .owner  = THIS_MODULE,
1923                 .load_super         = super_1_load,
1924                 .validate_super     = super_1_validate,
1925                 .sync_super         = super_1_sync,
1926                 .rdev_size_change   = super_1_rdev_size_change,
1927                 .allow_new_offset   = super_1_allow_new_offset,
1928         },
1929 };
1930
1931 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
1932 {
1933         if (mddev->sync_super) {
1934                 mddev->sync_super(mddev, rdev);
1935                 return;
1936         }
1937
1938         BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
1939
1940         super_types[mddev->major_version].sync_super(mddev, rdev);
1941 }
1942
1943 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
1944 {
1945         struct md_rdev *rdev, *rdev2;
1946
1947         rcu_read_lock();
1948         rdev_for_each_rcu(rdev, mddev1)
1949                 rdev_for_each_rcu(rdev2, mddev2)
1950                         if (rdev->bdev->bd_contains ==
1951                             rdev2->bdev->bd_contains) {
1952                                 rcu_read_unlock();
1953                                 return 1;
1954                         }
1955         rcu_read_unlock();
1956         return 0;
1957 }
1958
1959 static LIST_HEAD(pending_raid_disks);
1960
1961 /*
1962  * Try to register data integrity profile for an mddev
1963  *
1964  * This is called when an array is started and after a disk has been kicked
1965  * from the array. It only succeeds if all working and active component devices
1966  * are integrity capable with matching profiles.
1967  */
1968 int md_integrity_register(struct mddev *mddev)
1969 {
1970         struct md_rdev *rdev, *reference = NULL;
1971
1972         if (list_empty(&mddev->disks))
1973                 return 0; /* nothing to do */
1974         if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
1975                 return 0; /* shouldn't register, or already is */
1976         rdev_for_each(rdev, mddev) {
1977                 /* skip spares and non-functional disks */
1978                 if (test_bit(Faulty, &rdev->flags))
1979                         continue;
1980                 if (rdev->raid_disk < 0)
1981                         continue;
1982                 if (!reference) {
1983                         /* Use the first rdev as the reference */
1984                         reference = rdev;
1985                         continue;
1986                 }
1987                 /* does this rdev's profile match the reference profile? */
1988                 if (blk_integrity_compare(reference->bdev->bd_disk,
1989                                 rdev->bdev->bd_disk) < 0)
1990                         return -EINVAL;
1991         }
1992         if (!reference || !bdev_get_integrity(reference->bdev))
1993                 return 0;
1994         /*
1995          * All component devices are integrity capable and have matching
1996          * profiles, register the common profile for the md device.
1997          */
1998         if (blk_integrity_register(mddev->gendisk,
1999                         bdev_get_integrity(reference->bdev)) != 0) {
2000                 printk(KERN_ERR "md: failed to register integrity for %s\n",
2001                         mdname(mddev));
2002                 return -EINVAL;
2003         }
2004         printk(KERN_NOTICE "md: data integrity enabled on %s\n", mdname(mddev));
2005         if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
2006                 printk(KERN_ERR "md: failed to create integrity pool for %s\n",
2007                        mdname(mddev));
2008                 return -EINVAL;
2009         }
2010         return 0;
2011 }
2012 EXPORT_SYMBOL(md_integrity_register);
2013
2014 /* Disable data integrity if non-capable/non-matching disk is being added */
2015 void md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2016 {
2017         struct blk_integrity *bi_rdev;
2018         struct blk_integrity *bi_mddev;
2019
2020         if (!mddev->gendisk)
2021                 return;
2022
2023         bi_rdev = bdev_get_integrity(rdev->bdev);
2024         bi_mddev = blk_get_integrity(mddev->gendisk);
2025
2026         if (!bi_mddev) /* nothing to do */
2027                 return;
2028         if (rdev->raid_disk < 0) /* skip spares */
2029                 return;
2030         if (bi_rdev && blk_integrity_compare(mddev->gendisk,
2031                                              rdev->bdev->bd_disk) >= 0)
2032                 return;
2033         printk(KERN_NOTICE "disabling data integrity on %s\n", mdname(mddev));
2034         blk_integrity_unregister(mddev->gendisk);
2035 }
2036 EXPORT_SYMBOL(md_integrity_add_rdev);
2037
2038 static int bind_rdev_to_array(struct md_rdev * rdev, struct mddev * mddev)
2039 {
2040         char b[BDEVNAME_SIZE];
2041         struct kobject *ko;
2042         char *s;
2043         int err;
2044
2045         if (rdev->mddev) {
2046                 MD_BUG();
2047                 return -EINVAL;
2048         }
2049
2050         /* prevent duplicates */
2051         if (find_rdev(mddev, rdev->bdev->bd_dev))
2052                 return -EEXIST;
2053
2054         /* make sure rdev->sectors exceeds mddev->dev_sectors */
2055         if (rdev->sectors && (mddev->dev_sectors == 0 ||
2056                         rdev->sectors < mddev->dev_sectors)) {
2057                 if (mddev->pers) {
2058                         /* Cannot change size, so fail
2059                          * If mddev->level <= 0, then we don't care
2060                          * about aligning sizes (e.g. linear)
2061                          */
2062                         if (mddev->level > 0)
2063                                 return -ENOSPC;
2064                 } else
2065                         mddev->dev_sectors = rdev->sectors;
2066         }
2067
2068         /* Verify rdev->desc_nr is unique.
2069          * If it is -1, assign a free number, else
2070          * check number is not in use
2071          */
2072         if (rdev->desc_nr < 0) {
2073                 int choice = 0;
2074                 if (mddev->pers) choice = mddev->raid_disks;
2075                 while (find_rdev_nr(mddev, choice))
2076                         choice++;
2077                 rdev->desc_nr = choice;
2078         } else {
2079                 if (find_rdev_nr(mddev, rdev->desc_nr))
2080                         return -EBUSY;
2081         }
2082         if (mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2083                 printk(KERN_WARNING "md: %s: array is limited to %d devices\n",
2084                        mdname(mddev), mddev->max_disks);
2085                 return -EBUSY;
2086         }
2087         bdevname(rdev->bdev,b);
2088         while ( (s=strchr(b, '/')) != NULL)
2089                 *s = '!';
2090
2091         rdev->mddev = mddev;
2092         printk(KERN_INFO "md: bind<%s>\n", b);
2093
2094         if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2095                 goto fail;
2096
2097         ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2098         if (sysfs_create_link(&rdev->kobj, ko, "block"))
2099                 /* failure here is OK */;
2100         rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2101
2102         list_add_rcu(&rdev->same_set, &mddev->disks);
2103         bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2104
2105         /* May as well allow recovery to be retried once */
2106         mddev->recovery_disabled++;
2107
2108         return 0;
2109
2110  fail:
2111         printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
2112                b, mdname(mddev));
2113         return err;
2114 }
2115
2116 static void md_delayed_delete(struct work_struct *ws)
2117 {
2118         struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2119         kobject_del(&rdev->kobj);
2120         kobject_put(&rdev->kobj);
2121 }
2122
2123 static void unbind_rdev_from_array(struct md_rdev * rdev)
2124 {
2125         char b[BDEVNAME_SIZE];
2126         if (!rdev->mddev) {
2127                 MD_BUG();
2128                 return;
2129         }
2130         bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2131         list_del_rcu(&rdev->same_set);
2132         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
2133         rdev->mddev = NULL;
2134         sysfs_remove_link(&rdev->kobj, "block");
2135         sysfs_put(rdev->sysfs_state);
2136         rdev->sysfs_state = NULL;
2137         rdev->badblocks.count = 0;
2138         /* We need to delay this, otherwise we can deadlock when
2139          * writing to 'remove' to "dev/state".  We also need
2140          * to delay it due to rcu usage.
2141          */
2142         synchronize_rcu();
2143         INIT_WORK(&rdev->del_work, md_delayed_delete);
2144         kobject_get(&rdev->kobj);
2145         queue_work(md_misc_wq, &rdev->del_work);
2146 }
2147
2148 /*
2149  * prevent the device from being mounted, repartitioned or
2150  * otherwise reused by a RAID array (or any other kernel
2151  * subsystem), by bd_claiming the device.
2152  */
2153 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2154 {
2155         int err = 0;
2156         struct block_device *bdev;
2157         char b[BDEVNAME_SIZE];
2158
2159         bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2160                                  shared ? (struct md_rdev *)lock_rdev : rdev);
2161         if (IS_ERR(bdev)) {
2162                 printk(KERN_ERR "md: could not open %s.\n",
2163                         __bdevname(dev, b));
2164                 return PTR_ERR(bdev);
2165         }
2166         rdev->bdev = bdev;
2167         return err;
2168 }
2169
2170 static void unlock_rdev(struct md_rdev *rdev)
2171 {
2172         struct block_device *bdev = rdev->bdev;
2173         rdev->bdev = NULL;
2174         if (!bdev)
2175                 MD_BUG();
2176         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2177 }
2178
2179 void md_autodetect_dev(dev_t dev);
2180
2181 static void export_rdev(struct md_rdev * rdev)
2182 {
2183         char b[BDEVNAME_SIZE];
2184         printk(KERN_INFO "md: export_rdev(%s)\n",
2185                 bdevname(rdev->bdev,b));
2186         if (rdev->mddev)
2187                 MD_BUG();
2188         md_rdev_clear(rdev);
2189 #ifndef MODULE
2190         if (test_bit(AutoDetected, &rdev->flags))
2191                 md_autodetect_dev(rdev->bdev->bd_dev);
2192 #endif
2193         unlock_rdev(rdev);
2194         kobject_put(&rdev->kobj);
2195 }
2196
2197 static void kick_rdev_from_array(struct md_rdev * rdev)
2198 {
2199         unbind_rdev_from_array(rdev);
2200         export_rdev(rdev);
2201 }
2202
2203 static void export_array(struct mddev *mddev)
2204 {
2205         struct md_rdev *rdev, *tmp;
2206
2207         rdev_for_each_safe(rdev, tmp, mddev) {
2208                 if (!rdev->mddev) {
2209                         MD_BUG();
2210                         continue;
2211                 }
2212                 kick_rdev_from_array(rdev);
2213         }
2214         if (!list_empty(&mddev->disks))
2215                 MD_BUG();
2216         mddev->raid_disks = 0;
2217         mddev->major_version = 0;
2218 }
2219
2220 static void print_desc(mdp_disk_t *desc)
2221 {
2222         printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
2223                 desc->major,desc->minor,desc->raid_disk,desc->state);
2224 }
2225
2226 static void print_sb_90(mdp_super_t *sb)
2227 {
2228         int i;
2229
2230         printk(KERN_INFO 
2231                 "md:  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
2232                 sb->major_version, sb->minor_version, sb->patch_version,
2233                 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
2234                 sb->ctime);
2235         printk(KERN_INFO "md:     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
2236                 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
2237                 sb->md_minor, sb->layout, sb->chunk_size);
2238         printk(KERN_INFO "md:     UT:%08x ST:%d AD:%d WD:%d"
2239                 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
2240                 sb->utime, sb->state, sb->active_disks, sb->working_disks,
2241                 sb->failed_disks, sb->spare_disks,
2242                 sb->sb_csum, (unsigned long)sb->events_lo);
2243
2244         printk(KERN_INFO);
2245         for (i = 0; i < MD_SB_DISKS; i++) {
2246                 mdp_disk_t *desc;
2247
2248                 desc = sb->disks + i;
2249                 if (desc->number || desc->major || desc->minor ||
2250                     desc->raid_disk || (desc->state && (desc->state != 4))) {
2251                         printk("     D %2d: ", i);
2252                         print_desc(desc);
2253                 }
2254         }
2255         printk(KERN_INFO "md:     THIS: ");
2256         print_desc(&sb->this_disk);
2257 }
2258
2259 static void print_sb_1(struct mdp_superblock_1 *sb)
2260 {
2261         __u8 *uuid;
2262
2263         uuid = sb->set_uuid;
2264         printk(KERN_INFO
2265                "md:  SB: (V:%u) (F:0x%08x) Array-ID:<%pU>\n"
2266                "md:    Name: \"%s\" CT:%llu\n",
2267                 le32_to_cpu(sb->major_version),
2268                 le32_to_cpu(sb->feature_map),
2269                 uuid,
2270                 sb->set_name,
2271                 (unsigned long long)le64_to_cpu(sb->ctime)
2272                        & MD_SUPERBLOCK_1_TIME_SEC_MASK);
2273
2274         uuid = sb->device_uuid;
2275         printk(KERN_INFO
2276                "md:       L%u SZ%llu RD:%u LO:%u CS:%u DO:%llu DS:%llu SO:%llu"
2277                         " RO:%llu\n"
2278                "md:     Dev:%08x UUID: %pU\n"
2279                "md:       (F:0x%08x) UT:%llu Events:%llu ResyncOffset:%llu CSUM:0x%08x\n"
2280                "md:         (MaxDev:%u) \n",
2281                 le32_to_cpu(sb->level),
2282                 (unsigned long long)le64_to_cpu(sb->size),
2283                 le32_to_cpu(sb->raid_disks),
2284                 le32_to_cpu(sb->layout),
2285                 le32_to_cpu(sb->chunksize),
2286                 (unsigned long long)le64_to_cpu(sb->data_offset),
2287                 (unsigned long long)le64_to_cpu(sb->data_size),
2288                 (unsigned long long)le64_to_cpu(sb->super_offset),
2289                 (unsigned long long)le64_to_cpu(sb->recovery_offset),
2290                 le32_to_cpu(sb->dev_number),
2291                 uuid,
2292                 sb->devflags,
2293                 (unsigned long long)le64_to_cpu(sb->utime) & MD_SUPERBLOCK_1_TIME_SEC_MASK,
2294                 (unsigned long long)le64_to_cpu(sb->events),
2295                 (unsigned long long)le64_to_cpu(sb->resync_offset),
2296                 le32_to_cpu(sb->sb_csum),
2297                 le32_to_cpu(sb->max_dev)
2298                 );
2299 }
2300
2301 static void print_rdev(struct md_rdev *rdev, int major_version)
2302 {
2303         char b[BDEVNAME_SIZE];
2304         printk(KERN_INFO "md: rdev %s, Sect:%08llu F:%d S:%d DN:%u\n",
2305                 bdevname(rdev->bdev, b), (unsigned long long)rdev->sectors,
2306                 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
2307                 rdev->desc_nr);
2308         if (rdev->sb_loaded) {
2309                 printk(KERN_INFO "md: rdev superblock (MJ:%d):\n", major_version);
2310                 switch (major_version) {
2311                 case 0:
2312                         print_sb_90(page_address(rdev->sb_page));
2313                         break;
2314                 case 1:
2315                         print_sb_1(page_address(rdev->sb_page));
2316                         break;
2317                 }
2318         } else
2319                 printk(KERN_INFO "md: no rdev superblock!\n");
2320 }
2321
2322 static void md_print_devices(void)
2323 {
2324         struct list_head *tmp;
2325         struct md_rdev *rdev;
2326         struct mddev *mddev;
2327         char b[BDEVNAME_SIZE];
2328
2329         printk("\n");
2330         printk("md:     **********************************\n");
2331         printk("md:     * <COMPLETE RAID STATE PRINTOUT> *\n");
2332         printk("md:     **********************************\n");
2333         for_each_mddev(mddev, tmp) {
2334
2335                 if (mddev->bitmap)
2336                         bitmap_print_sb(mddev->bitmap);
2337                 else
2338                         printk("%s: ", mdname(mddev));
2339                 rdev_for_each(rdev, mddev)
2340                         printk("<%s>", bdevname(rdev->bdev,b));
2341                 printk("\n");
2342
2343                 rdev_for_each(rdev, mddev)
2344                         print_rdev(rdev, mddev->major_version);
2345         }
2346         printk("md:     **********************************\n");
2347         printk("\n");
2348 }
2349
2350
2351 static void sync_sbs(struct mddev * mddev, int nospares)
2352 {
2353         /* Update each superblock (in-memory image), but
2354          * if we are allowed to, skip spares which already
2355          * have the right event counter, or have one earlier
2356          * (which would mean they aren't being marked as dirty
2357          * with the rest of the array)
2358          */
2359         struct md_rdev *rdev;
2360         rdev_for_each(rdev, mddev) {
2361                 if (rdev->sb_events == mddev->events ||
2362                     (nospares &&
2363                      rdev->raid_disk < 0 &&
2364                      rdev->sb_events+1 == mddev->events)) {
2365                         /* Don't update this superblock */
2366                         rdev->sb_loaded = 2;
2367                 } else {
2368                         sync_super(mddev, rdev);
2369                         rdev->sb_loaded = 1;
2370                 }
2371         }
2372 }
2373
2374 static void md_update_sb(struct mddev * mddev, int force_change)
2375 {
2376         struct md_rdev *rdev;
2377         int sync_req;
2378         int nospares = 0;
2379         int any_badblocks_changed = 0;
2380
2381         if (mddev->ro) {
2382                 if (force_change)
2383                         set_bit(MD_CHANGE_DEVS, &mddev->flags);
2384                 return;
2385         }
2386 repeat:
2387         /* First make sure individual recovery_offsets are correct */
2388         rdev_for_each(rdev, mddev) {
2389                 if (rdev->raid_disk >= 0 &&
2390                     mddev->delta_disks >= 0 &&
2391                     !test_bit(In_sync, &rdev->flags) &&
2392                     mddev->curr_resync_completed > rdev->recovery_offset)
2393                                 rdev->recovery_offset = mddev->curr_resync_completed;
2394
2395         }       
2396         if (!mddev->persistent) {
2397                 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2398                 clear_bit(MD_CHANGE_DEVS, &mddev->flags);
2399                 if (!mddev->external) {
2400                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2401                         rdev_for_each(rdev, mddev) {
2402                                 if (rdev->badblocks.changed) {
2403                                         rdev->badblocks.changed = 0;
2404                                         md_ack_all_badblocks(&rdev->badblocks);
2405                                         md_error(mddev, rdev);
2406                                 }
2407                                 clear_bit(Blocked, &rdev->flags);
2408                                 clear_bit(BlockedBadBlocks, &rdev->flags);
2409                                 wake_up(&rdev->blocked_wait);
2410                         }
2411                 }
2412                 wake_up(&mddev->sb_wait);
2413                 return;
2414         }
2415
2416         spin_lock_irq(&mddev->write_lock);
2417
2418         mddev->utime = get_seconds();
2419
2420         if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
2421                 force_change = 1;
2422         if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
2423                 /* just a clean<-> dirty transition, possibly leave spares alone,
2424                  * though if events isn't the right even/odd, we will have to do
2425                  * spares after all
2426                  */
2427                 nospares = 1;
2428         if (force_change)
2429                 nospares = 0;
2430         if (mddev->degraded)
2431                 /* If the array is degraded, then skipping spares is both
2432                  * dangerous and fairly pointless.
2433                  * Dangerous because a device that was removed from the array
2434                  * might have a event_count that still looks up-to-date,
2435                  * so it can be re-added without a resync.
2436                  * Pointless because if there are any spares to skip,
2437                  * then a recovery will happen and soon that array won't
2438                  * be degraded any more and the spare can go back to sleep then.
2439                  */
2440                 nospares = 0;
2441
2442         sync_req = mddev->in_sync;
2443
2444         /* If this is just a dirty<->clean transition, and the array is clean
2445          * and 'events' is odd, we can roll back to the previous clean state */
2446         if (nospares
2447             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2448             && mddev->can_decrease_events
2449             && mddev->events != 1) {
2450                 mddev->events--;
2451                 mddev->can_decrease_events = 0;
2452         } else {
2453                 /* otherwise we have to go forward and ... */
2454                 mddev->events ++;
2455                 mddev->can_decrease_events = nospares;
2456         }
2457
2458         if (!mddev->events) {
2459                 /*
2460                  * oops, this 64-bit counter should never wrap.
2461                  * Either we are in around ~1 trillion A.C., assuming
2462                  * 1 reboot per second, or we have a bug:
2463                  */
2464                 MD_BUG();
2465                 mddev->events --;
2466         }
2467
2468         rdev_for_each(rdev, mddev) {
2469                 if (rdev->badblocks.changed)
2470                         any_badblocks_changed++;
2471                 if (test_bit(Faulty, &rdev->flags))
2472                         set_bit(FaultRecorded, &rdev->flags);
2473         }
2474
2475         sync_sbs(mddev, nospares);
2476         spin_unlock_irq(&mddev->write_lock);
2477
2478         pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2479                  mdname(mddev), mddev->in_sync);
2480
2481         bitmap_update_sb(mddev->bitmap);
2482         rdev_for_each(rdev, mddev) {
2483                 char b[BDEVNAME_SIZE];
2484
2485                 if (rdev->sb_loaded != 1)
2486                         continue; /* no noise on spare devices */
2487
2488                 if (!test_bit(Faulty, &rdev->flags)) {
2489                         md_super_write(mddev,rdev,
2490                                        rdev->sb_start, rdev->sb_size,
2491                                        rdev->sb_page);
2492                         pr_debug("md: (write) %s's sb offset: %llu\n",
2493                                  bdevname(rdev->bdev, b),
2494                                  (unsigned long long)rdev->sb_start);
2495                         rdev->sb_events = mddev->events;
2496                         if (rdev->badblocks.size) {
2497                                 md_super_write(mddev, rdev,
2498                                                rdev->badblocks.sector,
2499                                                rdev->badblocks.size << 9,
2500                                                rdev->bb_page);
2501                                 rdev->badblocks.size = 0;
2502                         }
2503
2504                 } else
2505                         pr_debug("md: %s (skipping faulty)\n",
2506                                  bdevname(rdev->bdev, b));
2507
2508                 if (mddev->level == LEVEL_MULTIPATH)
2509                         /* only need to write one superblock... */
2510                         break;
2511         }
2512         md_super_wait(mddev);
2513         /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
2514
2515         spin_lock_irq(&mddev->write_lock);
2516         if (mddev->in_sync != sync_req ||
2517             test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
2518                 /* have to write it out again */
2519                 spin_unlock_irq(&mddev->write_lock);
2520                 goto repeat;
2521         }
2522         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2523         spin_unlock_irq(&mddev->write_lock);
2524         wake_up(&mddev->sb_wait);
2525         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2526                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2527
2528         rdev_for_each(rdev, mddev) {
2529                 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2530                         clear_bit(Blocked, &rdev->flags);
2531
2532                 if (any_badblocks_changed)
2533                         md_ack_all_badblocks(&rdev->badblocks);
2534                 clear_bit(BlockedBadBlocks, &rdev->flags);
2535                 wake_up(&rdev->blocked_wait);
2536         }
2537 }
2538
2539 /* words written to sysfs files may, or may not, be \n terminated.
2540  * We want to accept with case. For this we use cmd_match.
2541  */
2542 static int cmd_match(const char *cmd, const char *str)
2543 {
2544         /* See if cmd, written into a sysfs file, matches
2545          * str.  They must either be the same, or cmd can
2546          * have a trailing newline
2547          */
2548         while (*cmd && *str && *cmd == *str) {
2549                 cmd++;
2550                 str++;
2551         }
2552         if (*cmd == '\n')
2553                 cmd++;
2554         if (*str || *cmd)
2555                 return 0;
2556         return 1;
2557 }
2558
2559 struct rdev_sysfs_entry {
2560         struct attribute attr;
2561         ssize_t (*show)(struct md_rdev *, char *);
2562         ssize_t (*store)(struct md_rdev *, const char *, size_t);
2563 };
2564
2565 static ssize_t
2566 state_show(struct md_rdev *rdev, char *page)
2567 {
2568         char *sep = "";
2569         size_t len = 0;
2570
2571         if (test_bit(Faulty, &rdev->flags) ||
2572             rdev->badblocks.unacked_exist) {
2573                 len+= sprintf(page+len, "%sfaulty",sep);
2574                 sep = ",";
2575         }
2576         if (test_bit(In_sync, &rdev->flags)) {
2577                 len += sprintf(page+len, "%sin_sync",sep);
2578                 sep = ",";
2579         }
2580         if (test_bit(WriteMostly, &rdev->flags)) {
2581                 len += sprintf(page+len, "%swrite_mostly",sep);
2582                 sep = ",";
2583         }
2584         if (test_bit(Blocked, &rdev->flags) ||
2585             (rdev->badblocks.unacked_exist
2586              && !test_bit(Faulty, &rdev->flags))) {
2587                 len += sprintf(page+len, "%sblocked", sep);
2588                 sep = ",";
2589         }
2590         if (!test_bit(Faulty, &rdev->flags) &&
2591             !test_bit(In_sync, &rdev->flags)) {
2592                 len += sprintf(page+len, "%sspare", sep);
2593                 sep = ",";
2594         }
2595         if (test_bit(WriteErrorSeen, &rdev->flags)) {
2596                 len += sprintf(page+len, "%swrite_error", sep);
2597                 sep = ",";
2598         }
2599         if (test_bit(WantReplacement, &rdev->flags)) {
2600                 len += sprintf(page+len, "%swant_replacement", sep);
2601                 sep = ",";
2602         }
2603         if (test_bit(Replacement, &rdev->flags)) {
2604                 len += sprintf(page+len, "%sreplacement", sep);
2605                 sep = ",";
2606         }
2607
2608         return len+sprintf(page+len, "\n");
2609 }
2610
2611 static ssize_t
2612 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2613 {
2614         /* can write
2615          *  faulty  - simulates an error
2616          *  remove  - disconnects the device
2617          *  writemostly - sets write_mostly
2618          *  -writemostly - clears write_mostly
2619          *  blocked - sets the Blocked flags
2620          *  -blocked - clears the Blocked and possibly simulates an error
2621          *  insync - sets Insync providing device isn't active
2622          *  -insync - clear Insync for a device with a slot assigned,
2623          *            so that it gets rebuilt based on bitmap
2624          *  write_error - sets WriteErrorSeen
2625          *  -write_error - clears WriteErrorSeen
2626          */
2627         int err = -EINVAL;
2628         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2629                 md_error(rdev->mddev, rdev);
2630                 if (test_bit(Faulty, &rdev->flags))
2631                         err = 0;
2632                 else
2633                         err = -EBUSY;
2634         } else if (cmd_match(buf, "remove")) {
2635                 if (rdev->raid_disk >= 0)
2636                         err = -EBUSY;
2637                 else {
2638                         struct mddev *mddev = rdev->mddev;
2639                         kick_rdev_from_array(rdev);
2640                         if (mddev->pers)
2641                                 md_update_sb(mddev, 1);
2642                         md_new_event(mddev);
2643                         err = 0;
2644                 }
2645         } else if (cmd_match(buf, "writemostly")) {
2646                 set_bit(WriteMostly, &rdev->flags);
2647                 err = 0;
2648         } else if (cmd_match(buf, "-writemostly")) {
2649                 clear_bit(WriteMostly, &rdev->flags);
2650                 err = 0;
2651         } else if (cmd_match(buf, "blocked")) {
2652                 set_bit(Blocked, &rdev->flags);
2653                 err = 0;
2654         } else if (cmd_match(buf, "-blocked")) {
2655                 if (!test_bit(Faulty, &rdev->flags) &&
2656                     rdev->badblocks.unacked_exist) {
2657                         /* metadata handler doesn't understand badblocks,
2658                          * so we need to fail the device
2659                          */
2660                         md_error(rdev->mddev, rdev);
2661                 }
2662                 clear_bit(Blocked, &rdev->flags);
2663                 clear_bit(BlockedBadBlocks, &rdev->flags);
2664                 wake_up(&rdev->blocked_wait);
2665                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2666                 md_wakeup_thread(rdev->mddev->thread);
2667
2668                 err = 0;
2669         } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2670                 set_bit(In_sync, &rdev->flags);
2671                 err = 0;
2672         } else if (cmd_match(buf, "-insync") && rdev->raid_disk >= 0) {
2673                 clear_bit(In_sync, &rdev->flags);
2674                 rdev->saved_raid_disk = rdev->raid_disk;
2675                 rdev->raid_disk = -1;
2676                 err = 0;
2677         } else if (cmd_match(buf, "write_error")) {
2678                 set_bit(WriteErrorSeen, &rdev->flags);
2679                 err = 0;
2680         } else if (cmd_match(buf, "-write_error")) {
2681                 clear_bit(WriteErrorSeen, &rdev->flags);
2682                 err = 0;
2683         } else if (cmd_match(buf, "want_replacement")) {
2684                 /* Any non-spare device that is not a replacement can
2685                  * become want_replacement at any time, but we then need to
2686                  * check if recovery is needed.
2687                  */
2688                 if (rdev->raid_disk >= 0 &&
2689                     !test_bit(Replacement, &rdev->flags))
2690                         set_bit(WantReplacement, &rdev->flags);
2691                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2692                 md_wakeup_thread(rdev->mddev->thread);
2693                 err = 0;
2694         } else if (cmd_match(buf, "-want_replacement")) {
2695                 /* Clearing 'want_replacement' is always allowed.
2696                  * Once replacements starts it is too late though.
2697                  */
2698                 err = 0;
2699                 clear_bit(WantReplacement, &rdev->flags);
2700         } else if (cmd_match(buf, "replacement")) {
2701                 /* Can only set a device as a replacement when array has not
2702                  * yet been started.  Once running, replacement is automatic
2703                  * from spares, or by assigning 'slot'.
2704                  */
2705                 if (rdev->mddev->pers)
2706                         err = -EBUSY;
2707                 else {
2708                         set_bit(Replacement, &rdev->flags);
2709                         err = 0;
2710                 }
2711         } else if (cmd_match(buf, "-replacement")) {
2712                 /* Similarly, can only clear Replacement before start */
2713                 if (rdev->mddev->pers)
2714                         err = -EBUSY;
2715                 else {
2716                         clear_bit(Replacement, &rdev->flags);
2717                         err = 0;
2718                 }
2719         }
2720         if (!err)
2721                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2722         return err ? err : len;
2723 }
2724 static struct rdev_sysfs_entry rdev_state =
2725 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
2726
2727 static ssize_t
2728 errors_show(struct md_rdev *rdev, char *page)
2729 {
2730         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2731 }
2732
2733 static ssize_t
2734 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2735 {
2736         char *e;
2737         unsigned long n = simple_strtoul(buf, &e, 10);
2738         if (*buf && (*e == 0 || *e == '\n')) {
2739                 atomic_set(&rdev->corrected_errors, n);
2740                 return len;
2741         }
2742         return -EINVAL;
2743 }
2744 static struct rdev_sysfs_entry rdev_errors =
2745 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2746
2747 static ssize_t
2748 slot_show(struct md_rdev *rdev, char *page)
2749 {
2750         if (rdev->raid_disk < 0)
2751                 return sprintf(page, "none\n");
2752         else
2753                 return sprintf(page, "%d\n", rdev->raid_disk);
2754 }
2755
2756 static ssize_t
2757 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2758 {
2759         char *e;
2760         int err;
2761         int slot = simple_strtoul(buf, &e, 10);
2762         if (strncmp(buf, "none", 4)==0)
2763                 slot = -1;
2764         else if (e==buf || (*e && *e!= '\n'))
2765                 return -EINVAL;
2766         if (rdev->mddev->pers && slot == -1) {
2767                 /* Setting 'slot' on an active array requires also
2768                  * updating the 'rd%d' link, and communicating
2769                  * with the personality with ->hot_*_disk.
2770                  * For now we only support removing
2771                  * failed/spare devices.  This normally happens automatically,
2772                  * but not when the metadata is externally managed.
2773                  */
2774                 if (rdev->raid_disk == -1)
2775                         return -EEXIST;
2776                 /* personality does all needed checks */
2777                 if (rdev->mddev->pers->hot_remove_disk == NULL)
2778                         return -EINVAL;
2779                 clear_bit(Blocked, &rdev->flags);
2780                 remove_and_add_spares(rdev->mddev, rdev);
2781                 if (rdev->raid_disk >= 0)
2782                         return -EBUSY;
2783                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2784                 md_wakeup_thread(rdev->mddev->thread);
2785         } else if (rdev->mddev->pers) {
2786                 /* Activating a spare .. or possibly reactivating
2787                  * if we ever get bitmaps working here.
2788                  */
2789
2790                 if (rdev->raid_disk != -1)
2791                         return -EBUSY;
2792
2793                 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2794                         return -EBUSY;
2795
2796                 if (rdev->mddev->pers->hot_add_disk == NULL)
2797                         return -EINVAL;
2798
2799                 if (slot >= rdev->mddev->raid_disks &&
2800                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2801                         return -ENOSPC;
2802
2803                 rdev->raid_disk = slot;
2804                 if (test_bit(In_sync, &rdev->flags))
2805                         rdev->saved_raid_disk = slot;
2806                 else
2807                         rdev->saved_raid_disk = -1;
2808                 clear_bit(In_sync, &rdev->flags);
2809                 clear_bit(Bitmap_sync, &rdev->flags);
2810                 err = rdev->mddev->pers->
2811                         hot_add_disk(rdev->mddev, rdev);
2812                 if (err) {
2813                         rdev->raid_disk = -1;
2814                         return err;
2815                 } else
2816                         sysfs_notify_dirent_safe(rdev->sysfs_state);
2817                 if (sysfs_link_rdev(rdev->mddev, rdev))
2818                         /* failure here is OK */;
2819                 /* don't wakeup anyone, leave that to userspace. */
2820         } else {
2821                 if (slot >= rdev->mddev->raid_disks &&
2822                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2823                         return -ENOSPC;
2824                 rdev->raid_disk = slot;
2825                 /* assume it is working */
2826                 clear_bit(Faulty, &rdev->flags);
2827                 clear_bit(WriteMostly, &rdev->flags);
2828                 set_bit(In_sync, &rdev->flags);
2829                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2830         }
2831         return len;
2832 }
2833
2834
2835 static struct rdev_sysfs_entry rdev_slot =
2836 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2837
2838 static ssize_t
2839 offset_show(struct md_rdev *rdev, char *page)
2840 {
2841         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2842 }
2843
2844 static ssize_t
2845 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
2846 {
2847         unsigned long long offset;
2848         if (kstrtoull(buf, 10, &offset) < 0)
2849                 return -EINVAL;
2850         if (rdev->mddev->pers && rdev->raid_disk >= 0)
2851                 return -EBUSY;
2852         if (rdev->sectors && rdev->mddev->external)
2853                 /* Must set offset before size, so overlap checks
2854                  * can be sane */
2855                 return -EBUSY;
2856         rdev->data_offset = offset;
2857         rdev->new_data_offset = offset;
2858         return len;
2859 }
2860
2861 static struct rdev_sysfs_entry rdev_offset =
2862 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2863
2864 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
2865 {
2866         return sprintf(page, "%llu\n",
2867                        (unsigned long long)rdev->new_data_offset);
2868 }
2869
2870 static ssize_t new_offset_store(struct md_rdev *rdev,
2871                                 const char *buf, size_t len)
2872 {
2873         unsigned long long new_offset;
2874         struct mddev *mddev = rdev->mddev;
2875
2876         if (kstrtoull(buf, 10, &new_offset) < 0)
2877                 return -EINVAL;
2878
2879         if (mddev->sync_thread)
2880                 return -EBUSY;
2881         if (new_offset == rdev->data_offset)
2882                 /* reset is always permitted */
2883                 ;
2884         else if (new_offset > rdev->data_offset) {
2885                 /* must not push array size beyond rdev_sectors */
2886                 if (new_offset - rdev->data_offset
2887                     + mddev->dev_sectors > rdev->sectors)
2888                                 return -E2BIG;
2889         }
2890         /* Metadata worries about other space details. */
2891
2892         /* decreasing the offset is inconsistent with a backwards
2893          * reshape.
2894          */
2895         if (new_offset < rdev->data_offset &&
2896             mddev->reshape_backwards)
2897                 return -EINVAL;
2898         /* Increasing offset is inconsistent with forwards
2899          * reshape.  reshape_direction should be set to
2900          * 'backwards' first.
2901          */
2902         if (new_offset > rdev->data_offset &&
2903             !mddev->reshape_backwards)
2904                 return -EINVAL;
2905
2906         if (mddev->pers && mddev->persistent &&
2907             !super_types[mddev->major_version]
2908             .allow_new_offset(rdev, new_offset))
2909                 return -E2BIG;
2910         rdev->new_data_offset = new_offset;
2911         if (new_offset > rdev->data_offset)
2912                 mddev->reshape_backwards = 1;
2913         else if (new_offset < rdev->data_offset)
2914                 mddev->reshape_backwards = 0;
2915
2916         return len;
2917 }
2918 static struct rdev_sysfs_entry rdev_new_offset =
2919 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
2920
2921 static ssize_t
2922 rdev_size_show(struct md_rdev *rdev, char *page)
2923 {
2924         return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
2925 }
2926
2927 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2928 {
2929         /* check if two start/length pairs overlap */
2930         if (s1+l1 <= s2)
2931                 return 0;
2932         if (s2+l2 <= s1)
2933                 return 0;
2934         return 1;
2935 }
2936
2937 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
2938 {
2939         unsigned long long blocks;
2940         sector_t new;
2941
2942         if (kstrtoull(buf, 10, &blocks) < 0)
2943                 return -EINVAL;
2944
2945         if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
2946                 return -EINVAL; /* sector conversion overflow */
2947
2948         new = blocks * 2;
2949         if (new != blocks * 2)
2950                 return -EINVAL; /* unsigned long long to sector_t overflow */
2951
2952         *sectors = new;
2953         return 0;
2954 }
2955
2956 static ssize_t
2957 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
2958 {
2959         struct mddev *my_mddev = rdev->mddev;
2960         sector_t oldsectors = rdev->sectors;
2961         sector_t sectors;
2962
2963         if (strict_blocks_to_sectors(buf, &sectors) < 0)
2964                 return -EINVAL;
2965         if (rdev->data_offset != rdev->new_data_offset)
2966                 return -EINVAL; /* too confusing */
2967         if (my_mddev->pers && rdev->raid_disk >= 0) {
2968                 if (my_mddev->persistent) {
2969                         sectors = super_types[my_mddev->major_version].
2970                                 rdev_size_change(rdev, sectors);
2971                         if (!sectors)
2972                                 return -EBUSY;
2973                 } else if (!sectors)
2974                         sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
2975                                 rdev->data_offset;
2976                 if (!my_mddev->pers->resize)
2977                         /* Cannot change size for RAID0 or Linear etc */
2978                         return -EINVAL;
2979         }
2980         if (sectors < my_mddev->dev_sectors)
2981                 return -EINVAL; /* component must fit device */
2982
2983         rdev->sectors = sectors;
2984         if (sectors > oldsectors && my_mddev->external) {
2985                 /* need to check that all other rdevs with the same ->bdev
2986                  * do not overlap.  We need to unlock the mddev to avoid
2987                  * a deadlock.  We have already changed rdev->sectors, and if
2988                  * we have to change it back, we will have the lock again.
2989                  */
2990                 struct mddev *mddev;
2991                 int overlap = 0;
2992                 struct list_head *tmp;
2993
2994                 mddev_unlock(my_mddev);
2995                 for_each_mddev(mddev, tmp) {
2996                         struct md_rdev *rdev2;
2997
2998                         mddev_lock_nointr(mddev);
2999                         rdev_for_each(rdev2, mddev)
3000                                 if (rdev->bdev == rdev2->bdev &&
3001                                     rdev != rdev2 &&
3002                                     overlaps(rdev->data_offset, rdev->sectors,
3003                                              rdev2->data_offset,
3004                                              rdev2->sectors)) {
3005                                         overlap = 1;
3006                                         break;
3007                                 }
3008                         mddev_unlock(mddev);
3009                         if (overlap) {
3010                                 mddev_put(mddev);
3011                                 break;
3012                         }
3013                 }
3014                 mddev_lock_nointr(my_mddev);
3015                 if (overlap) {
3016                         /* Someone else could have slipped in a size
3017                          * change here, but doing so is just silly.
3018                          * We put oldsectors back because we *know* it is
3019                          * safe, and trust userspace not to race with
3020                          * itself
3021                          */
3022                         rdev->sectors = oldsectors;
3023                         return -EBUSY;
3024                 }
3025         }
3026         return len;
3027 }
3028
3029 static struct rdev_sysfs_entry rdev_size =
3030 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
3031
3032
3033 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
3034 {
3035         unsigned long long recovery_start = rdev->recovery_offset;
3036
3037         if (test_bit(In_sync, &rdev->flags) ||
3038             recovery_start == MaxSector)
3039                 return sprintf(page, "none\n");
3040
3041         return sprintf(page, "%llu\n", recovery_start);
3042 }
3043
3044 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
3045 {
3046         unsigned long long recovery_start;
3047
3048         if (cmd_match(buf, "none"))
3049                 recovery_start = MaxSector;
3050         else if (kstrtoull(buf, 10, &recovery_start))
3051                 return -EINVAL;
3052
3053         if (rdev->mddev->pers &&
3054             rdev->raid_disk >= 0)
3055                 return -EBUSY;
3056
3057         rdev->recovery_offset = recovery_start;
3058         if (recovery_start == MaxSector)
3059                 set_bit(In_sync, &rdev->flags);
3060         else
3061                 clear_bit(In_sync, &rdev->flags);
3062         return len;
3063 }
3064
3065 static struct rdev_sysfs_entry rdev_recovery_start =
3066 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
3067
3068
3069 static ssize_t
3070 badblocks_show(struct badblocks *bb, char *page, int unack);
3071 static ssize_t
3072 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack);
3073
3074 static ssize_t bb_show(struct md_rdev *rdev, char *page)
3075 {
3076         return badblocks_show(&rdev->badblocks, page, 0);
3077 }
3078 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
3079 {
3080         int rv = badblocks_store(&rdev->badblocks, page, len, 0);
3081         /* Maybe that ack was all we needed */
3082         if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
3083                 wake_up(&rdev->blocked_wait);
3084         return rv;
3085 }
3086 static struct rdev_sysfs_entry rdev_bad_blocks =
3087 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
3088
3089
3090 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
3091 {
3092         return badblocks_show(&rdev->badblocks, page, 1);
3093 }
3094 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3095 {
3096         return badblocks_store(&rdev->badblocks, page, len, 1);
3097 }
3098 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3099 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3100
3101 static struct attribute *rdev_default_attrs[] = {
3102         &rdev_state.attr,
3103         &rdev_errors.attr,
3104         &rdev_slot.attr,
3105         &rdev_offset.attr,
3106         &rdev_new_offset.attr,
3107         &rdev_size.attr,
3108         &rdev_recovery_start.attr,
3109         &rdev_bad_blocks.attr,
3110         &rdev_unack_bad_blocks.attr,
3111         NULL,
3112 };
3113 static ssize_t
3114 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3115 {
3116         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3117         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3118         struct mddev *mddev = rdev->mddev;
3119         ssize_t rv;
3120
3121         if (!entry->show)
3122                 return -EIO;
3123
3124         rv = mddev ? mddev_lock(mddev) : -EBUSY;
3125         if (!rv) {
3126                 if (rdev->mddev == NULL)
3127                         rv = -EBUSY;
3128                 else
3129                         rv = entry->show(rdev, page);
3130                 mddev_unlock(mddev);
3131         }
3132         return rv;
3133 }
3134
3135 static ssize_t
3136 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3137               const char *page, size_t length)
3138 {
3139         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3140         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3141         ssize_t rv;
3142         struct mddev *mddev = rdev->mddev;
3143
3144         if (!entry->store)
3145                 return -EIO;
3146         if (!capable(CAP_SYS_ADMIN))
3147                 return -EACCES;
3148         rv = mddev ? mddev_lock(mddev): -EBUSY;
3149         if (!rv) {
3150                 if (rdev->mddev == NULL)
3151                         rv = -EBUSY;
3152                 else
3153                         rv = entry->store(rdev, page, length);
3154                 mddev_unlock(mddev);
3155         }
3156         return rv;
3157 }
3158
3159 static void rdev_free(struct kobject *ko)
3160 {
3161         struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3162         kfree(rdev);
3163 }
3164 static const struct sysfs_ops rdev_sysfs_ops = {
3165         .show           = rdev_attr_show,
3166         .store          = rdev_attr_store,
3167 };
3168 static struct kobj_type rdev_ktype = {
3169         .release        = rdev_free,
3170         .sysfs_ops      = &rdev_sysfs_ops,
3171         .default_attrs  = rdev_default_attrs,
3172 };
3173
3174 int md_rdev_init(struct md_rdev *rdev)
3175 {
3176         rdev->desc_nr = -1;
3177         rdev->saved_raid_disk = -1;
3178         rdev->raid_disk = -1;
3179         rdev->flags = 0;
3180         rdev->data_offset = 0;
3181         rdev->new_data_offset = 0;
3182         rdev->sb_events = 0;
3183         rdev->last_read_error.tv_sec  = 0;
3184         rdev->last_read_error.tv_nsec = 0;
3185         rdev->sb_loaded = 0;
3186         rdev->bb_page = NULL;
3187         atomic_set(&rdev->nr_pending, 0);
3188         atomic_set(&rdev->read_errors, 0);
3189         atomic_set(&rdev->corrected_errors, 0);
3190
3191         INIT_LIST_HEAD(&rdev->same_set);
3192         init_waitqueue_head(&rdev->blocked_wait);
3193
3194         /* Add space to store bad block list.
3195          * This reserves the space even on arrays where it cannot
3196          * be used - I wonder if that matters
3197          */
3198         rdev->badblocks.count = 0;
3199         rdev->badblocks.shift = -1; /* disabled until explicitly enabled */
3200         rdev->badblocks.page = kmalloc(PAGE_SIZE, GFP_KERNEL);
3201         seqlock_init(&rdev->badblocks.lock);
3202         if (rdev->badblocks.page == NULL)
3203                 return -ENOMEM;
3204
3205         return 0;
3206 }
3207 EXPORT_SYMBOL_GPL(md_rdev_init);
3208 /*
3209  * Import a device. If 'super_format' >= 0, then sanity check the superblock
3210  *
3211  * mark the device faulty if:
3212  *
3213  *   - the device is nonexistent (zero size)
3214  *   - the device has no valid superblock
3215  *
3216  * a faulty rdev _never_ has rdev->sb set.
3217  */
3218 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3219 {
3220         char b[BDEVNAME_SIZE];
3221         int err;
3222         struct md_rdev *rdev;
3223         sector_t size;
3224
3225         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3226         if (!rdev) {
3227                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
3228                 return ERR_PTR(-ENOMEM);
3229         }
3230
3231         err = md_rdev_init(rdev);
3232         if (err)
3233                 goto abort_free;
3234         err = alloc_disk_sb(rdev);
3235         if (err)
3236                 goto abort_free;
3237
3238         err = lock_rdev(rdev, newdev, super_format == -2);
3239         if (err)
3240                 goto abort_free;
3241
3242         kobject_init(&rdev->kobj, &rdev_ktype);
3243
3244         size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3245         if (!size) {
3246                 printk(KERN_WARNING 
3247                         "md: %s has zero or unknown size, marking faulty!\n",
3248                         bdevname(rdev->bdev,b));
3249                 err = -EINVAL;
3250                 goto abort_free;
3251         }
3252
3253         if (super_format >= 0) {
3254                 err = super_types[super_format].
3255                         load_super(rdev, NULL, super_minor);
3256                 if (err == -EINVAL) {
3257                         printk(KERN_WARNING
3258                                 "md: %s does not have a valid v%d.%d "
3259                                "superblock, not importing!\n",
3260                                 bdevname(rdev->bdev,b),
3261                                super_format, super_minor);
3262                         goto abort_free;
3263                 }
3264                 if (err < 0) {
3265                         printk(KERN_WARNING 
3266                                 "md: could not read %s's sb, not importing!\n",
3267                                 bdevname(rdev->bdev,b));
3268                         goto abort_free;
3269                 }
3270         }
3271
3272         return rdev;
3273
3274 abort_free:
3275         if (rdev->bdev)
3276                 unlock_rdev(rdev);
3277         md_rdev_clear(rdev);
3278         kfree(rdev);
3279         return ERR_PTR(err);
3280 }
3281
3282 /*
3283  * Check a full RAID array for plausibility
3284  */
3285
3286
3287 static void analyze_sbs(struct mddev * mddev)
3288 {
3289         int i;
3290         struct md_rdev *rdev, *freshest, *tmp;
3291         char b[BDEVNAME_SIZE];
3292
3293         freshest = NULL;
3294         rdev_for_each_safe(rdev, tmp, mddev)
3295                 switch (super_types[mddev->major_version].
3296                         load_super(rdev, freshest, mddev->minor_version)) {
3297                 case 1:
3298                         freshest = rdev;
3299                         break;
3300                 case 0:
3301                         break;
3302                 default:
3303                         printk( KERN_ERR \
3304                                 "md: fatal superblock inconsistency in %s"
3305                                 " -- removing from array\n", 
3306                                 bdevname(rdev->bdev,b));
3307                         kick_rdev_from_array(rdev);
3308                 }
3309
3310
3311         super_types[mddev->major_version].
3312                 validate_super(mddev, freshest);
3313
3314         i = 0;
3315         rdev_for_each_safe(rdev, tmp, mddev) {
3316                 if (mddev->max_disks &&
3317                     (rdev->desc_nr >= mddev->max_disks ||
3318                      i > mddev->max_disks)) {
3319                         printk(KERN_WARNING
3320                                "md: %s: %s: only %d devices permitted\n",
3321                                mdname(mddev), bdevname(rdev->bdev, b),
3322                                mddev->max_disks);
3323                         kick_rdev_from_array(rdev);
3324                         continue;
3325                 }
3326                 if (rdev != freshest)
3327                         if (super_types[mddev->major_version].
3328                             validate_super(mddev, rdev)) {
3329                                 printk(KERN_WARNING "md: kicking non-fresh %s"
3330                                         " from array!\n",
3331                                         bdevname(rdev->bdev,b));
3332                                 kick_rdev_from_array(rdev);
3333                                 continue;
3334                         }
3335                 if (mddev->level == LEVEL_MULTIPATH) {
3336                         rdev->desc_nr = i++;
3337                         rdev->raid_disk = rdev->desc_nr;
3338                         set_bit(In_sync, &rdev->flags);
3339                 } else if (rdev->raid_disk >= (mddev->raid_disks - min(0, mddev->delta_disks))) {
3340                         rdev->raid_disk = -1;
3341                         clear_bit(In_sync, &rdev->flags);
3342                 }
3343         }
3344 }
3345
3346 /* Read a fixed-point number.
3347  * Numbers in sysfs attributes should be in "standard" units where
3348  * possible, so time should be in seconds.
3349  * However we internally use a a much smaller unit such as 
3350  * milliseconds or jiffies.
3351  * This function takes a decimal number with a possible fractional
3352  * component, and produces an integer which is the result of
3353  * multiplying that number by 10^'scale'.
3354  * all without any floating-point arithmetic.
3355  */
3356 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3357 {
3358         unsigned long result = 0;
3359         long decimals = -1;
3360         while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3361                 if (*cp == '.')
3362                         decimals = 0;
3363                 else if (decimals < scale) {
3364                         unsigned int value;
3365                         value = *cp - '0';
3366                         result = result * 10 + value;
3367                         if (decimals >= 0)
3368                                 decimals++;
3369                 }
3370                 cp++;
3371         }
3372         if (*cp == '\n')
3373                 cp++;
3374         if (*cp)
3375                 return -EINVAL;
3376         if (decimals < 0)
3377                 decimals = 0;
3378         while (decimals < scale) {
3379                 result *= 10;
3380                 decimals ++;
3381         }
3382         *res = result;
3383         return 0;
3384 }
3385
3386
3387 static void md_safemode_timeout(unsigned long data);
3388
3389 static ssize_t
3390 safe_delay_show(struct mddev *mddev, char *page)
3391 {
3392         int msec = (mddev->safemode_delay*1000)/HZ;
3393         return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3394 }
3395 static ssize_t
3396 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3397 {
3398         unsigned long msec;
3399
3400         if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3401                 return -EINVAL;
3402         if (msec == 0)
3403                 mddev->safemode_delay = 0;
3404         else {
3405                 unsigned long old_delay = mddev->safemode_delay;
3406                 mddev->safemode_delay = (msec*HZ)/1000;
3407                 if (mddev->safemode_delay == 0)
3408                         mddev->safemode_delay = 1;
3409                 if (mddev->safemode_delay < old_delay || old_delay == 0)
3410                         md_safemode_timeout((unsigned long)mddev);
3411         }
3412         return len;
3413 }
3414 static struct md_sysfs_entry md_safe_delay =
3415 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3416
3417 static ssize_t
3418 level_show(struct mddev *mddev, char *page)
3419 {
3420         struct md_personality *p = mddev->pers;
3421         if (p)
3422                 return sprintf(page, "%s\n", p->name);
3423         else if (mddev->clevel[0])
3424                 return sprintf(page, "%s\n", mddev->clevel);
3425         else if (mddev->level != LEVEL_NONE)
3426                 return sprintf(page, "%d\n", mddev->level);
3427         else
3428                 return 0;
3429 }
3430
3431 static ssize_t
3432 level_store(struct mddev *mddev, const char *buf, size_t len)
3433 {
3434         char clevel[16];
3435         ssize_t rv = len;
3436         struct md_personality *pers;
3437         long level;
3438         void *priv;
3439         struct md_rdev *rdev;
3440
3441         if (mddev->pers == NULL) {
3442                 if (len == 0)
3443                         return 0;
3444                 if (len >= sizeof(mddev->clevel))
3445                         return -ENOSPC;
3446                 strncpy(mddev->clevel, buf, len);
3447                 if (mddev->clevel[len-1] == '\n')
3448                         len--;
3449                 mddev->clevel[len] = 0;
3450                 mddev->level = LEVEL_NONE;
3451                 return rv;
3452         }
3453
3454         /* request to change the personality.  Need to ensure:
3455          *  - array is not engaged in resync/recovery/reshape
3456          *  - old personality can be suspended
3457          *  - new personality will access other array.
3458          */
3459
3460         if (mddev->sync_thread ||
3461             mddev->reshape_position != MaxSector ||
3462             mddev->sysfs_active)
3463                 return -EBUSY;
3464
3465         if (!mddev->pers->quiesce) {
3466                 printk(KERN_WARNING "md: %s: %s does not support online personality change\n",
3467                        mdname(mddev), mddev->pers->name);
3468                 return -EINVAL;
3469         }
3470
3471         /* Now find the new personality */
3472         if (len == 0 || len >= sizeof(clevel))
3473                 return -EINVAL;
3474         strncpy(clevel, buf, len);
3475         if (clevel[len-1] == '\n')
3476                 len--;
3477         clevel[len] = 0;
3478         if (kstrtol(clevel, 10, &level))
3479                 level = LEVEL_NONE;
3480
3481         if (request_module("md-%s", clevel) != 0)
3482                 request_module("md-level-%s", clevel);
3483         spin_lock(&pers_lock);
3484         pers = find_pers(level, clevel);
3485         if (!pers || !try_module_get(pers->owner)) {
3486                 spin_unlock(&pers_lock);
3487                 printk(KERN_WARNING "md: personality %s not loaded\n", clevel);
3488                 return -EINVAL;
3489         }
3490         spin_unlock(&pers_lock);
3491
3492         if (pers == mddev->pers) {
3493                 /* Nothing to do! */
3494                 module_put(pers->owner);
3495                 return rv;
3496         }
3497         if (!pers->takeover) {
3498                 module_put(pers->owner);
3499                 printk(KERN_WARNING "md: %s: %s does not support personality takeover\n",
3500                        mdname(mddev), clevel);
3501                 return -EINVAL;
3502         }
3503
3504         rdev_for_each(rdev, mddev)
3505                 rdev->new_raid_disk = rdev->raid_disk;
3506
3507         /* ->takeover must set new_* and/or delta_disks
3508          * if it succeeds, and may set them when it fails.
3509          */
3510         priv = pers->takeover(mddev);
3511         if (IS_ERR(priv)) {
3512                 mddev->new_level = mddev->level;
3513                 mddev->new_layout = mddev->layout;
3514                 mddev->new_chunk_sectors = mddev->chunk_sectors;
3515                 mddev->raid_disks -= mddev->delta_disks;
3516                 mddev->delta_disks = 0;
3517                 mddev->reshape_backwards = 0;
3518                 module_put(pers->owner);
3519                 printk(KERN_WARNING "md: %s: %s would not accept array\n",
3520                        mdname(mddev), clevel);
3521                 return PTR_ERR(priv);
3522         }
3523
3524         /* Looks like we have a winner */
3525         mddev_suspend(mddev);
3526         mddev->pers->stop(mddev);
3527         
3528         if (mddev->pers->sync_request == NULL &&
3529             pers->sync_request != NULL) {
3530                 /* need to add the md_redundancy_group */
3531                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3532                         printk(KERN_WARNING
3533                                "md: cannot register extra attributes for %s\n",
3534                                mdname(mddev));
3535                 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action");
3536         }               
3537         if (mddev->pers->sync_request != NULL &&
3538             pers->sync_request == NULL) {
3539                 /* need to remove the md_redundancy_group */
3540                 if (mddev->to_remove == NULL)
3541                         mddev->to_remove = &md_redundancy_group;
3542         }
3543
3544         if (mddev->pers->sync_request == NULL &&
3545             mddev->external) {
3546                 /* We are converting from a no-redundancy array
3547                  * to a redundancy array and metadata is managed
3548                  * externally so we need to be sure that writes
3549                  * won't block due to a need to transition
3550                  *      clean->dirty
3551                  * until external management is started.
3552                  */
3553                 mddev->in_sync = 0;
3554                 mddev->safemode_delay = 0;
3555                 mddev->safemode = 0;
3556         }
3557
3558         rdev_for_each(rdev, mddev) {
3559                 if (rdev->raid_disk < 0)
3560                         continue;
3561                 if (rdev->new_raid_disk >= mddev->raid_disks)
3562                         rdev->new_raid_disk = -1;
3563                 if (rdev->new_raid_disk == rdev->raid_disk)
3564                         continue;
3565                 sysfs_unlink_rdev(mddev, rdev);
3566         }
3567         rdev_for_each(rdev, mddev) {
3568                 if (rdev->raid_disk < 0)
3569                         continue;
3570                 if (rdev->new_raid_disk == rdev->raid_disk)
3571                         continue;
3572                 rdev->raid_disk = rdev->new_raid_disk;
3573                 if (rdev->raid_disk < 0)
3574                         clear_bit(In_sync, &rdev->flags);
3575                 else {
3576                         if (sysfs_link_rdev(mddev, rdev))
3577                                 printk(KERN_WARNING "md: cannot register rd%d"
3578                                        " for %s after level change\n",
3579                                        rdev->raid_disk, mdname(mddev));
3580                 }
3581         }
3582
3583         module_put(mddev->pers->owner);
3584         mddev->pers = pers;
3585         mddev->private = priv;
3586         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3587         mddev->level = mddev->new_level;
3588         mddev->layout = mddev->new_layout;
3589         mddev->chunk_sectors = mddev->new_chunk_sectors;
3590         mddev->delta_disks = 0;
3591         mddev->reshape_backwards = 0;
3592         mddev->degraded = 0;
3593         if (mddev->pers->sync_request == NULL) {
3594                 /* this is now an array without redundancy, so
3595                  * it must always be in_sync
3596                  */
3597                 mddev->in_sync = 1;
3598                 del_timer_sync(&mddev->safemode_timer);
3599         }
3600         blk_set_stacking_limits(&mddev->queue->limits);
3601         pers->run(mddev);
3602         set_bit(MD_CHANGE_DEVS, &mddev->flags);
3603         mddev_resume(mddev);
3604         if (!mddev->thread)
3605                 md_update_sb(mddev, 1);
3606         sysfs_notify(&mddev->kobj, NULL, "level");
3607         md_new_event(mddev);
3608         return rv;
3609 }
3610
3611 static struct md_sysfs_entry md_level =
3612 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3613
3614
3615 static ssize_t
3616 layout_show(struct mddev *mddev, char *page)
3617 {
3618         /* just a number, not meaningful for all levels */
3619         if (mddev->reshape_position != MaxSector &&
3620             mddev->layout != mddev->new_layout)
3621                 return sprintf(page, "%d (%d)\n",
3622                                mddev->new_layout, mddev->layout);
3623         return sprintf(page, "%d\n", mddev->layout);
3624 }
3625
3626 static ssize_t
3627 layout_store(struct mddev *mddev, const char *buf, size_t len)
3628 {
3629         char *e;
3630         unsigned long n = simple_strtoul(buf, &e, 10);
3631
3632         if (!*buf || (*e && *e != '\n'))
3633                 return -EINVAL;
3634
3635         if (mddev->pers) {
3636                 int err;
3637                 if (mddev->pers->check_reshape == NULL)
3638                         return -EBUSY;
3639                 mddev->new_layout = n;
3640                 err = mddev->pers->check_reshape(mddev);
3641                 if (err) {
3642                         mddev->new_layout = mddev->layout;
3643                         return err;
3644                 }
3645         } else {
3646                 mddev->new_layout = n;
3647                 if (mddev->reshape_position == MaxSector)
3648                         mddev->layout = n;
3649         }
3650         return len;
3651 }
3652 static struct md_sysfs_entry md_layout =
3653 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3654
3655
3656 static ssize_t
3657 raid_disks_show(struct mddev *mddev, char *page)
3658 {
3659         if (mddev->raid_disks == 0)
3660                 return 0;
3661         if (mddev->reshape_position != MaxSector &&
3662             mddev->delta_disks != 0)
3663                 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3664                                mddev->raid_disks - mddev->delta_disks);
3665         return sprintf(page, "%d\n", mddev->raid_disks);
3666 }
3667
3668 static int update_raid_disks(struct mddev *mddev, int raid_disks);
3669
3670 static ssize_t
3671 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
3672 {
3673         char *e;
3674         int rv = 0;
3675         unsigned long n = simple_strtoul(buf, &e, 10);
3676
3677         if (!*buf || (*e && *e != '\n'))
3678                 return -EINVAL;
3679
3680         if (mddev->pers)
3681                 rv = update_raid_disks(mddev, n);
3682         else if (mddev->reshape_position != MaxSector) {
3683                 struct md_rdev *rdev;
3684                 int olddisks = mddev->raid_disks - mddev->delta_disks;
3685
3686                 rdev_for_each(rdev, mddev) {
3687                         if (olddisks < n &&
3688                             rdev->data_offset < rdev->new_data_offset)
3689                                 return -EINVAL;
3690                         if (olddisks > n &&
3691                             rdev->data_offset > rdev->new_data_offset)
3692                                 return -EINVAL;
3693                 }
3694                 mddev->delta_disks = n - olddisks;
3695                 mddev->raid_disks = n;
3696                 mddev->reshape_backwards = (mddev->delta_disks < 0);
3697         } else
3698                 mddev->raid_disks = n;
3699         return rv ? rv : len;
3700 }
3701 static struct md_sysfs_entry md_raid_disks =
3702 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3703
3704 static ssize_t
3705 chunk_size_show(struct mddev *mddev, char *page)
3706 {
3707         if (mddev->reshape_position != MaxSector &&
3708             mddev->chunk_sectors != mddev->new_chunk_sectors)
3709                 return sprintf(page, "%d (%d)\n",
3710                                mddev->new_chunk_sectors << 9,
3711                                mddev->chunk_sectors << 9);
3712         return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3713 }
3714
3715 static ssize_t
3716 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
3717 {
3718         char *e;
3719         unsigned long n = simple_strtoul(buf, &e, 10);
3720
3721         if (!*buf || (*e && *e != '\n'))
3722                 return -EINVAL;
3723
3724         if (mddev->pers) {
3725                 int err;
3726                 if (mddev->pers->check_reshape == NULL)
3727                         return -EBUSY;
3728                 mddev->new_chunk_sectors = n >> 9;
3729                 err = mddev->pers->check_reshape(mddev);
3730                 if (err) {
3731                         mddev->new_chunk_sectors = mddev->chunk_sectors;
3732                         return err;
3733                 }
3734         } else {
3735                 mddev->new_chunk_sectors = n >> 9;
3736                 if (mddev->reshape_position == MaxSector)
3737                         mddev->chunk_sectors = n >> 9;
3738         }
3739         return len;
3740 }
3741 static struct md_sysfs_entry md_chunk_size =
3742 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
3743
3744 static ssize_t
3745 resync_start_show(struct mddev *mddev, char *page)
3746 {
3747         if (mddev->recovery_cp == MaxSector)
3748                 return sprintf(page, "none\n");
3749         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
3750 }
3751
3752 static ssize_t
3753 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
3754 {
3755         char *e;
3756         unsigned long long n = simple_strtoull(buf, &e, 10);
3757
3758         if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3759                 return -EBUSY;
3760         if (cmd_match(buf, "none"))
3761                 n = MaxSector;
3762         else if (!*buf || (*e && *e != '\n'))
3763                 return -EINVAL;
3764
3765         mddev->recovery_cp = n;
3766         if (mddev->pers)
3767                 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3768         return len;
3769 }
3770 static struct md_sysfs_entry md_resync_start =
3771 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
3772
3773 /*
3774  * The array state can be:
3775  *
3776  * clear
3777  *     No devices, no size, no level
3778  *     Equivalent to STOP_ARRAY ioctl
3779  * inactive
3780  *     May have some settings, but array is not active
3781  *        all IO results in error
3782  *     When written, doesn't tear down array, but just stops it
3783  * suspended (not supported yet)
3784  *     All IO requests will block. The array can be reconfigured.
3785  *     Writing this, if accepted, will block until array is quiescent
3786  * readonly
3787  *     no resync can happen.  no superblocks get written.
3788  *     write requests fail
3789  * read-auto
3790  *     like readonly, but behaves like 'clean' on a write request.
3791  *
3792  * clean - no pending writes, but otherwise active.
3793  *     When written to inactive array, starts without resync
3794  *     If a write request arrives then
3795  *       if metadata is known, mark 'dirty' and switch to 'active'.
3796  *       if not known, block and switch to write-pending
3797  *     If written to an active array that has pending writes, then fails.
3798  * active
3799  *     fully active: IO and resync can be happening.
3800  *     When written to inactive array, starts with resync
3801  *
3802  * write-pending
3803  *     clean, but writes are blocked waiting for 'active' to be written.
3804  *
3805  * active-idle
3806  *     like active, but no writes have been seen for a while (100msec).
3807  *
3808  */
3809 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
3810                    write_pending, active_idle, bad_word};
3811 static char *array_states[] = {
3812         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
3813         "write-pending", "active-idle", NULL };
3814
3815 static int match_word(const char *word, char **list)
3816 {
3817         int n;
3818         for (n=0; list[n]; n++)
3819                 if (cmd_match(word, list[n]))
3820                         break;
3821         return n;
3822 }
3823
3824 static ssize_t
3825 array_state_show(struct mddev *mddev, char *page)
3826 {
3827         enum array_state st = inactive;
3828
3829         if (mddev->pers)
3830                 switch(mddev->ro) {
3831                 case 1:
3832                         st = readonly;
3833                         break;
3834                 case 2:
3835                         st = read_auto;
3836                         break;
3837                 case 0:
3838                         if (mddev->in_sync)
3839                                 st = clean;
3840                         else if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
3841                                 st = write_pending;
3842                         else if (mddev->safemode)
3843                                 st = active_idle;
3844                         else
3845                                 st = active;
3846                 }
3847         else {
3848                 if (list_empty(&mddev->disks) &&
3849                     mddev->raid_disks == 0 &&
3850                     mddev->dev_sectors == 0)
3851                         st = clear;
3852                 else
3853                         st = inactive;
3854         }
3855         return sprintf(page, "%s\n", array_states[st]);
3856 }
3857
3858 static int do_md_stop(struct mddev * mddev, int ro, struct block_device *bdev);
3859 static int md_set_readonly(struct mddev * mddev, struct block_device *bdev);
3860 static int do_md_run(struct mddev * mddev);
3861 static int restart_array(struct mddev *mddev);
3862
3863 static ssize_t
3864 array_state_store(struct mddev *mddev, const char *buf, size_t len)
3865 {
3866         int err = -EINVAL;
3867         enum array_state st = match_word(buf, array_states);
3868         switch(st) {
3869         case bad_word:
3870                 break;
3871         case clear:
3872                 /* stopping an active array */
3873                 err = do_md_stop(mddev, 0, NULL);
3874                 break;
3875         case inactive:
3876                 /* stopping an active array */
3877                 if (mddev->pers)
3878                         err = do_md_stop(mddev, 2, NULL);
3879                 else
3880                         err = 0; /* already inactive */
3881                 break;
3882         case suspended:
3883                 break; /* not supported yet */
3884         case readonly:
3885                 if (mddev->pers)
3886                         err = md_set_readonly(mddev, NULL);
3887                 else {
3888                         mddev->ro = 1;
3889                         set_disk_ro(mddev->gendisk, 1);
3890                         err = do_md_run(mddev);
3891                 }
3892                 break;
3893         case read_auto:
3894                 if (mddev->pers) {
3895                         if (mddev->ro == 0)
3896                                 err = md_set_readonly(mddev, NULL);
3897                         else if (mddev->ro == 1)
3898                                 err = restart_array(mddev);
3899                         if (err == 0) {
3900                                 mddev->ro = 2;
3901                                 set_disk_ro(mddev->gendisk, 0);
3902                         }
3903                 } else {
3904                         mddev->ro = 2;
3905                         err = do_md_run(mddev);
3906                 }
3907                 break;
3908         case clean:
3909                 if (mddev->pers) {
3910                         restart_array(mddev);
3911                         spin_lock_irq(&mddev->write_lock);
3912                         if (atomic_read(&mddev->writes_pending) == 0) {
3913                                 if (mddev->in_sync == 0) {
3914                                         mddev->in_sync = 1;
3915                                         if (mddev->safemode == 1)
3916                                                 mddev->safemode = 0;
3917                                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3918                                 }
3919                                 err = 0;
3920                         } else
3921                                 err = -EBUSY;
3922                         spin_unlock_irq(&mddev->write_lock);
3923                 } else
3924                         err = -EINVAL;
3925                 break;
3926         case active:
3927                 if (mddev->pers) {
3928                         restart_array(mddev);
3929                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3930                         wake_up(&mddev->sb_wait);
3931                         err = 0;
3932                 } else {
3933                         mddev->ro = 0;
3934                         set_disk_ro(mddev->gendisk, 0);
3935                         err = do_md_run(mddev);
3936                 }
3937                 break;
3938         case write_pending:
3939         case active_idle:
3940                 /* these cannot be set */
3941                 break;
3942         }
3943         if (err)
3944                 return err;
3945         else {
3946                 if (mddev->hold_active == UNTIL_IOCTL)
3947                         mddev->hold_active = 0;
3948                 sysfs_notify_dirent_safe(mddev->sysfs_state);
3949                 return len;
3950         }
3951 }
3952 static struct md_sysfs_entry md_array_state =
3953 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3954
3955 static ssize_t
3956 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
3957         return sprintf(page, "%d\n",
3958                        atomic_read(&mddev->max_corr_read_errors));
3959 }
3960
3961 static ssize_t
3962 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
3963 {
3964         char *e;
3965         unsigned long n = simple_strtoul(buf, &e, 10);
3966
3967         if (*buf && (*e == 0 || *e == '\n')) {
3968                 atomic_set(&mddev->max_corr_read_errors, n);
3969                 return len;
3970         }
3971         return -EINVAL;
3972 }
3973
3974 static struct md_sysfs_entry max_corr_read_errors =
3975 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
3976         max_corrected_read_errors_store);
3977
3978 static ssize_t
3979 null_show(struct mddev *mddev, char *page)
3980 {
3981         return -EINVAL;
3982 }
3983
3984 static ssize_t
3985 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
3986 {
3987         /* buf must be %d:%d\n? giving major and minor numbers */
3988         /* The new device is added to the array.
3989          * If the array has a persistent superblock, we read the
3990          * superblock to initialise info and check validity.
3991          * Otherwise, only checking done is that in bind_rdev_to_array,
3992          * which mainly checks size.
3993          */
3994         char *e;
3995         int major = simple_strtoul(buf, &e, 10);
3996         int minor;
3997         dev_t dev;
3998         struct md_rdev *rdev;
3999         int err;
4000
4001         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
4002                 return -EINVAL;
4003         minor = simple_strtoul(e+1, &e, 10);
4004         if (*e && *e != '\n')
4005                 return -EINVAL;
4006         dev = MKDEV(major, minor);
4007         if (major != MAJOR(dev) ||
4008             minor != MINOR(dev))
4009                 return -EOVERFLOW;
4010
4011
4012         if (mddev->persistent) {
4013                 rdev = md_import_device(dev, mddev->major_version,
4014                                         mddev->minor_version);
4015                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
4016                         struct md_rdev *rdev0
4017                                 = list_entry(mddev->disks.next,
4018                                              struct md_rdev, same_set);
4019                         err = super_types[mddev->major_version]
4020                                 .load_super(rdev, rdev0, mddev->minor_version);
4021                         if (err < 0)
4022                                 goto out;
4023                 }
4024         } else if (mddev->external)
4025                 rdev = md_import_device(dev, -2, -1);
4026         else
4027                 rdev = md_import_device(dev, -1, -1);
4028
4029         if (IS_ERR(rdev))
4030                 return PTR_ERR(rdev);
4031         err = bind_rdev_to_array(rdev, mddev);
4032  out:
4033         if (err)
4034                 export_rdev(rdev);
4035         return err ? err : len;
4036 }
4037
4038 static struct md_sysfs_entry md_new_device =
4039 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
4040
4041 static ssize_t
4042 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
4043 {
4044         char *end;
4045         unsigned long chunk, end_chunk;
4046
4047         if (!mddev->bitmap)
4048                 goto out;
4049         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
4050         while (*buf) {
4051                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
4052                 if (buf == end) break;
4053                 if (*end == '-') { /* range */
4054                         buf = end + 1;
4055                         end_chunk = simple_strtoul(buf, &end, 0);
4056                         if (buf == end) break;
4057                 }
4058                 if (*end && !isspace(*end)) break;
4059                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
4060                 buf = skip_spaces(end);
4061         }
4062         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
4063 out:
4064         return len;
4065 }
4066
4067 static struct md_sysfs_entry md_bitmap =
4068 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
4069
4070 static ssize_t
4071 size_show(struct mddev *mddev, char *page)
4072 {
4073         return sprintf(page, "%llu\n",
4074                 (unsigned long long)mddev->dev_sectors / 2);
4075 }
4076
4077 static int update_size(struct mddev *mddev, sector_t num_sectors);
4078
4079 static ssize_t
4080 size_store(struct mddev *mddev, const char *buf, size_t len)
4081 {
4082         /* If array is inactive, we can reduce the component size, but
4083          * not increase it (except from 0).
4084          * If array is active, we can try an on-line resize
4085          */
4086         sector_t sectors;
4087         int err = strict_blocks_to_sectors(buf, &sectors);
4088
4089         if (err < 0)
4090                 return err;
4091         if (mddev->pers) {
4092                 err = update_size(mddev, sectors);
4093                 md_update_sb(mddev, 1);
4094         } else {
4095                 if (mddev->dev_sectors == 0 ||
4096                     mddev->dev_sectors > sectors)
4097                         mddev->dev_sectors = sectors;
4098                 else
4099                         err = -ENOSPC;
4100         }
4101         return err ? err : len;
4102 }
4103
4104 static struct md_sysfs_entry md_size =
4105 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4106
4107
4108 /* Metadata version.
4109  * This is one of
4110  *   'none' for arrays with no metadata (good luck...)
4111  *   'external' for arrays with externally managed metadata,
4112  * or N.M for internally known formats
4113  */
4114 static ssize_t
4115 metadata_show(struct mddev *mddev, char *page)
4116 {
4117         if (mddev->persistent)
4118                 return sprintf(page, "%d.%d\n",
4119                                mddev->major_version, mddev->minor_version);
4120         else if (mddev->external)
4121                 return sprintf(page, "external:%s\n", mddev->metadata_type);
4122         else
4123                 return sprintf(page, "none\n");
4124 }
4125
4126 static ssize_t
4127 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4128 {
4129         int major, minor;
4130         char *e;
4131         /* Changing the details of 'external' metadata is
4132          * always permitted.  Otherwise there must be
4133          * no devices attached to the array.
4134          */
4135         if (mddev->external && strncmp(buf, "external:", 9) == 0)
4136                 ;
4137         else if (!list_empty(&mddev->disks))
4138                 return -EBUSY;
4139
4140         if (cmd_match(buf, "none")) {
4141                 mddev->persistent = 0;
4142                 mddev->external = 0;
4143                 mddev->major_version = 0;
4144                 mddev->minor_version = 90;
4145                 return len;
4146         }
4147         if (strncmp(buf, "external:", 9) == 0) {
4148                 size_t namelen = len-9;
4149                 if (namelen >= sizeof(mddev->metadata_type))
4150                         namelen = sizeof(mddev->metadata_type)-1;
4151                 strncpy(mddev->metadata_type, buf+9, namelen);
4152                 mddev->metadata_type[namelen] = 0;
4153                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
4154                         mddev->metadata_type[--namelen] = 0;
4155                 mddev->persistent = 0;
4156                 mddev->external = 1;
4157                 mddev->major_version = 0;
4158                 mddev->minor_version = 90;
4159                 return len;
4160         }
4161         major = simple_strtoul(buf, &e, 10);
4162         if (e==buf || *e != '.')
4163                 return -EINVAL;
4164         buf = e+1;
4165         minor = simple_strtoul(buf, &e, 10);
4166         if (e==buf || (*e && *e != '\n') )
4167                 return -EINVAL;
4168         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4169                 return -ENOENT;
4170         mddev->major_version = major;
4171         mddev->minor_version = minor;
4172         mddev->persistent = 1;
4173         mddev->external = 0;
4174         return len;
4175 }
4176
4177 static struct md_sysfs_entry md_metadata =
4178 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4179
4180 static ssize_t
4181 action_show(struct mddev *mddev, char *page)
4182 {
4183         char *type = "idle";
4184         if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4185                 type = "frozen";
4186         else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4187             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
4188                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4189                         type = "reshape";
4190                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4191                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
4192                                 type = "resync";
4193                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
4194                                 type = "check";
4195                         else
4196                                 type = "repair";
4197                 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
4198                         type = "recover";
4199         }
4200         return sprintf(page, "%s\n", type);
4201 }
4202
4203 static ssize_t
4204 action_store(struct mddev *mddev, const char *page, size_t len)
4205 {
4206         if (!mddev->pers || !mddev->pers->sync_request)
4207                 return -EINVAL;
4208
4209         if (cmd_match(page, "frozen"))
4210                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4211         else
4212                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4213
4214         if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4215                 if (mddev->sync_thread) {
4216                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4217                         md_reap_sync_thread(mddev);
4218                 }
4219         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4220                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
4221                 return -EBUSY;
4222         else if (cmd_match(page, "resync"))
4223                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4224         else if (cmd_match(page, "recover")) {
4225                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4226                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4227         } else if (cmd_match(page, "reshape")) {
4228                 int err;
4229                 if (mddev->pers->start_reshape == NULL)
4230                         return -EINVAL;
4231                 err = mddev->pers->start_reshape(mddev);
4232                 if (err)
4233                         return err;
4234                 sysfs_notify(&mddev->kobj, NULL, "degraded");
4235         } else {
4236                 if (cmd_match(page, "check"))
4237                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4238                 else if (!cmd_match(page, "repair"))
4239                         return -EINVAL;
4240                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4241                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4242         }
4243         if (mddev->ro == 2) {
4244                 /* A write to sync_action is enough to justify
4245                  * canceling read-auto mode
4246                  */
4247                 mddev->ro = 0;
4248                 md_wakeup_thread(mddev->sync_thread);
4249         }
4250         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4251         md_wakeup_thread(mddev->thread);
4252         sysfs_notify_dirent_safe(mddev->sysfs_action);
4253         return len;
4254 }
4255
4256 static struct md_sysfs_entry md_scan_mode =
4257 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4258
4259 static ssize_t
4260 last_sync_action_show(struct mddev *mddev, char *page)
4261 {
4262         return sprintf(page, "%s\n", mddev->last_sync_action);
4263 }
4264
4265 static struct md_sysfs_entry md_last_scan_mode = __ATTR_RO(last_sync_action);
4266
4267 static ssize_t
4268 mismatch_cnt_show(struct mddev *mddev, char *page)
4269 {
4270         return sprintf(page, "%llu\n",
4271                        (unsigned long long)
4272                        atomic64_read(&mddev->resync_mismatches));
4273 }
4274
4275 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4276
4277 static ssize_t
4278 sync_min_show(struct mddev *mddev, char *page)
4279 {
4280         return sprintf(page, "%d (%s)\n", speed_min(mddev),
4281                        mddev->sync_speed_min ? "local": "system");
4282 }
4283
4284 static ssize_t
4285 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4286 {
4287         int min;
4288         char *e;
4289         if (strncmp(buf, "system", 6)==0) {
4290                 mddev->sync_speed_min = 0;
4291                 return len;
4292         }
4293         min = simple_strtoul(buf, &e, 10);
4294         if (buf == e || (*e && *e != '\n') || min <= 0)
4295                 return -EINVAL;
4296         mddev->sync_speed_min = min;
4297         return len;
4298 }
4299
4300 static struct md_sysfs_entry md_sync_min =
4301 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4302
4303 static ssize_t
4304 sync_max_show(struct mddev *mddev, char *page)
4305 {
4306         return sprintf(page, "%d (%s)\n", speed_max(mddev),
4307                        mddev->sync_speed_max ? "local": "system");
4308 }
4309
4310 static ssize_t
4311 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4312 {
4313         int max;
4314         char *e;
4315         if (strncmp(buf, "system", 6)==0) {
4316                 mddev->sync_speed_max = 0;
4317                 return len;
4318         }
4319         max = simple_strtoul(buf, &e, 10);
4320         if (buf == e || (*e && *e != '\n') || max <= 0)
4321                 return -EINVAL;
4322         mddev->sync_speed_max = max;
4323         return len;
4324 }
4325
4326 static struct md_sysfs_entry md_sync_max =
4327 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4328
4329 static ssize_t
4330 degraded_show(struct mddev *mddev, char *page)
4331 {
4332         return sprintf(page, "%d\n", mddev->degraded);
4333 }
4334 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4335
4336 static ssize_t
4337 sync_force_parallel_show(struct mddev *mddev, char *page)
4338 {
4339         return sprintf(page, "%d\n", mddev->parallel_resync);
4340 }
4341
4342 static ssize_t
4343 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4344 {
4345         long n;
4346
4347         if (kstrtol(buf, 10, &n))
4348                 return -EINVAL;
4349
4350         if (n != 0 && n != 1)
4351                 return -EINVAL;
4352
4353         mddev->parallel_resync = n;
4354
4355         if (mddev->sync_thread)
4356                 wake_up(&resync_wait);
4357
4358         return len;
4359 }
4360
4361 /* force parallel resync, even with shared block devices */
4362 static struct md_sysfs_entry md_sync_force_parallel =
4363 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4364        sync_force_parallel_show, sync_force_parallel_store);
4365
4366 static ssize_t
4367 sync_speed_show(struct mddev *mddev, char *page)
4368 {
4369         unsigned long resync, dt, db;
4370         if (mddev->curr_resync == 0)
4371                 return sprintf(page, "none\n");
4372         resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4373         dt = (jiffies - mddev->resync_mark) / HZ;
4374         if (!dt) dt++;
4375         db = resync - mddev->resync_mark_cnt;
4376         return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4377 }
4378
4379 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4380
4381 static ssize_t
4382 sync_completed_show(struct mddev *mddev, char *page)
4383 {
4384         unsigned long long max_sectors, resync;
4385
4386         if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4387                 return sprintf(page, "none\n");
4388
4389         if (mddev->curr_resync == 1 ||
4390             mddev->curr_resync == 2)
4391                 return sprintf(page, "delayed\n");
4392
4393         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
4394             test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4395                 max_sectors = mddev->resync_max_sectors;
4396         else
4397                 max_sectors = mddev->dev_sectors;
4398
4399         resync = mddev->curr_resync_completed;
4400         return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4401 }
4402
4403 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
4404
4405 static ssize_t
4406 min_sync_show(struct mddev *mddev, char *page)
4407 {
4408         return sprintf(page, "%llu\n",
4409                        (unsigned long long)mddev->resync_min);
4410 }
4411 static ssize_t
4412 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4413 {
4414         unsigned long long min;
4415         if (kstrtoull(buf, 10, &min))
4416                 return -EINVAL;
4417         if (min > mddev->resync_max)
4418                 return -EINVAL;
4419         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4420                 return -EBUSY;
4421
4422         /* Must be a multiple of chunk_size */
4423         if (mddev->chunk_sectors) {
4424                 sector_t temp = min;
4425                 if (sector_div(temp, mddev->chunk_sectors))
4426                         return -EINVAL;
4427         }
4428         mddev->resync_min = min;
4429
4430         return len;
4431 }
4432
4433 static struct md_sysfs_entry md_min_sync =
4434 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4435
4436 static ssize_t
4437 max_sync_show(struct mddev *mddev, char *page)
4438 {
4439         if (mddev->resync_max == MaxSector)
4440                 return sprintf(page, "max\n");
4441         else
4442                 return sprintf(page, "%llu\n",
4443                                (unsigned long long)mddev->resync_max);
4444 }
4445 static ssize_t
4446 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4447 {
4448         if (strncmp(buf, "max", 3) == 0)
4449                 mddev->resync_max = MaxSector;
4450         else {
4451                 unsigned long long max;
4452                 if (kstrtoull(buf, 10, &max))
4453                         return -EINVAL;
4454                 if (max < mddev->resync_min)
4455                         return -EINVAL;
4456                 if (max < mddev->resync_max &&
4457                     mddev->ro == 0 &&
4458                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4459                         return -EBUSY;
4460
4461                 /* Must be a multiple of chunk_size */
4462                 if (mddev->chunk_sectors) {
4463                         sector_t temp = max;
4464                         if (sector_div(temp, mddev->chunk_sectors))
4465                                 return -EINVAL;
4466                 }
4467                 mddev->resync_max = max;
4468         }
4469         wake_up(&mddev->recovery_wait);
4470         return len;
4471 }
4472
4473 static struct md_sysfs_entry md_max_sync =
4474 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4475
4476 static ssize_t
4477 suspend_lo_show(struct mddev *mddev, char *page)
4478 {
4479         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4480 }
4481
4482 static ssize_t
4483 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
4484 {
4485         char *e;
4486         unsigned long long new = simple_strtoull(buf, &e, 10);
4487         unsigned long long old = mddev->suspend_lo;
4488
4489         if (mddev->pers == NULL || 
4490             mddev->pers->quiesce == NULL)
4491                 return -EINVAL;
4492         if (buf == e || (*e && *e != '\n'))
4493                 return -EINVAL;
4494
4495         mddev->suspend_lo = new;
4496         if (new >= old)
4497                 /* Shrinking suspended region */
4498                 mddev->pers->quiesce(mddev, 2);
4499         else {
4500                 /* Expanding suspended region - need to wait */
4501                 mddev->pers->quiesce(mddev, 1);
4502                 mddev->pers->quiesce(mddev, 0);
4503         }
4504         return len;
4505 }
4506 static struct md_sysfs_entry md_suspend_lo =
4507 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4508
4509
4510 static ssize_t
4511 suspend_hi_show(struct mddev *mddev, char *page)
4512 {
4513         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4514 }
4515
4516 static ssize_t
4517 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
4518 {
4519         char *e;
4520         unsigned long long new = simple_strtoull(buf, &e, 10);
4521         unsigned long long old = mddev->suspend_hi;
4522
4523         if (mddev->pers == NULL ||
4524             mddev->pers->quiesce == NULL)
4525                 return -EINVAL;
4526         if (buf == e || (*e && *e != '\n'))
4527                 return -EINVAL;
4528
4529         mddev->suspend_hi = new;
4530         if (new <= old)
4531                 /* Shrinking suspended region */
4532                 mddev->pers->quiesce(mddev, 2);
4533         else {
4534                 /* Expanding suspended region - need to wait */
4535                 mddev->pers->quiesce(mddev, 1);
4536                 mddev->pers->quiesce(mddev, 0);
4537         }
4538         return len;
4539 }
4540 static struct md_sysfs_entry md_suspend_hi =
4541 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4542
4543 static ssize_t
4544 reshape_position_show(struct mddev *mddev, char *page)
4545 {
4546         if (mddev->reshape_position != MaxSector)
4547                 return sprintf(page, "%llu\n",
4548                                (unsigned long long)mddev->reshape_position);
4549         strcpy(page, "none\n");
4550         return 5;
4551 }
4552
4553 static ssize_t
4554 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
4555 {
4556         struct md_rdev *rdev;
4557         char *e;
4558         unsigned long long new = simple_strtoull(buf, &e, 10);
4559         if (mddev->pers)
4560                 return -EBUSY;
4561         if (buf == e || (*e && *e != '\n'))
4562                 return -EINVAL;
4563         mddev->reshape_position = new;
4564         mddev->delta_disks = 0;
4565         mddev->reshape_backwards = 0;
4566         mddev->new_level = mddev->level;
4567         mddev->new_layout = mddev->layout;
4568         mddev->new_chunk_sectors = mddev->chunk_sectors;
4569         rdev_for_each(rdev, mddev)
4570                 rdev->new_data_offset = rdev->data_offset;
4571         return len;
4572 }
4573
4574 static struct md_sysfs_entry md_reshape_position =
4575 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4576        reshape_position_store);
4577
4578 static ssize_t
4579 reshape_direction_show(struct mddev *mddev, char *page)
4580 {
4581         return sprintf(page, "%s\n",
4582                        mddev->reshape_backwards ? "backwards" : "forwards");
4583 }
4584
4585 static ssize_t
4586 reshape_direction_store(struct mddev *mddev, const char *buf, size_t len)
4587 {
4588         int backwards = 0;
4589         if (cmd_match(buf, "forwards"))
4590                 backwards = 0;
4591         else if (cmd_match(buf, "backwards"))
4592                 backwards = 1;
4593         else
4594                 return -EINVAL;
4595         if (mddev->reshape_backwards == backwards)
4596                 return len;
4597
4598         /* check if we are allowed to change */
4599         if (mddev->delta_disks)
4600                 return -EBUSY;
4601
4602         if (mddev->persistent &&
4603             mddev->major_version == 0)
4604                 return -EINVAL;
4605
4606         mddev->reshape_backwards = backwards;
4607         return len;
4608 }
4609
4610 static struct md_sysfs_entry md_reshape_direction =
4611 __ATTR(reshape_direction, S_IRUGO|S_IWUSR, reshape_direction_show,
4612        reshape_direction_store);
4613
4614 static ssize_t
4615 array_size_show(struct mddev *mddev, char *page)
4616 {
4617         if (mddev->external_size)
4618                 return sprintf(page, "%llu\n",
4619                                (unsigned long long)mddev->array_sectors/2);
4620         else
4621                 return sprintf(page, "default\n");
4622 }
4623
4624 static ssize_t
4625 array_size_store(struct mddev *mddev, const char *buf, size_t len)
4626 {
4627         sector_t sectors;
4628
4629         if (strncmp(buf, "default", 7) == 0) {
4630                 if (mddev->pers)
4631                         sectors = mddev->pers->size(mddev, 0, 0);
4632                 else
4633                         sectors = mddev->array_sectors;
4634
4635                 mddev->external_size = 0;
4636         } else {
4637                 if (strict_blocks_to_sectors(buf, &sectors) < 0)
4638                         return -EINVAL;
4639                 if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
4640                         return -E2BIG;
4641
4642                 mddev->external_size = 1;
4643         }
4644
4645         mddev->array_sectors = sectors;
4646         if (mddev->pers) {
4647                 set_capacity(mddev->gendisk, mddev->array_sectors);
4648                 revalidate_disk(mddev->gendisk);
4649         }
4650         return len;
4651 }
4652
4653 static struct md_sysfs_entry md_array_size =
4654 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
4655        array_size_store);
4656
4657 static struct attribute *md_default_attrs[] = {
4658         &md_level.attr,
4659         &md_layout.attr,
4660         &md_raid_disks.attr,
4661         &md_chunk_size.attr,
4662         &md_size.attr,
4663         &md_resync_start.attr,
4664         &md_metadata.attr,
4665         &md_new_device.attr,
4666         &md_safe_delay.attr,
4667         &md_array_state.attr,
4668         &md_reshape_position.attr,
4669         &md_reshape_direction.attr,
4670         &md_array_size.attr,
4671         &max_corr_read_errors.attr,
4672         NULL,
4673 };
4674
4675 static struct attribute *md_redundancy_attrs[] = {
4676         &md_scan_mode.attr,
4677         &md_last_scan_mode.attr,
4678         &md_mismatches.attr,
4679         &md_sync_min.attr,
4680         &md_sync_max.attr,
4681         &md_sync_speed.attr,
4682         &md_sync_force_parallel.attr,
4683         &md_sync_completed.attr,
4684         &md_min_sync.attr,
4685         &md_max_sync.attr,
4686         &md_suspend_lo.attr,
4687         &md_suspend_hi.attr,
4688         &md_bitmap.attr,
4689         &md_degraded.attr,
4690         NULL,
4691 };
4692 static struct attribute_group md_redundancy_group = {
4693         .name = NULL,
4694         .attrs = md_redundancy_attrs,
4695 };
4696
4697
4698 static ssize_t
4699 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
4700 {
4701         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4702         struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4703         ssize_t rv;
4704
4705         if (!entry->show)
4706                 return -EIO;
4707         spin_lock(&all_mddevs_lock);
4708         if (list_empty(&mddev->all_mddevs)) {
4709                 spin_unlock(&all_mddevs_lock);
4710                 return -EBUSY;
4711         }
4712         mddev_get(mddev);
4713         spin_unlock(&all_mddevs_lock);
4714
4715         rv = mddev_lock(mddev);
4716         if (!rv) {
4717                 rv = entry->show(mddev, page);
4718                 mddev_unlock(mddev);
4719         }
4720         mddev_put(mddev);
4721         return rv;
4722 }
4723
4724 static ssize_t
4725 md_attr_store(struct kobject *kobj, struct attribute *attr,
4726               const char *page, size_t length)
4727 {
4728         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4729         struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4730         ssize_t rv;
4731
4732         if (!entry->store)
4733                 return -EIO;
4734         if (!capable(CAP_SYS_ADMIN))
4735                 return -EACCES;
4736         spin_lock(&all_mddevs_lock);
4737         if (list_empty(&mddev->all_mddevs)) {
4738                 spin_unlock(&all_mddevs_lock);
4739                 return -EBUSY;
4740         }
4741         mddev_get(mddev);
4742         spin_unlock(&all_mddevs_lock);
4743         if (entry->store == new_dev_store)
4744                 flush_workqueue(md_misc_wq);
4745         rv = mddev_lock(mddev);
4746         if (!rv) {
4747                 rv = entry->store(mddev, page, length);
4748                 mddev_unlock(mddev);
4749         }
4750         mddev_put(mddev);
4751         return rv;
4752 }
4753
4754 static void md_free(struct kobject *ko)
4755 {
4756         struct mddev *mddev = container_of(ko, struct mddev, kobj);
4757
4758         if (mddev->sysfs_state)
4759                 sysfs_put(mddev->sysfs_state);
4760
4761         if (mddev->gendisk) {
4762                 del_gendisk(mddev->gendisk);
4763                 put_disk(mddev->gendisk);
4764         }
4765         if (mddev->queue)
4766                 blk_cleanup_queue(mddev->queue);
4767
4768         kfree(mddev);
4769 }
4770
4771 static const struct sysfs_ops md_sysfs_ops = {
4772         .show   = md_attr_show,
4773         .store  = md_attr_store,
4774 };
4775 static struct kobj_type md_ktype = {
4776         .release        = md_free,
4777         .sysfs_ops      = &md_sysfs_ops,
4778         .default_attrs  = md_default_attrs,
4779 };
4780
4781 int mdp_major = 0;
4782
4783 static void mddev_delayed_delete(struct work_struct *ws)
4784 {
4785         struct mddev *mddev = container_of(ws, struct mddev, del_work);
4786
4787         sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
4788         kobject_del(&mddev->kobj);
4789         kobject_put(&mddev->kobj);
4790 }
4791
4792 static int md_alloc(dev_t dev, char *name)
4793 {
4794         static DEFINE_MUTEX(disks_mutex);
4795         struct mddev *mddev = mddev_find(dev);
4796         struct gendisk *disk;
4797         int partitioned;
4798         int shift;
4799         int unit;
4800         int error;
4801
4802         if (!mddev)
4803                 return -ENODEV;
4804
4805         partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
4806         shift = partitioned ? MdpMinorShift : 0;
4807         unit = MINOR(mddev->unit) >> shift;
4808
4809         /* wait for any previous instance of this device to be
4810          * completely removed (mddev_delayed_delete).
4811          */
4812         flush_workqueue(md_misc_wq);
4813
4814         mutex_lock(&disks_mutex);
4815         error = -EEXIST;
4816         if (mddev->gendisk)
4817                 goto abort;
4818
4819         if (name) {
4820                 /* Need to ensure that 'name' is not a duplicate.
4821                  */
4822                 struct mddev *mddev2;
4823                 spin_lock(&all_mddevs_lock);
4824
4825                 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
4826                         if (mddev2->gendisk &&
4827                             strcmp(mddev2->gendisk->disk_name, name) == 0) {
4828                                 spin_unlock(&all_mddevs_lock);
4829                                 goto abort;
4830                         }
4831                 spin_unlock(&all_mddevs_lock);
4832         }
4833
4834         error = -ENOMEM;
4835         mddev->queue = blk_alloc_queue(GFP_KERNEL);
4836         if (!mddev->queue)
4837                 goto abort;
4838         mddev->queue->queuedata = mddev;
4839
4840         blk_queue_make_request(mddev->queue, md_make_request);
4841         blk_set_stacking_limits(&mddev->queue->limits);
4842
4843         disk = alloc_disk(1 << shift);
4844         if (!disk) {
4845                 blk_cleanup_queue(mddev->queue);
4846                 mddev->queue = NULL;
4847                 goto abort;
4848         }
4849         disk->major = MAJOR(mddev->unit);
4850         disk->first_minor = unit << shift;
4851         if (name)
4852                 strcpy(disk->disk_name, name);
4853         else if (partitioned)
4854                 sprintf(disk->disk_name, "md_d%d", unit);
4855         else
4856                 sprintf(disk->disk_name, "md%d", unit);
4857         disk->fops = &md_fops;
4858         disk->private_data = mddev;
4859         disk->queue = mddev->queue;
4860         blk_queue_flush(mddev->queue, REQ_FLUSH | REQ_FUA);
4861         /* Allow extended partitions.  This makes the
4862          * 'mdp' device redundant, but we can't really
4863          * remove it now.
4864          */
4865         disk->flags |= GENHD_FL_EXT_DEVT;
4866         mddev->gendisk = disk;
4867         /* As soon as we call add_disk(), another thread could get
4868          * through to md_open, so make sure it doesn't get too far
4869          */
4870         mutex_lock(&mddev->open_mutex);
4871         add_disk(disk);
4872
4873         error = kobject_init_and_add(&mddev->kobj, &md_ktype,
4874                                      &disk_to_dev(disk)->kobj, "%s", "md");
4875         if (error) {
4876                 /* This isn't possible, but as kobject_init_and_add is marked
4877                  * __must_check, we must do something with the result
4878                  */
4879                 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
4880                        disk->disk_name);
4881                 error = 0;
4882         }
4883         if (mddev->kobj.sd &&
4884             sysfs_create_group(&mddev->kobj, &md_bitmap_group))
4885                 printk(KERN_DEBUG "pointless warning\n");
4886         mutex_unlock(&mddev->open_mutex);
4887  abort:
4888         mutex_unlock(&disks_mutex);
4889         if (!error && mddev->kobj.sd) {
4890                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
4891                 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
4892         }
4893         mddev_put(mddev);
4894         return error;
4895 }
4896
4897 static struct kobject *md_probe(dev_t dev, int *part, void *data)
4898 {
4899         md_alloc(dev, NULL);
4900         return NULL;
4901 }
4902
4903 static int add_named_array(const char *val, struct kernel_param *kp)
4904 {
4905         /* val must be "md_*" where * is not all digits.
4906          * We allocate an array with a large free minor number, and
4907          * set the name to val.  val must not already be an active name.
4908          */
4909         int len = strlen(val);
4910         char buf[DISK_NAME_LEN];
4911
4912         while (len && val[len-1] == '\n')
4913                 len--;
4914         if (len >= DISK_NAME_LEN)
4915                 return -E2BIG;
4916         strlcpy(buf, val, len+1);
4917         if (strncmp(buf, "md_", 3) != 0)
4918                 return -EINVAL;
4919         return md_alloc(0, buf);
4920 }
4921
4922 static void md_safemode_timeout(unsigned long data)
4923 {
4924         struct mddev *mddev = (struct mddev *) data;
4925
4926         if (!atomic_read(&mddev->writes_pending)) {
4927                 mddev->safemode = 1;
4928                 if (mddev->external)
4929                         sysfs_notify_dirent_safe(mddev->sysfs_state);
4930         }
4931         md_wakeup_thread(mddev->thread);
4932 }
4933
4934 static int start_dirty_degraded;
4935
4936 int md_run(struct mddev *mddev)
4937 {
4938         int err;
4939         struct md_rdev *rdev;
4940         struct md_personality *pers;
4941
4942         if (list_empty(&mddev->disks))
4943                 /* cannot run an array with no devices.. */
4944                 return -EINVAL;
4945
4946         if (mddev->pers)
4947                 return -EBUSY;
4948         /* Cannot run until previous stop completes properly */
4949         if (mddev->sysfs_active)
4950                 return -EBUSY;
4951
4952         /*
4953          * Analyze all RAID superblock(s)
4954          */
4955         if (!mddev->raid_disks) {
4956                 if (!mddev->persistent)
4957                         return -EINVAL;
4958                 analyze_sbs(mddev);
4959         }
4960
4961         if (mddev->level != LEVEL_NONE)
4962                 request_module("md-level-%d", mddev->level);
4963         else if (mddev->clevel[0])
4964                 request_module("md-%s", mddev->clevel);
4965
4966         /*
4967          * Drop all container device buffers, from now on
4968          * the only valid external interface is through the md
4969          * device.
4970          */
4971         rdev_for_each(rdev, mddev) {
4972                 if (test_bit(Faulty, &rdev->flags))
4973                         continue;
4974                 sync_blockdev(rdev->bdev);
4975                 invalidate_bdev(rdev->bdev);
4976
4977                 /* perform some consistency tests on the device.
4978                  * We don't want the data to overlap the metadata,
4979                  * Internal Bitmap issues have been handled elsewhere.
4980                  */
4981                 if (rdev->meta_bdev) {
4982                         /* Nothing to check */;
4983                 } else if (rdev->data_offset < rdev->sb_start) {
4984                         if (mddev->dev_sectors &&
4985                             rdev->data_offset + mddev->dev_sectors
4986                             > rdev->sb_start) {
4987                                 printk("md: %s: data overlaps metadata\n",
4988                                        mdname(mddev));
4989                                 return -EINVAL;
4990                         }
4991                 } else {
4992                         if (rdev->sb_start + rdev->sb_size/512
4993                             > rdev->data_offset) {
4994                                 printk("md: %s: metadata overlaps data\n",
4995                                        mdname(mddev));
4996                                 return -EINVAL;
4997                         }
4998                 }
4999                 sysfs_notify_dirent_safe(rdev->sysfs_state);
5000         }
5001
5002         if (mddev->bio_set == NULL)
5003                 mddev->bio_set = bioset_create(BIO_POOL_SIZE, 0);
5004
5005         spin_lock(&pers_lock);
5006         pers = find_pers(mddev->level, mddev->clevel);
5007         if (!pers || !try_module_get(pers->owner)) {
5008                 spin_unlock(&pers_lock);
5009                 if (mddev->level != LEVEL_NONE)
5010                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
5011                                mddev->level);
5012                 else
5013                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
5014                                mddev->clevel);
5015                 return -EINVAL;
5016         }
5017         mddev->pers = pers;
5018         spin_unlock(&pers_lock);
5019         if (mddev->level != pers->level) {
5020                 mddev->level = pers->level;
5021                 mddev->new_level = pers->level;
5022         }
5023         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5024
5025         if (mddev->reshape_position != MaxSector &&
5026             pers->start_reshape == NULL) {
5027                 /* This personality cannot handle reshaping... */
5028                 mddev->pers = NULL;
5029                 module_put(pers->owner);
5030                 return -EINVAL;
5031         }
5032
5033         if (pers->sync_request) {
5034                 /* Warn if this is a potentially silly
5035                  * configuration.
5036                  */
5037                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5038                 struct md_rdev *rdev2;
5039                 int warned = 0;
5040
5041                 rdev_for_each(rdev, mddev)
5042                         rdev_for_each(rdev2, mddev) {
5043                                 if (rdev < rdev2 &&
5044                                     rdev->bdev->bd_contains ==
5045                                     rdev2->bdev->bd_contains) {
5046                                         printk(KERN_WARNING
5047                                                "%s: WARNING: %s appears to be"
5048                                                " on the same physical disk as"
5049                                                " %s.\n",
5050                                                mdname(mddev),
5051                                                bdevname(rdev->bdev,b),
5052                                                bdevname(rdev2->bdev,b2));
5053                                         warned = 1;
5054                                 }
5055                         }
5056
5057                 if (warned)
5058                         printk(KERN_WARNING
5059                                "True protection against single-disk"
5060                                " failure might be compromised.\n");
5061         }
5062
5063         mddev->recovery = 0;
5064         /* may be over-ridden by personality */
5065         mddev->resync_max_sectors = mddev->dev_sectors;
5066
5067         mddev->ok_start_degraded = start_dirty_degraded;
5068
5069         if (start_readonly && mddev->ro == 0)
5070                 mddev->ro = 2; /* read-only, but switch on first write */
5071
5072         err = mddev->pers->run(mddev);
5073         if (err)
5074                 printk(KERN_ERR "md: pers->run() failed ...\n");
5075         else if (mddev->pers->size(mddev, 0, 0) < mddev->array_sectors) {
5076                 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
5077                           " but 'external_size' not in effect?\n", __func__);
5078                 printk(KERN_ERR
5079                        "md: invalid array_size %llu > default size %llu\n",
5080                        (unsigned long long)mddev->array_sectors / 2,
5081                        (unsigned long long)mddev->pers->size(mddev, 0, 0) / 2);
5082                 err = -EINVAL;
5083                 mddev->pers->stop(mddev);
5084         }
5085         if (err == 0 && mddev->pers->sync_request &&
5086             (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5087                 err = bitmap_create(mddev);
5088                 if (err) {
5089                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
5090                                mdname(mddev), err);
5091                         mddev->pers->stop(mddev);
5092                 }
5093         }
5094         if (err) {
5095                 module_put(mddev->pers->owner);
5096                 mddev->pers = NULL;
5097                 bitmap_destroy(mddev);
5098                 return err;
5099         }
5100         if (mddev->pers->sync_request) {
5101                 if (mddev->kobj.sd &&
5102                     sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5103                         printk(KERN_WARNING
5104                                "md: cannot register extra attributes for %s\n",
5105                                mdname(mddev));
5106                 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5107         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
5108                 mddev->ro = 0;
5109
5110         atomic_set(&mddev->writes_pending,0);
5111         atomic_set(&mddev->max_corr_read_errors,
5112                    MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
5113         mddev->safemode = 0;
5114         mddev->safemode_timer.function = md_safemode_timeout;
5115         mddev->safemode_timer.data = (unsigned long) mddev;
5116         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
5117         mddev->in_sync = 1;
5118         smp_wmb();
5119         mddev->ready = 1;
5120         rdev_for_each(rdev, mddev)
5121                 if (rdev->raid_disk >= 0)
5122                         if (sysfs_link_rdev(mddev, rdev))
5123                                 /* failure here is OK */;
5124         
5125         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5126         
5127         if (mddev->flags & MD_UPDATE_SB_FLAGS)
5128                 md_update_sb(mddev, 0);
5129
5130         md_new_event(mddev);
5131         sysfs_notify_dirent_safe(mddev->sysfs_state);
5132         sysfs_notify_dirent_safe(mddev->sysfs_action);
5133         sysfs_notify(&mddev->kobj, NULL, "degraded");
5134         return 0;
5135 }
5136 EXPORT_SYMBOL_GPL(md_run);
5137
5138 static int do_md_run(struct mddev *mddev)
5139 {
5140         int err;
5141
5142         err = md_run(mddev);
5143         if (err)
5144                 goto out;
5145         err = bitmap_load(mddev);
5146         if (err) {
5147                 bitmap_destroy(mddev);
5148                 goto out;
5149         }
5150
5151         md_wakeup_thread(mddev->thread);
5152         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
5153
5154         set_capacity(mddev->gendisk, mddev->array_sectors);
5155         revalidate_disk(mddev->gendisk);
5156         mddev->changed = 1;
5157         kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5158 out:
5159         return err;
5160 }
5161
5162 static int restart_array(struct mddev *mddev)
5163 {
5164         struct gendisk *disk = mddev->gendisk;
5165
5166         /* Complain if it has no devices */
5167         if (list_empty(&mddev->disks))
5168                 return -ENXIO;
5169         if (!mddev->pers)
5170                 return -EINVAL;
5171         if (!mddev->ro)
5172                 return -EBUSY;
5173         mddev->safemode = 0;
5174         mddev->ro = 0;
5175         set_disk_ro(disk, 0);
5176         printk(KERN_INFO "md: %s switched to read-write mode.\n",
5177                 mdname(mddev));
5178         /* Kick recovery or resync if necessary */
5179         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5180         md_wakeup_thread(mddev->thread);
5181         md_wakeup_thread(mddev->sync_thread);
5182         sysfs_notify_dirent_safe(mddev->sysfs_state);
5183         return 0;
5184 }
5185
5186 /* similar to deny_write_access, but accounts for our holding a reference
5187  * to the file ourselves */
5188 static int deny_bitmap_write_access(struct file * file)
5189 {
5190         struct inode *inode = file->f_mapping->host;
5191
5192         spin_lock(&inode->i_lock);
5193         if (atomic_read(&inode->i_writecount) > 1) {
5194                 spin_unlock(&inode->i_lock);
5195                 return -ETXTBSY;
5196         }
5197         atomic_set(&inode->i_writecount, -1);
5198         spin_unlock(&inode->i_lock);
5199
5200         return 0;
5201 }
5202
5203 void restore_bitmap_write_access(struct file *file)
5204 {
5205         struct inode *inode = file->f_mapping->host;
5206
5207         spin_lock(&inode->i_lock);
5208         atomic_set(&inode->i_writecount, 1);
5209         spin_unlock(&inode->i_lock);
5210 }
5211
5212 static void md_clean(struct mddev *mddev)
5213 {
5214         mddev->array_sectors = 0;
5215         mddev->external_size = 0;
5216         mddev->dev_sectors = 0;
5217         mddev->raid_disks = 0;
5218         mddev->recovery_cp = 0;
5219         mddev->resync_min = 0;
5220         mddev->resync_max = MaxSector;
5221         mddev->reshape_position = MaxSector;
5222         mddev->external = 0;
5223         mddev->persistent = 0;
5224         mddev->level = LEVEL_NONE;
5225         mddev->clevel[0] = 0;
5226         mddev->flags = 0;
5227         mddev->ro = 0;
5228         mddev->metadata_type[0] = 0;
5229         mddev->chunk_sectors = 0;
5230         mddev->ctime = mddev->utime = 0;
5231         mddev->layout = 0;
5232         mddev->max_disks = 0;
5233         mddev->events = 0;
5234         mddev->can_decrease_events = 0;
5235         mddev->delta_disks = 0;
5236         mddev->reshape_backwards = 0;
5237         mddev->new_level = LEVEL_NONE;
5238         mddev->new_layout = 0;
5239         mddev->new_chunk_sectors = 0;
5240         mddev->curr_resync = 0;
5241         atomic64_set(&mddev->resync_mismatches, 0);
5242         mddev->suspend_lo = mddev->suspend_hi = 0;
5243         mddev->sync_speed_min = mddev->sync_speed_max = 0;
5244         mddev->recovery = 0;
5245         mddev->in_sync = 0;
5246         mddev->changed = 0;
5247         mddev->degraded = 0;
5248         mddev->safemode = 0;
5249         mddev->merge_check_needed = 0;
5250         mddev->bitmap_info.offset = 0;
5251         mddev->bitmap_info.default_offset = 0;
5252         mddev->bitmap_info.default_space = 0;
5253         mddev->bitmap_info.chunksize = 0;
5254         mddev->bitmap_info.daemon_sleep = 0;
5255         mddev->bitmap_info.max_write_behind = 0;
5256 }
5257
5258 static void __md_stop_writes(struct mddev *mddev)
5259 {
5260         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5261         if (mddev->sync_thread) {
5262                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5263                 md_reap_sync_thread(mddev);
5264         }
5265
5266         del_timer_sync(&mddev->safemode_timer);
5267
5268         bitmap_flush(mddev);
5269         md_super_wait(mddev);
5270
5271         if (mddev->ro == 0 &&
5272             (!mddev->in_sync || (mddev->flags & MD_UPDATE_SB_FLAGS))) {
5273                 /* mark array as shutdown cleanly */
5274                 mddev->in_sync = 1;
5275                 md_update_sb(mddev, 1);
5276         }
5277 }
5278
5279 void md_stop_writes(struct mddev *mddev)
5280 {
5281         mddev_lock_nointr(mddev);
5282         __md_stop_writes(mddev);
5283         mddev_unlock(mddev);
5284 }
5285 EXPORT_SYMBOL_GPL(md_stop_writes);
5286
5287 static void __md_stop(struct mddev *mddev)
5288 {
5289         mddev->ready = 0;
5290         mddev->pers->stop(mddev);
5291         if (mddev->pers->sync_request && mddev->to_remove == NULL)
5292                 mddev->to_remove = &md_redundancy_group;
5293         module_put(mddev->pers->owner);
5294         mddev->pers = NULL;
5295         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5296 }
5297
5298 void md_stop(struct mddev *mddev)
5299 {
5300         /* stop the array and free an attached data structures.
5301          * This is called from dm-raid
5302          */
5303         __md_stop(mddev);
5304         bitmap_destroy(mddev);
5305         if (mddev->bio_set)
5306                 bioset_free(mddev->bio_set);
5307 }
5308
5309 EXPORT_SYMBOL_GPL(md_stop);
5310
5311 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
5312 {
5313         int err = 0;
5314         int did_freeze = 0;
5315
5316         if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5317                 did_freeze = 1;
5318                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5319                 md_wakeup_thread(mddev->thread);
5320         }
5321         if (mddev->sync_thread) {
5322                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5323                 /* Thread might be blocked waiting for metadata update
5324                  * which will now never happen */
5325                 wake_up_process(mddev->sync_thread->tsk);
5326         }
5327         mddev_unlock(mddev);
5328         wait_event(resync_wait, mddev->sync_thread == NULL);
5329         mddev_lock_nointr(mddev);
5330
5331         mutex_lock(&mddev->open_mutex);
5332         if (atomic_read(&mddev->openers) > !!bdev ||
5333             mddev->sync_thread ||
5334             (bdev && !test_bit(MD_STILL_CLOSED, &mddev->flags))) {
5335                 printk("md: %s still in use.\n",mdname(mddev));
5336                 if (did_freeze) {
5337                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5338                         md_wakeup_thread(mddev->thread);
5339                 }
5340                 err = -EBUSY;
5341                 goto out;
5342         }
5343         if (mddev->pers) {
5344                 __md_stop_writes(mddev);
5345
5346                 err  = -ENXIO;
5347                 if (mddev->ro==1)
5348                         goto out;
5349                 mddev->ro = 1;
5350                 set_disk_ro(mddev->gendisk, 1);
5351                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5352                 sysfs_notify_dirent_safe(mddev->sysfs_state);
5353                 err = 0;
5354         }
5355 out:
5356         mutex_unlock(&mddev->open_mutex);
5357         return err;
5358 }
5359
5360 /* mode:
5361  *   0 - completely stop and dis-assemble array
5362  *   2 - stop but do not disassemble array
5363  */
5364 static int do_md_stop(struct mddev * mddev, int mode,
5365                       struct block_device *bdev)
5366 {
5367         struct gendisk *disk = mddev->gendisk;
5368         struct md_rdev *rdev;
5369         int did_freeze = 0;
5370
5371         if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5372                 did_freeze = 1;
5373                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5374                 md_wakeup_thread(mddev->thread);
5375         }
5376         if (mddev->sync_thread) {
5377                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5378                 /* Thread might be blocked waiting for metadata update
5379                  * which will now never happen */
5380                 wake_up_process(mddev->sync_thread->tsk);
5381         }
5382         mddev_unlock(mddev);
5383         wait_event(resync_wait, mddev->sync_thread == NULL);
5384         mddev_lock_nointr(mddev);
5385
5386         mutex_lock(&mddev->open_mutex);
5387         if (atomic_read(&mddev->openers) > !!bdev ||
5388             mddev->sysfs_active ||
5389             mddev->sync_thread ||
5390             (bdev && !test_bit(MD_STILL_CLOSED, &mddev->flags))) {
5391                 printk("md: %s still in use.\n",mdname(mddev));
5392                 mutex_unlock(&mddev->open_mutex);
5393                 if (did_freeze) {
5394                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5395                         md_wakeup_thread(mddev->thread);
5396                 }
5397                 return -EBUSY;
5398         }
5399         if (mddev->pers) {
5400                 if (mddev->ro)
5401                         set_disk_ro(disk, 0);
5402
5403                 __md_stop_writes(mddev);
5404                 __md_stop(mddev);
5405                 mddev->queue->merge_bvec_fn = NULL;
5406                 mddev->queue->backing_dev_info.congested_fn = NULL;
5407
5408                 /* tell userspace to handle 'inactive' */
5409                 sysfs_notify_dirent_safe(mddev->sysfs_state);
5410
5411                 rdev_for_each(rdev, mddev)
5412                         if (rdev->raid_disk >= 0)
5413                                 sysfs_unlink_rdev(mddev, rdev);
5414
5415                 set_capacity(disk, 0);
5416                 mutex_unlock(&mddev->open_mutex);
5417                 mddev->changed = 1;
5418                 revalidate_disk(disk);
5419
5420                 if (mddev->ro)
5421                         mddev->ro = 0;
5422         } else
5423                 mutex_unlock(&mddev->open_mutex);
5424         /*
5425          * Free resources if final stop
5426          */
5427         if (mode == 0) {
5428                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
5429
5430                 bitmap_destroy(mddev);
5431                 if (mddev->bitmap_info.file) {
5432                         restore_bitmap_write_access(mddev->bitmap_info.file);
5433                         fput(mddev->bitmap_info.file);
5434                         mddev->bitmap_info.file = NULL;
5435                 }
5436                 mddev->bitmap_info.offset = 0;
5437
5438                 export_array(mddev);
5439
5440                 md_clean(mddev);
5441                 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5442                 if (mddev->hold_active == UNTIL_STOP)
5443                         mddev->hold_active = 0;
5444         }
5445         blk_integrity_unregister(disk);
5446         md_new_event(mddev);
5447         sysfs_notify_dirent_safe(mddev->sysfs_state);
5448         return 0;
5449 }
5450
5451 #ifndef MODULE
5452 static void autorun_array(struct mddev *mddev)
5453 {
5454         struct md_rdev *rdev;
5455         int err;
5456
5457         if (list_empty(&mddev->disks))
5458                 return;
5459
5460         printk(KERN_INFO "md: running: ");
5461
5462         rdev_for_each(rdev, mddev) {
5463                 char b[BDEVNAME_SIZE];
5464                 printk("<%s>", bdevname(rdev->bdev,b));
5465         }
5466         printk("\n");
5467
5468         err = do_md_run(mddev);
5469         if (err) {
5470                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
5471                 do_md_stop(mddev, 0, NULL);
5472         }
5473 }
5474
5475 /*
5476  * lets try to run arrays based on all disks that have arrived
5477  * until now. (those are in pending_raid_disks)
5478  *
5479  * the method: pick the first pending disk, collect all disks with
5480  * the same UUID, remove all from the pending list and put them into
5481  * the 'same_array' list. Then order this list based on superblock
5482  * update time (freshest comes first), kick out 'old' disks and
5483  * compare superblocks. If everything's fine then run it.
5484  *
5485  * If "unit" is allocated, then bump its reference count
5486  */
5487 static void autorun_devices(int part)
5488 {
5489         struct md_rdev *rdev0, *rdev, *tmp;
5490         struct mddev *mddev;
5491         char b[BDEVNAME_SIZE];
5492
5493         printk(KERN_INFO "md: autorun ...\n");
5494         while (!list_empty(&pending_raid_disks)) {
5495                 int unit;
5496                 dev_t dev;
5497                 LIST_HEAD(candidates);
5498                 rdev0 = list_entry(pending_raid_disks.next,
5499                                          struct md_rdev, same_set);
5500
5501                 printk(KERN_INFO "md: considering %s ...\n",
5502                         bdevname(rdev0->bdev,b));
5503                 INIT_LIST_HEAD(&candidates);
5504                 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
5505                         if (super_90_load(rdev, rdev0, 0) >= 0) {
5506                                 printk(KERN_INFO "md:  adding %s ...\n",
5507                                         bdevname(rdev->bdev,b));
5508                                 list_move(&rdev->same_set, &candidates);
5509                         }
5510                 /*
5511                  * now we have a set of devices, with all of them having
5512                  * mostly sane superblocks. It's time to allocate the
5513                  * mddev.
5514                  */
5515                 if (part) {
5516                         dev = MKDEV(mdp_major,
5517                                     rdev0->preferred_minor << MdpMinorShift);
5518                         unit = MINOR(dev) >> MdpMinorShift;
5519                 } else {
5520                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
5521                         unit = MINOR(dev);
5522                 }
5523                 if (rdev0->preferred_minor != unit) {
5524                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
5525                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
5526                         break;
5527                 }
5528
5529                 md_probe(dev, NULL, NULL);
5530                 mddev = mddev_find(dev);
5531                 if (!mddev || !mddev->gendisk) {
5532                         if (mddev)
5533                                 mddev_put(mddev);
5534                         printk(KERN_ERR
5535                                 "md: cannot allocate memory for md drive.\n");
5536                         break;
5537                 }
5538                 if (mddev_lock(mddev)) 
5539                         printk(KERN_WARNING "md: %s locked, cannot run\n",
5540                                mdname(mddev));
5541                 else if (mddev->raid_disks || mddev->major_version
5542                          || !list_empty(&mddev->disks)) {
5543                         printk(KERN_WARNING 
5544                                 "md: %s already running, cannot run %s\n",
5545                                 mdname(mddev), bdevname(rdev0->bdev,b));
5546                         mddev_unlock(mddev);
5547                 } else {
5548                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
5549                         mddev->persistent = 1;
5550                         rdev_for_each_list(rdev, tmp, &candidates) {
5551                                 list_del_init(&rdev->same_set);
5552                                 if (bind_rdev_to_array(rdev, mddev))
5553                                         export_rdev(rdev);
5554                         }
5555                         autorun_array(mddev);
5556                         mddev_unlock(mddev);
5557                 }
5558                 /* on success, candidates will be empty, on error
5559                  * it won't...
5560                  */
5561                 rdev_for_each_list(rdev, tmp, &candidates) {
5562                         list_del_init(&rdev->same_set);
5563                         export_rdev(rdev);
5564                 }
5565                 mddev_put(mddev);
5566         }
5567         printk(KERN_INFO "md: ... autorun DONE.\n");
5568 }
5569 #endif /* !MODULE */
5570
5571 static int get_version(void __user * arg)
5572 {
5573         mdu_version_t ver;
5574
5575         ver.major = MD_MAJOR_VERSION;
5576         ver.minor = MD_MINOR_VERSION;
5577         ver.patchlevel = MD_PATCHLEVEL_VERSION;
5578
5579         if (copy_to_user(arg, &ver, sizeof(ver)))
5580                 return -EFAULT;
5581
5582         return 0;
5583 }
5584
5585 static int get_array_info(struct mddev * mddev, void __user * arg)
5586 {
5587         mdu_array_info_t info;
5588         int nr,working,insync,failed,spare;
5589         struct md_rdev *rdev;
5590
5591         nr = working = insync = failed = spare = 0;
5592         rcu_read_lock();
5593         rdev_for_each_rcu(rdev, mddev) {
5594                 nr++;
5595                 if (test_bit(Faulty, &rdev->flags))
5596                         failed++;
5597                 else {
5598                         working++;
5599                         if (test_bit(In_sync, &rdev->flags))
5600                                 insync++;       
5601                         else
5602                                 spare++;
5603                 }
5604         }
5605         rcu_read_unlock();
5606
5607         info.major_version = mddev->major_version;
5608         info.minor_version = mddev->minor_version;
5609         info.patch_version = MD_PATCHLEVEL_VERSION;
5610         info.ctime         = mddev->ctime;
5611         info.level         = mddev->level;
5612         info.size          = mddev->dev_sectors / 2;
5613         if (info.size != mddev->dev_sectors / 2) /* overflow */
5614                 info.size = -1;
5615         info.nr_disks      = nr;
5616         info.raid_disks    = mddev->raid_disks;
5617         info.md_minor      = mddev->md_minor;
5618         info.not_persistent= !mddev->persistent;
5619
5620         info.utime         = mddev->utime;
5621         info.state         = 0;
5622         if (mddev->in_sync)
5623                 info.state = (1<<MD_SB_CLEAN);
5624         if (mddev->bitmap && mddev->bitmap_info.offset)
5625                 info.state = (1<<MD_SB_BITMAP_PRESENT);
5626         info.active_disks  = insync;
5627         info.working_disks = working;
5628         info.failed_disks  = failed;
5629         info.spare_disks   = spare;
5630
5631         info.layout        = mddev->layout;
5632         info.chunk_size    = mddev->chunk_sectors << 9;
5633
5634         if (copy_to_user(arg, &info, sizeof(info)))
5635                 return -EFAULT;
5636
5637         return 0;
5638 }
5639
5640 static int get_bitmap_file(struct mddev * mddev, void __user * arg)
5641 {
5642         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
5643         char *ptr, *buf = NULL;
5644         int err = -ENOMEM;
5645
5646         file = kmalloc(sizeof(*file), GFP_NOIO);
5647
5648         if (!file)
5649                 goto out;
5650
5651         /* bitmap disabled, zero the first byte and copy out */
5652         if (!mddev->bitmap || !mddev->bitmap->storage.file) {
5653                 file->pathname[0] = '\0';
5654                 goto copy_out;
5655         }
5656
5657         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
5658         if (!buf)
5659                 goto out;
5660
5661         ptr = d_path(&mddev->bitmap->storage.file->f_path,
5662                      buf, sizeof(file->pathname));
5663         if (IS_ERR(ptr))
5664                 goto out;
5665
5666         strcpy(file->pathname, ptr);
5667
5668 copy_out:
5669         err = 0;
5670         if (copy_to_user(arg, file, sizeof(*file)))
5671                 err = -EFAULT;
5672 out:
5673         kfree(buf);
5674         kfree(file);
5675         return err;
5676 }
5677
5678 static int get_disk_info(struct mddev * mddev, void __user * arg)
5679 {
5680         mdu_disk_info_t info;
5681         struct md_rdev *rdev;
5682
5683         if (copy_from_user(&info, arg, sizeof(info)))
5684                 return -EFAULT;
5685
5686         rcu_read_lock();
5687         rdev = find_rdev_nr_rcu(mddev, info.number);
5688         if (rdev) {
5689                 info.major = MAJOR(rdev->bdev->bd_dev);
5690                 info.minor = MINOR(rdev->bdev->bd_dev);
5691                 info.raid_disk = rdev->raid_disk;
5692                 info.state = 0;
5693                 if (test_bit(Faulty, &rdev->flags))
5694                         info.state |= (1<<MD_DISK_FAULTY);
5695                 else if (test_bit(In_sync, &rdev->flags)) {
5696                         info.state |= (1<<MD_DISK_ACTIVE);
5697                         info.state |= (1<<MD_DISK_SYNC);
5698                 }
5699                 if (test_bit(WriteMostly, &rdev->flags))
5700                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
5701         } else {
5702                 info.major = info.minor = 0;
5703                 info.raid_disk = -1;
5704                 info.state = (1<<MD_DISK_REMOVED);
5705         }
5706         rcu_read_unlock();
5707
5708         if (copy_to_user(arg, &info, sizeof(info)))
5709                 return -EFAULT;
5710
5711         return 0;
5712 }
5713
5714 static int add_new_disk(struct mddev * mddev, mdu_disk_info_t *info)
5715 {
5716         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5717         struct md_rdev *rdev;
5718         dev_t dev = MKDEV(info->major,info->minor);
5719
5720         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
5721                 return -EOVERFLOW;
5722
5723         if (!mddev->raid_disks) {
5724                 int err;
5725                 /* expecting a device which has a superblock */
5726                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
5727                 if (IS_ERR(rdev)) {
5728                         printk(KERN_WARNING 
5729                                 "md: md_import_device returned %ld\n",
5730                                 PTR_ERR(rdev));
5731                         return PTR_ERR(rdev);
5732                 }
5733                 if (!list_empty(&mddev->disks)) {
5734                         struct md_rdev *rdev0
5735                                 = list_entry(mddev->disks.next,
5736                                              struct md_rdev, same_set);
5737                         err = super_types[mddev->major_version]
5738                                 .load_super(rdev, rdev0, mddev->minor_version);
5739                         if (err < 0) {
5740                                 printk(KERN_WARNING 
5741                                         "md: %s has different UUID to %s\n",
5742                                         bdevname(rdev->bdev,b), 
5743                                         bdevname(rdev0->bdev,b2));
5744                                 export_rdev(rdev);
5745                                 return -EINVAL;
5746                         }
5747                 }
5748                 err = bind_rdev_to_array(rdev, mddev);
5749                 if (err)
5750                         export_rdev(rdev);
5751                 return err;
5752         }
5753
5754         /*
5755          * add_new_disk can be used once the array is assembled
5756          * to add "hot spares".  They must already have a superblock
5757          * written
5758          */
5759         if (mddev->pers) {
5760                 int err;
5761                 if (!mddev->pers->hot_add_disk) {
5762                         printk(KERN_WARNING 
5763                                 "%s: personality does not support diskops!\n",
5764                                mdname(mddev));
5765                         return -EINVAL;
5766                 }
5767                 if (mddev->persistent)
5768                         rdev = md_import_device(dev, mddev->major_version,
5769                                                 mddev->minor_version);
5770                 else
5771                         rdev = md_import_device(dev, -1, -1);
5772                 if (IS_ERR(rdev)) {
5773                         printk(KERN_WARNING 
5774                                 "md: md_import_device returned %ld\n",
5775                                 PTR_ERR(rdev));
5776                         return PTR_ERR(rdev);
5777                 }
5778                 /* set saved_raid_disk if appropriate */
5779                 if (!mddev->persistent) {
5780                         if (info->state & (1<<MD_DISK_SYNC)  &&
5781                             info->raid_disk < mddev->raid_disks) {
5782                                 rdev->raid_disk = info->raid_disk;
5783                                 set_bit(In_sync, &rdev->flags);
5784                                 clear_bit(Bitmap_sync, &rdev->flags);
5785                         } else
5786                                 rdev->raid_disk = -1;
5787                         rdev->saved_raid_disk = rdev->raid_disk;
5788                 } else
5789                         super_types[mddev->major_version].
5790                                 validate_super(mddev, rdev);
5791                 if ((info->state & (1<<MD_DISK_SYNC)) &&
5792                      rdev->raid_disk != info->raid_disk) {
5793                         /* This was a hot-add request, but events doesn't
5794                          * match, so reject it.
5795                          */
5796                         export_rdev(rdev);
5797                         return -EINVAL;
5798                 }
5799
5800                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
5801                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5802                         set_bit(WriteMostly, &rdev->flags);
5803                 else
5804                         clear_bit(WriteMostly, &rdev->flags);
5805
5806                 rdev->raid_disk = -1;
5807                 err = bind_rdev_to_array(rdev, mddev);
5808                 if (!err && !mddev->pers->hot_remove_disk) {
5809                         /* If there is hot_add_disk but no hot_remove_disk
5810                          * then added disks for geometry changes,
5811                          * and should be added immediately.
5812                          */
5813                         super_types[mddev->major_version].
5814                                 validate_super(mddev, rdev);
5815                         err = mddev->pers->hot_add_disk(mddev, rdev);
5816                         if (err)
5817                                 unbind_rdev_from_array(rdev);
5818                 }
5819                 if (err)
5820                         export_rdev(rdev);
5821                 else
5822                         sysfs_notify_dirent_safe(rdev->sysfs_state);
5823
5824                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5825                 if (mddev->degraded)
5826                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5827                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5828                 if (!err)
5829                         md_new_event(mddev);
5830                 md_wakeup_thread(mddev->thread);
5831                 return err;
5832         }
5833
5834         /* otherwise, add_new_disk is only allowed
5835          * for major_version==0 superblocks
5836          */
5837         if (mddev->major_version != 0) {
5838                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
5839                        mdname(mddev));
5840                 return -EINVAL;
5841         }
5842
5843         if (!(info->state & (1<<MD_DISK_FAULTY))) {
5844                 int err;
5845                 rdev = md_import_device(dev, -1, 0);
5846                 if (IS_ERR(rdev)) {
5847                         printk(KERN_WARNING 
5848                                 "md: error, md_import_device() returned %ld\n",
5849                                 PTR_ERR(rdev));
5850                         return PTR_ERR(rdev);
5851                 }
5852                 rdev->desc_nr = info->number;
5853                 if (info->raid_disk < mddev->raid_disks)
5854                         rdev->raid_disk = info->raid_disk;
5855                 else
5856                         rdev->raid_disk = -1;
5857
5858                 if (rdev->raid_disk < mddev->raid_disks)
5859                         if (info->state & (1<<MD_DISK_SYNC))
5860                                 set_bit(In_sync, &rdev->flags);
5861
5862                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5863                         set_bit(WriteMostly, &rdev->flags);
5864
5865                 if (!mddev->persistent) {
5866                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
5867                         rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5868                 } else
5869                         rdev->sb_start = calc_dev_sboffset(rdev);
5870                 rdev->sectors = rdev->sb_start;
5871
5872                 err = bind_rdev_to_array(rdev, mddev);
5873                 if (err) {
5874                         export_rdev(rdev);
5875                         return err;
5876                 }
5877         }
5878
5879         return 0;
5880 }
5881
5882 static int hot_remove_disk(struct mddev * mddev, dev_t dev)
5883 {
5884         char b[BDEVNAME_SIZE];
5885         struct md_rdev *rdev;
5886
5887         rdev = find_rdev(mddev, dev);
5888         if (!rdev)
5889                 return -ENXIO;
5890
5891         clear_bit(Blocked, &rdev->flags);
5892         remove_and_add_spares(mddev, rdev);
5893
5894         if (rdev->raid_disk >= 0)
5895                 goto busy;
5896
5897         kick_rdev_from_array(rdev);
5898         md_update_sb(mddev, 1);
5899         md_new_event(mddev);
5900
5901         return 0;
5902 busy:
5903         printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
5904                 bdevname(rdev->bdev,b), mdname(mddev));
5905         return -EBUSY;
5906 }
5907
5908 static int hot_add_disk(struct mddev * mddev, dev_t dev)
5909 {
5910         char b[BDEVNAME_SIZE];
5911         int err;
5912         struct md_rdev *rdev;
5913
5914         if (!mddev->pers)
5915                 return -ENODEV;
5916
5917         if (mddev->major_version != 0) {
5918                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
5919                         " version-0 superblocks.\n",
5920                         mdname(mddev));
5921                 return -EINVAL;
5922         }
5923         if (!mddev->pers->hot_add_disk) {
5924                 printk(KERN_WARNING 
5925                         "%s: personality does not support diskops!\n",
5926                         mdname(mddev));
5927                 return -EINVAL;
5928         }
5929
5930         rdev = md_import_device(dev, -1, 0);
5931         if (IS_ERR(rdev)) {
5932                 printk(KERN_WARNING 
5933                         "md: error, md_import_device() returned %ld\n",
5934                         PTR_ERR(rdev));
5935                 return -EINVAL;
5936         }
5937
5938         if (mddev->persistent)
5939                 rdev->sb_start = calc_dev_sboffset(rdev);
5940         else
5941                 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5942
5943         rdev->sectors = rdev->sb_start;
5944
5945         if (test_bit(Faulty, &rdev->flags)) {
5946                 printk(KERN_WARNING 
5947                         "md: can not hot-add faulty %s disk to %s!\n",
5948                         bdevname(rdev->bdev,b), mdname(mddev));
5949                 err = -EINVAL;
5950                 goto abort_export;
5951         }
5952         clear_bit(In_sync, &rdev->flags);
5953         rdev->desc_nr = -1;
5954         rdev->saved_raid_disk = -1;
5955         err = bind_rdev_to_array(rdev, mddev);
5956         if (err)
5957                 goto abort_export;
5958
5959         /*
5960          * The rest should better be atomic, we can have disk failures
5961          * noticed in interrupt contexts ...
5962          */
5963
5964         rdev->raid_disk = -1;
5965
5966         md_update_sb(mddev, 1);
5967
5968         /*
5969          * Kick recovery, maybe this spare has to be added to the
5970          * array immediately.
5971          */
5972         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5973         md_wakeup_thread(mddev->thread);
5974         md_new_event(mddev);
5975         return 0;
5976
5977 abort_export:
5978         export_rdev(rdev);
5979         return err;
5980 }
5981
5982 static int set_bitmap_file(struct mddev *mddev, int fd)
5983 {
5984         int err;
5985
5986         if (mddev->pers) {
5987                 if (!mddev->pers->quiesce)
5988                         return -EBUSY;
5989                 if (mddev->recovery || mddev->sync_thread)
5990                         return -EBUSY;
5991                 /* we should be able to change the bitmap.. */
5992         }
5993
5994
5995         if (fd >= 0) {
5996                 if (mddev->bitmap)
5997                         return -EEXIST; /* cannot add when bitmap is present */
5998                 mddev->bitmap_info.file = fget(fd);
5999
6000                 if (mddev->bitmap_info.file == NULL) {
6001                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
6002                                mdname(mddev));
6003                         return -EBADF;
6004                 }
6005
6006                 err = deny_bitmap_write_access(mddev->bitmap_info.file);
6007                 if (err) {
6008                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
6009                                mdname(mddev));
6010                         fput(mddev->bitmap_info.file);
6011                         mddev->bitmap_info.file = NULL;
6012                         return err;
6013                 }
6014                 mddev->bitmap_info.offset = 0; /* file overrides offset */
6015         } else if (mddev->bitmap == NULL)
6016                 return -ENOENT; /* cannot remove what isn't there */
6017         err = 0;
6018         if (mddev->pers) {
6019                 mddev->pers->quiesce(mddev, 1);
6020                 if (fd >= 0) {
6021                         err = bitmap_create(mddev);
6022                         if (!err)
6023                                 err = bitmap_load(mddev);
6024                 }
6025                 if (fd < 0 || err) {
6026                         bitmap_destroy(mddev);
6027                         fd = -1; /* make sure to put the file */
6028                 }
6029                 mddev->pers->quiesce(mddev, 0);
6030         }
6031         if (fd < 0) {
6032                 if (mddev->bitmap_info.file) {
6033                         restore_bitmap_write_access(mddev->bitmap_info.file);
6034                         fput(mddev->bitmap_info.file);
6035                 }
6036                 mddev->bitmap_info.file = NULL;
6037         }
6038
6039         return err;
6040 }
6041
6042 /*
6043  * set_array_info is used two different ways
6044  * The original usage is when creating a new array.
6045  * In this usage, raid_disks is > 0 and it together with
6046  *  level, size, not_persistent,layout,chunksize determine the
6047  *  shape of the array.
6048  *  This will always create an array with a type-0.90.0 superblock.
6049  * The newer usage is when assembling an array.
6050  *  In this case raid_disks will be 0, and the major_version field is
6051  *  use to determine which style super-blocks are to be found on the devices.
6052  *  The minor and patch _version numbers are also kept incase the
6053  *  super_block handler wishes to interpret them.
6054  */
6055 static int set_array_info(struct mddev * mddev, mdu_array_info_t *info)
6056 {
6057
6058         if (info->raid_disks == 0) {
6059                 /* just setting version number for superblock loading */
6060                 if (info->major_version < 0 ||
6061                     info->major_version >= ARRAY_SIZE(super_types) ||
6062                     super_types[info->major_version].name == NULL) {
6063                         /* maybe try to auto-load a module? */
6064                         printk(KERN_INFO 
6065                                 "md: superblock version %d not known\n",
6066                                 info->major_version);
6067                         return -EINVAL;
6068                 }
6069                 mddev->major_version = info->major_version;
6070                 mddev->minor_version = info->minor_version;
6071                 mddev->patch_version = info->patch_version;
6072                 mddev->persistent = !info->not_persistent;
6073                 /* ensure mddev_put doesn't delete this now that there
6074                  * is some minimal configuration.
6075                  */
6076                 mddev->ctime         = get_seconds();
6077                 return 0;
6078         }
6079         mddev->major_version = MD_MAJOR_VERSION;
6080         mddev->minor_version = MD_MINOR_VERSION;
6081         mddev->patch_version = MD_PATCHLEVEL_VERSION;
6082         mddev->ctime         = get_seconds();
6083
6084         mddev->level         = info->level;
6085         mddev->clevel[0]     = 0;
6086         mddev->dev_sectors   = 2 * (sector_t)info->size;
6087         mddev->raid_disks    = info->raid_disks;
6088         /* don't set md_minor, it is determined by which /dev/md* was
6089          * openned
6090          */
6091         if (info->state & (1<<MD_SB_CLEAN))
6092                 mddev->recovery_cp = MaxSector;
6093         else
6094                 mddev->recovery_cp = 0;
6095         mddev->persistent    = ! info->not_persistent;
6096         mddev->external      = 0;
6097
6098         mddev->layout        = info->layout;
6099         mddev->chunk_sectors = info->chunk_size >> 9;
6100
6101         mddev->max_disks     = MD_SB_DISKS;
6102
6103         if (mddev->persistent)
6104                 mddev->flags         = 0;
6105         set_bit(MD_CHANGE_DEVS, &mddev->flags);
6106
6107         mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
6108         mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
6109         mddev->bitmap_info.offset = 0;
6110
6111         mddev->reshape_position = MaxSector;
6112
6113         /*
6114          * Generate a 128 bit UUID
6115          */
6116         get_random_bytes(mddev->uuid, 16);
6117
6118         mddev->new_level = mddev->level;
6119         mddev->new_chunk_sectors = mddev->chunk_sectors;
6120         mddev->new_layout = mddev->layout;
6121         mddev->delta_disks = 0;
6122         mddev->reshape_backwards = 0;
6123
6124         return 0;
6125 }
6126
6127 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
6128 {
6129         WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
6130
6131         if (mddev->external_size)
6132                 return;
6133
6134         mddev->array_sectors = array_sectors;
6135 }
6136 EXPORT_SYMBOL(md_set_array_sectors);
6137
6138 static int update_size(struct mddev *mddev, sector_t num_sectors)
6139 {
6140         struct md_rdev *rdev;
6141         int rv;
6142         int fit = (num_sectors == 0);
6143
6144         if (mddev->pers->resize == NULL)
6145                 return -EINVAL;
6146         /* The "num_sectors" is the number of sectors of each device that
6147          * is used.  This can only make sense for arrays with redundancy.
6148          * linear and raid0 always use whatever space is available. We can only
6149          * consider changing this number if no resync or reconstruction is
6150          * happening, and if the new size is acceptable. It must fit before the
6151          * sb_start or, if that is <data_offset, it must fit before the size
6152          * of each device.  If num_sectors is zero, we find the largest size
6153          * that fits.
6154          */
6155         if (mddev->sync_thread)
6156                 return -EBUSY;
6157
6158         rdev_for_each(rdev, mddev) {
6159                 sector_t avail = rdev->sectors;
6160
6161                 if (fit && (num_sectors == 0 || num_sectors > avail))
6162                         num_sectors = avail;
6163                 if (avail < num_sectors)
6164                         return -ENOSPC;
6165         }
6166         rv = mddev->pers->resize(mddev, num_sectors);
6167         if (!rv)
6168                 revalidate_disk(mddev->gendisk);
6169         return rv;
6170 }
6171
6172 static int update_raid_disks(struct mddev *mddev, int raid_disks)
6173 {
6174         int rv;
6175         struct md_rdev *rdev;
6176         /* change the number of raid disks */
6177         if (mddev->pers->check_reshape == NULL)
6178                 return -EINVAL;
6179         if (raid_disks <= 0 ||
6180             (mddev->max_disks && raid_disks >= mddev->max_disks))
6181                 return -EINVAL;
6182         if (mddev->sync_thread || mddev->reshape_position != MaxSector)
6183                 return -EBUSY;
6184
6185         rdev_for_each(rdev, mddev) {
6186                 if (mddev->raid_disks < raid_disks &&
6187                     rdev->data_offset < rdev->new_data_offset)
6188                         return -EINVAL;
6189                 if (mddev->raid_disks > raid_disks &&
6190                     rdev->data_offset > rdev->new_data_offset)
6191                         return -EINVAL;
6192         }
6193
6194         mddev->delta_disks = raid_disks - mddev->raid_disks;
6195         if (mddev->delta_disks < 0)
6196                 mddev->reshape_backwards = 1;
6197         else if (mddev->delta_disks > 0)
6198                 mddev->reshape_backwards = 0;
6199
6200         rv = mddev->pers->check_reshape(mddev);
6201         if (rv < 0) {
6202                 mddev->delta_disks = 0;
6203                 mddev->reshape_backwards = 0;
6204         }
6205         return rv;
6206 }
6207
6208
6209 /*
6210  * update_array_info is used to change the configuration of an
6211  * on-line array.
6212  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
6213  * fields in the info are checked against the array.
6214  * Any differences that cannot be handled will cause an error.
6215  * Normally, only one change can be managed at a time.
6216  */
6217 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
6218 {
6219         int rv = 0;
6220         int cnt = 0;
6221         int state = 0;
6222
6223         /* calculate expected state,ignoring low bits */
6224         if (mddev->bitmap && mddev->bitmap_info.offset)
6225                 state |= (1 << MD_SB_BITMAP_PRESENT);
6226
6227         if (mddev->major_version != info->major_version ||
6228             mddev->minor_version != info->minor_version ||
6229 /*          mddev->patch_version != info->patch_version || */
6230             mddev->ctime         != info->ctime         ||
6231             mddev->level         != info->level         ||
6232 /*          mddev->layout        != info->layout        || */
6233             !mddev->persistent   != info->not_persistent||
6234             mddev->chunk_sectors != info->chunk_size >> 9 ||
6235             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
6236             ((state^info->state) & 0xfffffe00)
6237                 )
6238                 return -EINVAL;
6239         /* Check there is only one change */
6240         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6241                 cnt++;
6242         if (mddev->raid_disks != info->raid_disks)
6243                 cnt++;
6244         if (mddev->layout != info->layout)
6245                 cnt++;
6246         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
6247                 cnt++;
6248         if (cnt == 0)
6249                 return 0;
6250         if (cnt > 1)
6251                 return -EINVAL;
6252
6253         if (mddev->layout != info->layout) {
6254                 /* Change layout
6255                  * we don't need to do anything at the md level, the
6256                  * personality will take care of it all.
6257                  */
6258                 if (mddev->pers->check_reshape == NULL)
6259                         return -EINVAL;
6260                 else {
6261                         mddev->new_layout = info->layout;
6262                         rv = mddev->pers->check_reshape(mddev);
6263                         if (rv)
6264                                 mddev->new_layout = mddev->layout;
6265                         return rv;
6266                 }
6267         }
6268         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6269                 rv = update_size(mddev, (sector_t)info->size * 2);
6270
6271         if (mddev->raid_disks    != info->raid_disks)
6272                 rv = update_raid_disks(mddev, info->raid_disks);
6273
6274         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
6275                 if (mddev->pers->quiesce == NULL)
6276                         return -EINVAL;
6277                 if (mddev->recovery || mddev->sync_thread)
6278                         return -EBUSY;
6279                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
6280                         /* add the bitmap */
6281                         if (mddev->bitmap)
6282                                 return -EEXIST;
6283                         if (mddev->bitmap_info.default_offset == 0)
6284                                 return -EINVAL;
6285                         mddev->bitmap_info.offset =
6286                                 mddev->bitmap_info.default_offset;
6287                         mddev->bitmap_info.space =
6288                                 mddev->bitmap_info.default_space;
6289                         mddev->pers->quiesce(mddev, 1);
6290                         rv = bitmap_create(mddev);
6291                         if (!rv)
6292                                 rv = bitmap_load(mddev);
6293                         if (rv)
6294                                 bitmap_destroy(mddev);
6295                         mddev->pers->quiesce(mddev, 0);
6296                 } else {
6297                         /* remove the bitmap */
6298                         if (!mddev->bitmap)
6299                                 return -ENOENT;
6300                         if (mddev->bitmap->storage.file)
6301                                 return -EINVAL;
6302                         mddev->pers->quiesce(mddev, 1);
6303                         bitmap_destroy(mddev);
6304                         mddev->pers->quiesce(mddev, 0);
6305                         mddev->bitmap_info.offset = 0;
6306                 }
6307         }
6308         md_update_sb(mddev, 1);
6309         return rv;
6310 }
6311
6312 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
6313 {
6314         struct md_rdev *rdev;
6315         int err = 0;
6316
6317         if (mddev->pers == NULL)
6318                 return -ENODEV;
6319
6320         rcu_read_lock();
6321         rdev = find_rdev_rcu(mddev, dev);
6322         if (!rdev)
6323                 err =  -ENODEV;
6324         else {
6325                 md_error(mddev, rdev);
6326                 if (!test_bit(Faulty, &rdev->flags))
6327                         err = -EBUSY;
6328         }
6329         rcu_read_unlock();
6330         return err;
6331 }
6332
6333 /*
6334  * We have a problem here : there is no easy way to give a CHS
6335  * virtual geometry. We currently pretend that we have a 2 heads
6336  * 4 sectors (with a BIG number of cylinders...). This drives
6337  * dosfs just mad... ;-)
6338  */
6339 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
6340 {
6341         struct mddev *mddev = bdev->bd_disk->private_data;
6342
6343         geo->heads = 2;
6344         geo->sectors = 4;
6345         geo->cylinders = mddev->array_sectors / 8;
6346         return 0;
6347 }
6348
6349 static inline bool md_ioctl_valid(unsigned int cmd)
6350 {
6351         switch (cmd) {
6352         case ADD_NEW_DISK:
6353         case BLKROSET:
6354         case GET_ARRAY_INFO:
6355         case GET_BITMAP_FILE:
6356         case GET_DISK_INFO:
6357         case HOT_ADD_DISK:
6358         case HOT_REMOVE_DISK:
6359         case PRINT_RAID_DEBUG:
6360         case RAID_AUTORUN:
6361         case RAID_VERSION:
6362         case RESTART_ARRAY_RW:
6363         case RUN_ARRAY:
6364         case SET_ARRAY_INFO:
6365         case SET_BITMAP_FILE:
6366         case SET_DISK_FAULTY:
6367         case STOP_ARRAY:
6368         case STOP_ARRAY_RO:
6369                 return true;
6370         default:
6371                 return false;
6372         }
6373 }
6374
6375 static int md_ioctl(struct block_device *bdev, fmode_t mode,
6376                         unsigned int cmd, unsigned long arg)
6377 {
6378         int err = 0;
6379         void __user *argp = (void __user *)arg;
6380         struct mddev *mddev = NULL;
6381         int ro;
6382
6383         if (!md_ioctl_valid(cmd))
6384                 return -ENOTTY;
6385
6386         switch (cmd) {
6387         case RAID_VERSION:
6388         case GET_ARRAY_INFO:
6389         case GET_DISK_INFO:
6390                 break;
6391         default:
6392                 if (!capable(CAP_SYS_ADMIN))
6393                         return -EACCES;
6394         }
6395
6396         /*
6397          * Commands dealing with the RAID driver but not any
6398          * particular array:
6399          */
6400         switch (cmd) {
6401         case RAID_VERSION:
6402                 err = get_version(argp);
6403                 goto done;
6404
6405         case PRINT_RAID_DEBUG:
6406                 err = 0;
6407                 md_print_devices();
6408                 goto done;
6409
6410 #ifndef MODULE
6411         case RAID_AUTORUN:
6412                 err = 0;
6413                 autostart_arrays(arg);
6414                 goto done;
6415 #endif
6416         default:;
6417         }
6418
6419         /*
6420          * Commands creating/starting a new array:
6421          */
6422
6423         mddev = bdev->bd_disk->private_data;
6424
6425         if (!mddev) {
6426                 BUG();
6427                 goto abort;
6428         }
6429
6430         /* Some actions do not requires the mutex */
6431         switch (cmd) {
6432         case GET_ARRAY_INFO:
6433                 if (!mddev->raid_disks && !mddev->external)
6434                         err = -ENODEV;
6435                 else
6436                         err = get_array_info(mddev, argp);
6437                 goto abort;
6438
6439         case GET_DISK_INFO:
6440                 if (!mddev->raid_disks && !mddev->external)
6441                         err = -ENODEV;
6442                 else
6443                         err = get_disk_info(mddev, argp);
6444                 goto abort;
6445
6446         case SET_DISK_FAULTY:
6447                 err = set_disk_faulty(mddev, new_decode_dev(arg));
6448                 goto abort;
6449         }
6450
6451         if (cmd == ADD_NEW_DISK)
6452                 /* need to ensure md_delayed_delete() has completed */
6453                 flush_workqueue(md_misc_wq);
6454
6455         if (cmd == HOT_REMOVE_DISK)
6456                 /* need to ensure recovery thread has run */
6457                 wait_event_interruptible_timeout(mddev->sb_wait,
6458                                                  !test_bit(MD_RECOVERY_NEEDED,
6459                                                            &mddev->flags),
6460                                                  msecs_to_jiffies(5000));
6461         if (cmd == STOP_ARRAY || cmd == STOP_ARRAY_RO) {
6462                 /* Need to flush page cache, and ensure no-one else opens
6463                  * and writes
6464                  */
6465                 mutex_lock(&mddev->open_mutex);
6466                 if (atomic_read(&mddev->openers) > 1) {
6467                         mutex_unlock(&mddev->open_mutex);
6468                         err = -EBUSY;
6469                         goto abort;
6470                 }
6471                 set_bit(MD_STILL_CLOSED, &mddev->flags);
6472                 mutex_unlock(&mddev->open_mutex);
6473                 sync_blockdev(bdev);
6474         }
6475         err = mddev_lock(mddev);
6476         if (err) {
6477                 printk(KERN_INFO 
6478                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
6479                         err, cmd);
6480                 goto abort;
6481         }
6482
6483         if (cmd == SET_ARRAY_INFO) {
6484                 mdu_array_info_t info;
6485                 if (!arg)
6486                         memset(&info, 0, sizeof(info));
6487                 else if (copy_from_user(&info, argp, sizeof(info))) {
6488                         err = -EFAULT;
6489                         goto abort_unlock;
6490                 }
6491                 if (mddev->pers) {
6492                         err = update_array_info(mddev, &info);
6493                         if (err) {
6494                                 printk(KERN_WARNING "md: couldn't update"
6495                                        " array info. %d\n", err);
6496                                 goto abort_unlock;
6497                         }
6498                         goto done_unlock;
6499                 }
6500                 if (!list_empty(&mddev->disks)) {
6501                         printk(KERN_WARNING
6502                                "md: array %s already has disks!\n",
6503                                mdname(mddev));
6504                         err = -EBUSY;
6505                         goto abort_unlock;
6506                 }
6507                 if (mddev->raid_disks) {
6508                         printk(KERN_WARNING
6509                                "md: array %s already initialised!\n",
6510                                mdname(mddev));
6511                         err = -EBUSY;
6512                         goto abort_unlock;
6513                 }
6514                 err = set_array_info(mddev, &info);
6515                 if (err) {
6516                         printk(KERN_WARNING "md: couldn't set"
6517                                " array info. %d\n", err);
6518                         goto abort_unlock;
6519                 }
6520                 goto done_unlock;
6521         }
6522
6523         /*
6524          * Commands querying/configuring an existing array:
6525          */
6526         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
6527          * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
6528         if ((!mddev->raid_disks && !mddev->external)
6529             && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
6530             && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
6531             && cmd != GET_BITMAP_FILE) {
6532                 err = -ENODEV;
6533                 goto abort_unlock;
6534         }
6535
6536         /*
6537          * Commands even a read-only array can execute:
6538          */
6539         switch (cmd) {
6540         case GET_BITMAP_FILE:
6541                 err = get_bitmap_file(mddev, argp);
6542                 goto done_unlock;
6543
6544         case RESTART_ARRAY_RW:
6545                 err = restart_array(mddev);
6546                 goto done_unlock;
6547
6548         case STOP_ARRAY:
6549                 err = do_md_stop(mddev, 0, bdev);
6550                 goto done_unlock;
6551
6552         case STOP_ARRAY_RO:
6553                 err = md_set_readonly(mddev, bdev);
6554                 goto done_unlock;
6555
6556         case HOT_REMOVE_DISK:
6557                 err = hot_remove_disk(mddev, new_decode_dev(arg));
6558                 goto done_unlock;
6559
6560         case ADD_NEW_DISK:
6561                 /* We can support ADD_NEW_DISK on read-only arrays
6562                  * on if we are re-adding a preexisting device.
6563                  * So require mddev->pers and MD_DISK_SYNC.
6564                  */
6565                 if (mddev->pers) {
6566                         mdu_disk_info_t info;
6567                         if (copy_from_user(&info, argp, sizeof(info)))
6568                                 err = -EFAULT;
6569                         else if (!(info.state & (1<<MD_DISK_SYNC)))
6570                                 /* Need to clear read-only for this */
6571                                 break;
6572                         else
6573                                 err = add_new_disk(mddev, &info);
6574                         goto done_unlock;
6575                 }
6576                 break;
6577
6578         case BLKROSET:
6579                 if (get_user(ro, (int __user *)(arg))) {
6580                         err = -EFAULT;
6581                         goto done_unlock;
6582                 }
6583                 err = -EINVAL;
6584
6585                 /* if the bdev is going readonly the value of mddev->ro
6586                  * does not matter, no writes are coming
6587                  */
6588                 if (ro)
6589                         goto done_unlock;
6590
6591                 /* are we are already prepared for writes? */
6592                 if (mddev->ro != 1)
6593                         goto done_unlock;
6594
6595                 /* transitioning to readauto need only happen for
6596                  * arrays that call md_write_start
6597                  */
6598                 if (mddev->pers) {
6599                         err = restart_array(mddev);
6600                         if (err == 0) {
6601                                 mddev->ro = 2;
6602                                 set_disk_ro(mddev->gendisk, 0);
6603                         }
6604                 }
6605                 goto done_unlock;
6606         }
6607
6608         /*
6609          * The remaining ioctls are changing the state of the
6610          * superblock, so we do not allow them on read-only arrays.
6611          * However non-MD ioctls (e.g. get-size) will still come through
6612          * here and hit the 'default' below, so only disallow
6613          * 'md' ioctls, and switch to rw mode if started auto-readonly.
6614          */
6615         if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
6616                 if (mddev->ro == 2) {
6617                         mddev->ro = 0;
6618                         sysfs_notify_dirent_safe(mddev->sysfs_state);
6619                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6620                         /* mddev_unlock will wake thread */
6621                         /* If a device failed while we were read-only, we
6622                          * need to make sure the metadata is updated now.
6623                          */
6624                         if (test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
6625                                 mddev_unlock(mddev);
6626                                 wait_event(mddev->sb_wait,
6627                                            !test_bit(MD_CHANGE_DEVS, &mddev->flags) &&
6628                                            !test_bit(MD_CHANGE_PENDING, &mddev->flags));
6629                                 mddev_lock_nointr(mddev);
6630                         }
6631                 } else {
6632                         err = -EROFS;
6633                         goto abort_unlock;
6634                 }
6635         }
6636
6637         switch (cmd) {
6638         case ADD_NEW_DISK:
6639         {
6640                 mdu_disk_info_t info;
6641                 if (copy_from_user(&info, argp, sizeof(info)))
6642                         err = -EFAULT;
6643                 else
6644                         err = add_new_disk(mddev, &info);
6645                 goto done_unlock;
6646         }
6647
6648         case HOT_ADD_DISK:
6649                 err = hot_add_disk(mddev, new_decode_dev(arg));
6650                 goto done_unlock;
6651
6652         case RUN_ARRAY:
6653                 err = do_md_run(mddev);
6654                 goto done_unlock;
6655
6656         case SET_BITMAP_FILE:
6657                 err = set_bitmap_file(mddev, (int)arg);
6658                 goto done_unlock;
6659
6660         default:
6661                 err = -EINVAL;
6662                 goto abort_unlock;
6663         }
6664
6665 done_unlock:
6666 abort_unlock:
6667         if (mddev->hold_active == UNTIL_IOCTL &&
6668             err != -EINVAL)
6669                 mddev->hold_active = 0;
6670         mddev_unlock(mddev);
6671
6672         return err;
6673 done:
6674         if (err)
6675                 MD_BUG();
6676 abort:
6677         return err;
6678 }
6679 #ifdef CONFIG_COMPAT
6680 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
6681                     unsigned int cmd, unsigned long arg)
6682 {
6683         switch (cmd) {
6684         case HOT_REMOVE_DISK:
6685         case HOT_ADD_DISK:
6686         case SET_DISK_FAULTY:
6687         case SET_BITMAP_FILE:
6688                 /* These take in integer arg, do not convert */
6689                 break;
6690         default:
6691                 arg = (unsigned long)compat_ptr(arg);
6692                 break;
6693         }
6694
6695         return md_ioctl(bdev, mode, cmd, arg);
6696 }
6697 #endif /* CONFIG_COMPAT */
6698
6699 static int md_open(struct block_device *bdev, fmode_t mode)
6700 {
6701         /*
6702          * Succeed if we can lock the mddev, which confirms that
6703          * it isn't being stopped right now.
6704          */
6705         struct mddev *mddev = mddev_find(bdev->bd_dev);
6706         int err;
6707
6708         if (!mddev)
6709                 return -ENODEV;
6710
6711         if (mddev->gendisk != bdev->bd_disk) {
6712                 /* we are racing with mddev_put which is discarding this
6713                  * bd_disk.
6714                  */
6715                 mddev_put(mddev);
6716                 /* Wait until bdev->bd_disk is definitely gone */
6717                 flush_workqueue(md_misc_wq);
6718                 /* Then retry the open from the top */
6719                 return -ERESTARTSYS;
6720         }
6721         BUG_ON(mddev != bdev->bd_disk->private_data);
6722
6723         if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
6724                 goto out;
6725
6726         err = 0;
6727         atomic_inc(&mddev->openers);
6728         clear_bit(MD_STILL_CLOSED, &mddev->flags);
6729         mutex_unlock(&mddev->open_mutex);
6730
6731         check_disk_change(bdev);
6732  out:
6733         return err;
6734 }
6735
6736 static void md_release(struct gendisk *disk, fmode_t mode)
6737 {
6738         struct mddev *mddev = disk->private_data;
6739
6740         BUG_ON(!mddev);
6741         atomic_dec(&mddev->openers);
6742         mddev_put(mddev);
6743 }
6744
6745 static int md_media_changed(struct gendisk *disk)
6746 {
6747         struct mddev *mddev = disk->private_data;
6748
6749         return mddev->changed;
6750 }
6751
6752 static int md_revalidate(struct gendisk *disk)
6753 {
6754         struct mddev *mddev = disk->private_data;
6755
6756         mddev->changed = 0;
6757         return 0;
6758 }
6759 static const struct block_device_operations md_fops =
6760 {
6761         .owner          = THIS_MODULE,
6762         .open           = md_open,
6763         .release        = md_release,
6764         .ioctl          = md_ioctl,
6765 #ifdef CONFIG_COMPAT
6766         .compat_ioctl   = md_compat_ioctl,
6767 #endif
6768         .getgeo         = md_getgeo,
6769         .media_changed  = md_media_changed,
6770         .revalidate_disk= md_revalidate,
6771 };
6772
6773 static int md_thread(void * arg)
6774 {
6775         struct md_thread *thread = arg;
6776
6777         /*
6778          * md_thread is a 'system-thread', it's priority should be very
6779          * high. We avoid resource deadlocks individually in each
6780          * raid personality. (RAID5 does preallocation) We also use RR and
6781          * the very same RT priority as kswapd, thus we will never get
6782          * into a priority inversion deadlock.
6783          *
6784          * we definitely have to have equal or higher priority than
6785          * bdflush, otherwise bdflush will deadlock if there are too
6786          * many dirty RAID5 blocks.
6787          */
6788
6789         allow_signal(SIGKILL);
6790         while (!kthread_should_stop()) {
6791
6792                 /* We need to wait INTERRUPTIBLE so that
6793                  * we don't add to the load-average.
6794                  * That means we need to be sure no signals are
6795                  * pending
6796                  */
6797                 if (signal_pending(current))
6798                         flush_signals(current);
6799
6800                 wait_event_interruptible_timeout
6801                         (thread->wqueue,
6802                          test_bit(THREAD_WAKEUP, &thread->flags)
6803                          || kthread_should_stop(),
6804                          thread->timeout);
6805
6806                 clear_bit(THREAD_WAKEUP, &thread->flags);
6807                 if (!kthread_should_stop())
6808                         thread->run(thread);
6809         }
6810
6811         return 0;
6812 }
6813
6814 void md_wakeup_thread(struct md_thread *thread)
6815 {
6816         if (thread) {
6817                 pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
6818                 set_bit(THREAD_WAKEUP, &thread->flags);
6819                 wake_up(&thread->wqueue);
6820         }
6821 }
6822
6823 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
6824                 struct mddev *mddev, const char *name)
6825 {
6826         struct md_thread *thread;
6827
6828         thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
6829         if (!thread)
6830                 return NULL;
6831
6832         init_waitqueue_head(&thread->wqueue);
6833
6834         thread->run = run;
6835         thread->mddev = mddev;
6836         thread->timeout = MAX_SCHEDULE_TIMEOUT;
6837         thread->tsk = kthread_run(md_thread, thread,
6838                                   "%s_%s",
6839                                   mdname(thread->mddev),
6840                                   name);
6841         if (IS_ERR(thread->tsk)) {
6842                 kfree(thread);
6843                 return NULL;
6844         }
6845         return thread;
6846 }
6847
6848 void md_unregister_thread(struct md_thread **threadp)
6849 {
6850         struct md_thread *thread = *threadp;
6851         if (!thread)
6852                 return;
6853         pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
6854         /* Locking ensures that mddev_unlock does not wake_up a
6855          * non-existent thread
6856          */
6857         spin_lock(&pers_lock);
6858         *threadp = NULL;
6859         spin_unlock(&pers_lock);
6860
6861         kthread_stop(thread->tsk);
6862         kfree(thread);
6863 }
6864
6865 void md_error(struct mddev *mddev, struct md_rdev *rdev)
6866 {
6867         if (!mddev) {
6868                 MD_BUG();
6869                 return;
6870         }
6871
6872         if (!rdev || test_bit(Faulty, &rdev->flags))
6873                 return;
6874
6875         if (!mddev->pers || !mddev->pers->error_handler)
6876                 return;
6877         mddev->pers->error_handler(mddev,rdev);
6878         if (mddev->degraded)
6879                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6880         sysfs_notify_dirent_safe(rdev->sysfs_state);
6881         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6882         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6883         md_wakeup_thread(mddev->thread);
6884         if (mddev->event_work.func)
6885                 queue_work(md_misc_wq, &mddev->event_work);
6886         md_new_event_inintr(mddev);
6887 }
6888
6889 /* seq_file implementation /proc/mdstat */
6890
6891 static void status_unused(struct seq_file *seq)
6892 {
6893         int i = 0;
6894         struct md_rdev *rdev;
6895
6896         seq_printf(seq, "unused devices: ");
6897
6898         list_for_each_entry(rdev, &pending_raid_disks, same_set) {
6899                 char b[BDEVNAME_SIZE];
6900                 i++;
6901                 seq_printf(seq, "%s ",
6902                               bdevname(rdev->bdev,b));
6903         }
6904         if (!i)
6905                 seq_printf(seq, "<none>");
6906
6907         seq_printf(seq, "\n");
6908 }
6909
6910
6911 static void status_resync(struct seq_file *seq, struct mddev * mddev)
6912 {
6913         sector_t max_sectors, resync, res;
6914         unsigned long dt, db;
6915         sector_t rt;
6916         int scale;
6917         unsigned int per_milli;
6918
6919         if (mddev->curr_resync <= 3)
6920                 resync = 0;
6921         else
6922                 resync = mddev->curr_resync
6923                         - atomic_read(&mddev->recovery_active);
6924
6925         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
6926             test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6927                 max_sectors = mddev->resync_max_sectors;
6928         else
6929                 max_sectors = mddev->dev_sectors;
6930
6931         /*
6932          * Should not happen.
6933          */
6934         if (!max_sectors) {
6935                 MD_BUG();
6936                 return;
6937         }
6938         /* Pick 'scale' such that (resync>>scale)*1000 will fit
6939          * in a sector_t, and (max_sectors>>scale) will fit in a
6940          * u32, as those are the requirements for sector_div.
6941          * Thus 'scale' must be at least 10
6942          */
6943         scale = 10;
6944         if (sizeof(sector_t) > sizeof(unsigned long)) {
6945                 while ( max_sectors/2 > (1ULL<<(scale+32)))
6946                         scale++;
6947         }
6948         res = (resync>>scale)*1000;
6949         sector_div(res, (u32)((max_sectors>>scale)+1));
6950
6951         per_milli = res;
6952         {
6953                 int i, x = per_milli/50, y = 20-x;
6954                 seq_printf(seq, "[");
6955                 for (i = 0; i < x; i++)
6956                         seq_printf(seq, "=");
6957                 seq_printf(seq, ">");
6958                 for (i = 0; i < y; i++)
6959                         seq_printf(seq, ".");
6960                 seq_printf(seq, "] ");
6961         }
6962         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
6963                    (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
6964                     "reshape" :
6965                     (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
6966                      "check" :
6967                      (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
6968                       "resync" : "recovery"))),
6969                    per_milli/10, per_milli % 10,
6970                    (unsigned long long) resync/2,
6971                    (unsigned long long) max_sectors/2);
6972
6973         /*
6974          * dt: time from mark until now
6975          * db: blocks written from mark until now
6976          * rt: remaining time
6977          *
6978          * rt is a sector_t, so could be 32bit or 64bit.
6979          * So we divide before multiply in case it is 32bit and close
6980          * to the limit.
6981          * We scale the divisor (db) by 32 to avoid losing precision
6982          * near the end of resync when the number of remaining sectors
6983          * is close to 'db'.
6984          * We then divide rt by 32 after multiplying by db to compensate.
6985          * The '+1' avoids division by zero if db is very small.
6986          */
6987         dt = ((jiffies - mddev->resync_mark) / HZ);
6988         if (!dt) dt++;
6989         db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
6990                 - mddev->resync_mark_cnt;
6991
6992         rt = max_sectors - resync;    /* number of remaining sectors */
6993         sector_div(rt, db/32+1);
6994         rt *= dt;
6995         rt >>= 5;
6996
6997         seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
6998                    ((unsigned long)rt % 60)/6);
6999
7000         seq_printf(seq, " speed=%ldK/sec", db/2/dt);
7001 }
7002
7003 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
7004 {
7005         struct list_head *tmp;
7006         loff_t l = *pos;
7007         struct mddev *mddev;
7008
7009         if (l >= 0x10000)
7010                 return NULL;
7011         if (!l--)
7012                 /* header */
7013                 return (void*)1;
7014
7015         spin_lock(&all_mddevs_lock);
7016         list_for_each(tmp,&all_mddevs)
7017                 if (!l--) {
7018                         mddev = list_entry(tmp, struct mddev, all_mddevs);
7019                         mddev_get(mddev);
7020                         spin_unlock(&all_mddevs_lock);
7021                         return mddev;
7022                 }
7023         spin_unlock(&all_mddevs_lock);
7024         if (!l--)
7025                 return (void*)2;/* tail */
7026         return NULL;
7027 }
7028
7029 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
7030 {
7031         struct list_head *tmp;
7032         struct mddev *next_mddev, *mddev = v;
7033         
7034         ++*pos;
7035         if (v == (void*)2)
7036                 return NULL;
7037
7038         spin_lock(&all_mddevs_lock);
7039         if (v == (void*)1)
7040                 tmp = all_mddevs.next;
7041         else
7042                 tmp = mddev->all_mddevs.next;
7043         if (tmp != &all_mddevs)
7044                 next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
7045         else {
7046                 next_mddev = (void*)2;
7047                 *pos = 0x10000;
7048         }               
7049         spin_unlock(&all_mddevs_lock);
7050
7051         if (v != (void*)1)
7052                 mddev_put(mddev);
7053         return next_mddev;
7054
7055 }
7056
7057 static void md_seq_stop(struct seq_file *seq, void *v)
7058 {
7059         struct mddev *mddev = v;
7060
7061         if (mddev && v != (void*)1 && v != (void*)2)
7062                 mddev_put(mddev);
7063 }
7064
7065 static int md_seq_show(struct seq_file *seq, void *v)
7066 {
7067         struct mddev *mddev = v;
7068         sector_t sectors;
7069         struct md_rdev *rdev;
7070
7071         if (v == (void*)1) {
7072                 struct md_personality *pers;
7073                 seq_printf(seq, "Personalities : ");
7074                 spin_lock(&pers_lock);
7075                 list_for_each_entry(pers, &pers_list, list)
7076                         seq_printf(seq, "[%s] ", pers->name);
7077
7078                 spin_unlock(&pers_lock);
7079                 seq_printf(seq, "\n");
7080                 seq->poll_event = atomic_read(&md_event_count);
7081                 return 0;
7082         }
7083         if (v == (void*)2) {
7084                 status_unused(seq);
7085                 return 0;
7086         }
7087
7088         if (mddev_lock(mddev) < 0)
7089                 return -EINTR;
7090
7091         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
7092                 seq_printf(seq, "%s : %sactive", mdname(mddev),
7093                                                 mddev->pers ? "" : "in");
7094                 if (mddev->pers) {
7095                         if (mddev->ro==1)
7096                                 seq_printf(seq, " (read-only)");
7097                         if (mddev->ro==2)
7098                                 seq_printf(seq, " (auto-read-only)");
7099                         seq_printf(seq, " %s", mddev->pers->name);
7100                 }
7101
7102                 sectors = 0;
7103                 rdev_for_each(rdev, mddev) {
7104                         char b[BDEVNAME_SIZE];
7105                         seq_printf(seq, " %s[%d]",
7106                                 bdevname(rdev->bdev,b), rdev->desc_nr);
7107                         if (test_bit(WriteMostly, &rdev->flags))
7108                                 seq_printf(seq, "(W)");
7109                         if (test_bit(Faulty, &rdev->flags)) {
7110                                 seq_printf(seq, "(F)");
7111                                 continue;
7112                         }
7113                         if (rdev->raid_disk < 0)
7114                                 seq_printf(seq, "(S)"); /* spare */
7115                         if (test_bit(Replacement, &rdev->flags))
7116                                 seq_printf(seq, "(R)");
7117                         sectors += rdev->sectors;
7118                 }
7119
7120                 if (!list_empty(&mddev->disks)) {
7121                         if (mddev->pers)
7122                                 seq_printf(seq, "\n      %llu blocks",
7123                                            (unsigned long long)
7124                                            mddev->array_sectors / 2);
7125                         else
7126                                 seq_printf(seq, "\n      %llu blocks",
7127                                            (unsigned long long)sectors / 2);
7128                 }
7129                 if (mddev->persistent) {
7130                         if (mddev->major_version != 0 ||
7131                             mddev->minor_version != 90) {
7132                                 seq_printf(seq," super %d.%d",
7133                                            mddev->major_version,
7134                                            mddev->minor_version);
7135                         }
7136                 } else if (mddev->external)
7137                         seq_printf(seq, " super external:%s",
7138                                    mddev->metadata_type);
7139                 else
7140                         seq_printf(seq, " super non-persistent");
7141
7142                 if (mddev->pers) {
7143                         mddev->pers->status(seq, mddev);
7144                         seq_printf(seq, "\n      ");
7145                         if (mddev->pers->sync_request) {
7146                                 if (mddev->curr_resync > 2) {
7147                                         status_resync(seq, mddev);
7148                                         seq_printf(seq, "\n      ");
7149                                 } else if (mddev->curr_resync >= 1)
7150                                         seq_printf(seq, "\tresync=DELAYED\n      ");
7151                                 else if (mddev->recovery_cp < MaxSector)
7152                                         seq_printf(seq, "\tresync=PENDING\n      ");
7153                         }
7154                 } else
7155                         seq_printf(seq, "\n       ");
7156
7157                 bitmap_status(seq, mddev->bitmap);
7158
7159                 seq_printf(seq, "\n");
7160         }
7161         mddev_unlock(mddev);
7162         
7163         return 0;
7164 }
7165
7166 static const struct seq_operations md_seq_ops = {
7167         .start  = md_seq_start,
7168         .next   = md_seq_next,
7169         .stop   = md_seq_stop,
7170         .show   = md_seq_show,
7171 };
7172
7173 static int md_seq_open(struct inode *inode, struct file *file)
7174 {
7175         struct seq_file *seq;
7176         int error;
7177
7178         error = seq_open(file, &md_seq_ops);
7179         if (error)
7180                 return error;
7181
7182         seq = file->private_data;
7183         seq->poll_event = atomic_read(&md_event_count);
7184         return error;
7185 }
7186
7187 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
7188 {
7189         struct seq_file *seq = filp->private_data;
7190         int mask;
7191
7192         poll_wait(filp, &md_event_waiters, wait);
7193
7194         /* always allow read */
7195         mask = POLLIN | POLLRDNORM;
7196
7197         if (seq->poll_event != atomic_read(&md_event_count))
7198                 mask |= POLLERR | POLLPRI;
7199         return mask;
7200 }
7201
7202 static const struct file_operations md_seq_fops = {
7203         .owner          = THIS_MODULE,
7204         .open           = md_seq_open,
7205         .read           = seq_read,
7206         .llseek         = seq_lseek,
7207         .release        = seq_release_private,
7208         .poll           = mdstat_poll,
7209 };
7210
7211 int register_md_personality(struct md_personality *p)
7212 {
7213         spin_lock(&pers_lock);
7214         list_add_tail(&p->list, &pers_list);
7215         printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
7216         spin_unlock(&pers_lock);
7217         return 0;
7218 }
7219
7220 int unregister_md_personality(struct md_personality *p)
7221 {
7222         printk(KERN_INFO "md: %s personality unregistered\n", p->name);
7223         spin_lock(&pers_lock);
7224         list_del_init(&p->list);
7225         spin_unlock(&pers_lock);
7226         return 0;
7227 }
7228
7229 static int is_mddev_idle(struct mddev *mddev, int init)
7230 {
7231         struct md_rdev * rdev;
7232         int idle;
7233         int curr_events;
7234
7235         idle = 1;
7236         rcu_read_lock();
7237         rdev_for_each_rcu(rdev, mddev) {
7238                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
7239                 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
7240                               (int)part_stat_read(&disk->part0, sectors[1]) -
7241                               atomic_read(&disk->sync_io);
7242                 /* sync IO will cause sync_io to increase before the disk_stats
7243                  * as sync_io is counted when a request starts, and
7244                  * disk_stats is counted when it completes.
7245                  * So resync activity will cause curr_events to be smaller than
7246                  * when there was no such activity.
7247                  * non-sync IO will cause disk_stat to increase without
7248                  * increasing sync_io so curr_events will (eventually)
7249                  * be larger than it was before.  Once it becomes
7250                  * substantially larger, the test below will cause
7251                  * the array to appear non-idle, and resync will slow
7252                  * down.
7253                  * If there is a lot of outstanding resync activity when
7254                  * we set last_event to curr_events, then all that activity
7255                  * completing might cause the array to appear non-idle
7256                  * and resync will be slowed down even though there might
7257                  * not have been non-resync activity.  This will only
7258                  * happen once though.  'last_events' will soon reflect
7259                  * the state where there is little or no outstanding
7260                  * resync requests, and further resync activity will
7261                  * always make curr_events less than last_events.
7262                  *
7263                  */
7264                 if (init || curr_events - rdev->last_events > 64) {
7265                         rdev->last_events = curr_events;
7266                         idle = 0;
7267                 }
7268         }
7269         rcu_read_unlock();
7270         return idle;
7271 }
7272
7273 void md_done_sync(struct mddev *mddev, int blocks, int ok)
7274 {
7275         /* another "blocks" (512byte) blocks have been synced */
7276         atomic_sub(blocks, &mddev->recovery_active);
7277         wake_up(&mddev->recovery_wait);
7278         if (!ok) {
7279                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7280                 set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
7281                 md_wakeup_thread(mddev->thread);
7282                 // stop recovery, signal do_sync ....
7283         }
7284 }
7285
7286
7287 /* md_write_start(mddev, bi)
7288  * If we need to update some array metadata (e.g. 'active' flag
7289  * in superblock) before writing, schedule a superblock update
7290  * and wait for it to complete.
7291  */
7292 void md_write_start(struct mddev *mddev, struct bio *bi)
7293 {
7294         int did_change = 0;
7295         if (bio_data_dir(bi) != WRITE)
7296                 return;
7297
7298         BUG_ON(mddev->ro == 1);
7299         if (mddev->ro == 2) {
7300                 /* need to switch to read/write */
7301                 mddev->ro = 0;
7302                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7303                 md_wakeup_thread(mddev->thread);
7304                 md_wakeup_thread(mddev->sync_thread);
7305                 did_change = 1;
7306         }
7307         atomic_inc(&mddev->writes_pending);
7308         if (mddev->safemode == 1)
7309                 mddev->safemode = 0;
7310         if (mddev->in_sync) {
7311                 spin_lock_irq(&mddev->write_lock);
7312                 if (mddev->in_sync) {
7313                         mddev->in_sync = 0;
7314                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7315                         set_bit(MD_CHANGE_PENDING, &mddev->flags);
7316                         md_wakeup_thread(mddev->thread);
7317                         did_change = 1;
7318                 }
7319                 spin_unlock_irq(&mddev->write_lock);
7320         }
7321         if (did_change)
7322                 sysfs_notify_dirent_safe(mddev->sysfs_state);
7323         wait_event(mddev->sb_wait,
7324                    !test_bit(MD_CHANGE_PENDING, &mddev->flags));
7325 }
7326
7327 void md_write_end(struct mddev *mddev)
7328 {
7329         if (atomic_dec_and_test(&mddev->writes_pending)) {
7330                 if (mddev->safemode == 2)
7331                         md_wakeup_thread(mddev->thread);
7332                 else if (mddev->safemode_delay)
7333                         mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
7334         }
7335 }
7336
7337 /* md_allow_write(mddev)
7338  * Calling this ensures that the array is marked 'active' so that writes
7339  * may proceed without blocking.  It is important to call this before
7340  * attempting a GFP_KERNEL allocation while holding the mddev lock.
7341  * Must be called with mddev_lock held.
7342  *
7343  * In the ->external case MD_CHANGE_CLEAN can not be cleared until mddev->lock
7344  * is dropped, so return -EAGAIN after notifying userspace.
7345  */
7346 int md_allow_write(struct mddev *mddev)
7347 {
7348         if (!mddev->pers)
7349                 return 0;
7350         if (mddev->ro)
7351                 return 0;
7352         if (!mddev->pers->sync_request)
7353                 return 0;
7354
7355         spin_lock_irq(&mddev->write_lock);
7356         if (mddev->in_sync) {
7357                 mddev->in_sync = 0;
7358                 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7359                 set_bit(MD_CHANGE_PENDING, &mddev->flags);
7360                 if (mddev->safemode_delay &&
7361                     mddev->safemode == 0)
7362                         mddev->safemode = 1;
7363                 spin_unlock_irq(&mddev->write_lock);
7364                 md_update_sb(mddev, 0);
7365                 sysfs_notify_dirent_safe(mddev->sysfs_state);
7366         } else
7367                 spin_unlock_irq(&mddev->write_lock);
7368
7369         if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
7370                 return -EAGAIN;
7371         else
7372                 return 0;
7373 }
7374 EXPORT_SYMBOL_GPL(md_allow_write);
7375
7376 #define SYNC_MARKS      10
7377 #define SYNC_MARK_STEP  (3*HZ)
7378 #define UPDATE_FREQUENCY (5*60*HZ)
7379 void md_do_sync(struct md_thread *thread)
7380 {
7381         struct mddev *mddev = thread->mddev;
7382         struct mddev *mddev2;
7383         unsigned int currspeed = 0,
7384                  window;
7385         sector_t max_sectors,j, io_sectors;
7386         unsigned long mark[SYNC_MARKS];
7387         unsigned long update_time;
7388         sector_t mark_cnt[SYNC_MARKS];
7389         int last_mark,m;
7390         struct list_head *tmp;
7391         sector_t last_check;
7392         int skipped = 0;
7393         struct md_rdev *rdev;
7394         char *desc, *action = NULL;
7395         struct blk_plug plug;
7396
7397         /* just incase thread restarts... */
7398         if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
7399                 return;
7400         if (mddev->ro) /* never try to sync a read-only array */
7401                 return;
7402
7403         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7404                 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
7405                         desc = "data-check";
7406                         action = "check";
7407                 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
7408                         desc = "requested-resync";
7409                         action = "repair";
7410                 } else
7411                         desc = "resync";
7412         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7413                 desc = "reshape";
7414         else
7415                 desc = "recovery";
7416
7417         mddev->last_sync_action = action ?: desc;
7418
7419         /* we overload curr_resync somewhat here.
7420          * 0 == not engaged in resync at all
7421          * 2 == checking that there is no conflict with another sync
7422          * 1 == like 2, but have yielded to allow conflicting resync to
7423          *              commense
7424          * other == active in resync - this many blocks
7425          *
7426          * Before starting a resync we must have set curr_resync to
7427          * 2, and then checked that every "conflicting" array has curr_resync
7428          * less than ours.  When we find one that is the same or higher
7429          * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
7430          * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
7431          * This will mean we have to start checking from the beginning again.
7432          *
7433          */
7434
7435         do {
7436                 mddev->curr_resync = 2;
7437
7438         try_again:
7439                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7440                         goto skip;
7441                 for_each_mddev(mddev2, tmp) {
7442                         if (mddev2 == mddev)
7443                                 continue;
7444                         if (!mddev->parallel_resync
7445                         &&  mddev2->curr_resync
7446                         &&  match_mddev_units(mddev, mddev2)) {
7447                                 DEFINE_WAIT(wq);
7448                                 if (mddev < mddev2 && mddev->curr_resync == 2) {
7449                                         /* arbitrarily yield */
7450                                         mddev->curr_resync = 1;
7451                                         wake_up(&resync_wait);
7452                                 }
7453                                 if (mddev > mddev2 && mddev->curr_resync == 1)
7454                                         /* no need to wait here, we can wait the next
7455                                          * time 'round when curr_resync == 2
7456                                          */
7457                                         continue;
7458                                 /* We need to wait 'interruptible' so as not to
7459                                  * contribute to the load average, and not to
7460                                  * be caught by 'softlockup'
7461                                  */
7462                                 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
7463                                 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
7464                                     mddev2->curr_resync >= mddev->curr_resync) {
7465                                         printk(KERN_INFO "md: delaying %s of %s"
7466                                                " until %s has finished (they"
7467                                                " share one or more physical units)\n",
7468                                                desc, mdname(mddev), mdname(mddev2));
7469                                         mddev_put(mddev2);
7470                                         if (signal_pending(current))
7471                                                 flush_signals(current);
7472                                         schedule();
7473                                         finish_wait(&resync_wait, &wq);
7474                                         goto try_again;
7475                                 }
7476                                 finish_wait(&resync_wait, &wq);
7477                         }
7478                 }
7479         } while (mddev->curr_resync < 2);
7480
7481         j = 0;
7482         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7483                 /* resync follows the size requested by the personality,
7484                  * which defaults to physical size, but can be virtual size
7485                  */
7486                 max_sectors = mddev->resync_max_sectors;
7487                 atomic64_set(&mddev->resync_mismatches, 0);
7488                 /* we don't use the checkpoint if there's a bitmap */
7489                 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7490                         j = mddev->resync_min;
7491                 else if (!mddev->bitmap)
7492                         j = mddev->recovery_cp;
7493
7494         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7495                 max_sectors = mddev->resync_max_sectors;
7496         else {
7497                 /* recovery follows the physical size of devices */
7498                 max_sectors = mddev->dev_sectors;
7499                 j = MaxSector;
7500                 rcu_read_lock();
7501                 rdev_for_each_rcu(rdev, mddev)
7502                         if (rdev->raid_disk >= 0 &&
7503                             !test_bit(Faulty, &rdev->flags) &&
7504                             !test_bit(In_sync, &rdev->flags) &&
7505                             rdev->recovery_offset < j)
7506                                 j = rdev->recovery_offset;
7507                 rcu_read_unlock();
7508         }
7509
7510         printk(KERN_INFO "md: %s of RAID array %s\n", desc, mdname(mddev));
7511         printk(KERN_INFO "md: minimum _guaranteed_  speed:"
7512                 " %d KB/sec/disk.\n", speed_min(mddev));
7513         printk(KERN_INFO "md: using maximum available idle IO bandwidth "
7514                "(but not more than %d KB/sec) for %s.\n",
7515                speed_max(mddev), desc);
7516
7517         is_mddev_idle(mddev, 1); /* this initializes IO event counters */
7518
7519         io_sectors = 0;
7520         for (m = 0; m < SYNC_MARKS; m++) {
7521                 mark[m] = jiffies;
7522                 mark_cnt[m] = io_sectors;
7523         }
7524         last_mark = 0;
7525         mddev->resync_mark = mark[last_mark];
7526         mddev->resync_mark_cnt = mark_cnt[last_mark];
7527
7528         /*
7529          * Tune reconstruction:
7530          */
7531         window = 32*(PAGE_SIZE/512);
7532         printk(KERN_INFO "md: using %dk window, over a total of %lluk.\n",
7533                 window/2, (unsigned long long)max_sectors/2);
7534
7535         atomic_set(&mddev->recovery_active, 0);
7536         last_check = 0;
7537
7538         if (j>2) {
7539                 printk(KERN_INFO
7540                        "md: resuming %s of %s from checkpoint.\n",
7541                        desc, mdname(mddev));
7542                 mddev->curr_resync = j;
7543         } else
7544                 mddev->curr_resync = 3; /* no longer delayed */
7545         mddev->curr_resync_completed = j;
7546         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
7547         md_new_event(mddev);
7548         update_time = jiffies;
7549
7550         blk_start_plug(&plug);
7551         while (j < max_sectors) {
7552                 sector_t sectors;
7553
7554                 skipped = 0;
7555
7556                 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7557                     ((mddev->curr_resync > mddev->curr_resync_completed &&
7558                       (mddev->curr_resync - mddev->curr_resync_completed)
7559                       > (max_sectors >> 4)) ||
7560                      time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
7561                      (j - mddev->curr_resync_completed)*2
7562                      >= mddev->resync_max - mddev->curr_resync_completed
7563                             )) {
7564                         /* time to update curr_resync_completed */
7565                         wait_event(mddev->recovery_wait,
7566                                    atomic_read(&mddev->recovery_active) == 0);
7567                         mddev->curr_resync_completed = j;
7568                         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
7569                             j > mddev->recovery_cp)
7570                                 mddev->recovery_cp = j;
7571                         update_time = jiffies;
7572                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7573                         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
7574                 }
7575
7576                 while (j >= mddev->resync_max &&
7577                        !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7578                         /* As this condition is controlled by user-space,
7579                          * we can block indefinitely, so use '_interruptible'
7580                          * to avoid triggering warnings.
7581                          */
7582                         flush_signals(current); /* just in case */
7583                         wait_event_interruptible(mddev->recovery_wait,
7584                                                  mddev->resync_max > j
7585                                                  || test_bit(MD_RECOVERY_INTR,
7586                                                              &mddev->recovery));
7587                 }
7588
7589                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7590                         break;
7591
7592                 sectors = mddev->pers->sync_request(mddev, j, &skipped,
7593                                                   currspeed < speed_min(mddev));
7594                 if (sectors == 0) {
7595                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7596                         break;
7597                 }
7598
7599                 if (!skipped) { /* actual IO requested */
7600                         io_sectors += sectors;
7601                         atomic_add(sectors, &mddev->recovery_active);
7602                 }
7603
7604                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7605                         break;
7606
7607                 j += sectors;
7608                 if (j > 2)
7609                         mddev->curr_resync = j;
7610                 mddev->curr_mark_cnt = io_sectors;
7611                 if (last_check == 0)
7612                         /* this is the earliest that rebuild will be
7613                          * visible in /proc/mdstat
7614                          */
7615                         md_new_event(mddev);
7616
7617                 if (last_check + window > io_sectors || j == max_sectors)
7618                         continue;
7619
7620                 last_check = io_sectors;
7621         repeat:
7622                 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
7623                         /* step marks */
7624                         int next = (last_mark+1) % SYNC_MARKS;
7625
7626                         mddev->resync_mark = mark[next];
7627                         mddev->resync_mark_cnt = mark_cnt[next];
7628                         mark[next] = jiffies;
7629                         mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
7630                         last_mark = next;
7631                 }
7632
7633                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7634                         break;
7635
7636                 /*
7637                  * this loop exits only if either when we are slower than
7638                  * the 'hard' speed limit, or the system was IO-idle for
7639                  * a jiffy.
7640                  * the system might be non-idle CPU-wise, but we only care
7641                  * about not overloading the IO subsystem. (things like an
7642                  * e2fsck being done on the RAID array should execute fast)
7643                  */
7644                 cond_resched();
7645
7646                 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
7647                         /((jiffies-mddev->resync_mark)/HZ +1) +1;
7648
7649                 if (currspeed > speed_min(mddev)) {
7650                         if ((currspeed > speed_max(mddev)) ||
7651                                         !is_mddev_idle(mddev, 0)) {
7652                                 msleep(500);
7653                                 goto repeat;
7654                         }
7655                 }
7656         }
7657         printk(KERN_INFO "md: %s: %s %s.\n",mdname(mddev), desc,
7658                test_bit(MD_RECOVERY_INTR, &mddev->recovery)
7659                ? "interrupted" : "done");
7660         /*
7661          * this also signals 'finished resyncing' to md_stop
7662          */
7663         blk_finish_plug(&plug);
7664         wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
7665
7666         /* tell personality that we are finished */
7667         mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
7668
7669         if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
7670             mddev->curr_resync > 2) {
7671                 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7672                         if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7673                                 if (mddev->curr_resync >= mddev->recovery_cp) {
7674                                         printk(KERN_INFO
7675                                                "md: checkpointing %s of %s.\n",
7676                                                desc, mdname(mddev));
7677                                         if (test_bit(MD_RECOVERY_ERROR,
7678                                                 &mddev->recovery))
7679                                                 mddev->recovery_cp =
7680                                                         mddev->curr_resync_completed;
7681                                         else
7682                                                 mddev->recovery_cp =
7683                                                         mddev->curr_resync;
7684                                 }
7685                         } else
7686                                 mddev->recovery_cp = MaxSector;
7687                 } else {
7688                         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7689                                 mddev->curr_resync = MaxSector;
7690                         rcu_read_lock();
7691                         rdev_for_each_rcu(rdev, mddev)
7692                                 if (rdev->raid_disk >= 0 &&
7693                                     mddev->delta_disks >= 0 &&
7694                                     !test_bit(Faulty, &rdev->flags) &&
7695                                     !test_bit(In_sync, &rdev->flags) &&
7696                                     rdev->recovery_offset < mddev->curr_resync)
7697                                         rdev->recovery_offset = mddev->curr_resync;
7698                         rcu_read_unlock();
7699                 }
7700         }
7701  skip:
7702         set_bit(MD_CHANGE_DEVS, &mddev->flags);
7703
7704         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7705                 /* We completed so min/max setting can be forgotten if used. */
7706                 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7707                         mddev->resync_min = 0;
7708                 mddev->resync_max = MaxSector;
7709         } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7710                 mddev->resync_min = mddev->curr_resync_completed;
7711         mddev->curr_resync = 0;
7712         wake_up(&resync_wait);
7713         set_bit(MD_RECOVERY_DONE, &mddev->recovery);
7714         md_wakeup_thread(mddev->thread);
7715         return;
7716 }
7717 EXPORT_SYMBOL_GPL(md_do_sync);
7718
7719 static int remove_and_add_spares(struct mddev *mddev,
7720                                  struct md_rdev *this)
7721 {
7722         struct md_rdev *rdev;
7723         int spares = 0;
7724         int removed = 0;
7725
7726         rdev_for_each(rdev, mddev)
7727                 if ((this == NULL || rdev == this) &&
7728                     rdev->raid_disk >= 0 &&
7729                     !test_bit(Blocked, &rdev->flags) &&
7730                     (test_bit(Faulty, &rdev->flags) ||
7731                      ! test_bit(In_sync, &rdev->flags)) &&
7732                     atomic_read(&rdev->nr_pending)==0) {
7733                         if (mddev->pers->hot_remove_disk(
7734                                     mddev, rdev) == 0) {
7735                                 sysfs_unlink_rdev(mddev, rdev);
7736                                 rdev->raid_disk = -1;
7737                                 removed++;
7738                         }
7739                 }
7740         if (removed && mddev->kobj.sd)
7741                 sysfs_notify(&mddev->kobj, NULL, "degraded");
7742
7743         if (this)
7744                 goto no_add;
7745
7746         rdev_for_each(rdev, mddev) {
7747                 if (rdev->raid_disk >= 0 &&
7748                     !test_bit(In_sync, &rdev->flags) &&
7749                     !test_bit(Faulty, &rdev->flags))
7750                         spares++;
7751                 if (rdev->raid_disk >= 0)
7752                         continue;
7753                 if (test_bit(Faulty, &rdev->flags))
7754                         continue;
7755                 if (mddev->ro &&
7756                     ! (rdev->saved_raid_disk >= 0 &&
7757                        !test_bit(Bitmap_sync, &rdev->flags)))
7758                         continue;
7759
7760                 if (rdev->saved_raid_disk < 0)
7761                         rdev->recovery_offset = 0;
7762                 if (mddev->pers->
7763                     hot_add_disk(mddev, rdev) == 0) {
7764                         if (sysfs_link_rdev(mddev, rdev))
7765                                 /* failure here is OK */;
7766                         spares++;
7767                         md_new_event(mddev);
7768                         set_bit(MD_CHANGE_DEVS, &mddev->flags);
7769                 }
7770         }
7771 no_add:
7772         if (removed)
7773                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7774         return spares;
7775 }
7776
7777 /*
7778  * This routine is regularly called by all per-raid-array threads to
7779  * deal with generic issues like resync and super-block update.
7780  * Raid personalities that don't have a thread (linear/raid0) do not
7781  * need this as they never do any recovery or update the superblock.
7782  *
7783  * It does not do any resync itself, but rather "forks" off other threads
7784  * to do that as needed.
7785  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
7786  * "->recovery" and create a thread at ->sync_thread.
7787  * When the thread finishes it sets MD_RECOVERY_DONE
7788  * and wakeups up this thread which will reap the thread and finish up.
7789  * This thread also removes any faulty devices (with nr_pending == 0).
7790  *
7791  * The overall approach is:
7792  *  1/ if the superblock needs updating, update it.
7793  *  2/ If a recovery thread is running, don't do anything else.
7794  *  3/ If recovery has finished, clean up, possibly marking spares active.
7795  *  4/ If there are any faulty devices, remove them.
7796  *  5/ If array is degraded, try to add spares devices
7797  *  6/ If array has spares or is not in-sync, start a resync thread.
7798  */
7799 void md_check_recovery(struct mddev *mddev)
7800 {
7801         if (mddev->suspended)
7802                 return;
7803
7804         if (mddev->bitmap)
7805                 bitmap_daemon_work(mddev);
7806
7807         if (signal_pending(current)) {
7808                 if (mddev->pers->sync_request && !mddev->external) {
7809                         printk(KERN_INFO "md: %s in immediate safe mode\n",
7810                                mdname(mddev));
7811                         mddev->safemode = 2;
7812                 }
7813                 flush_signals(current);
7814         }
7815
7816         if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
7817                 return;
7818         if ( ! (
7819                 (mddev->flags & MD_UPDATE_SB_FLAGS & ~ (1<<MD_CHANGE_PENDING)) ||
7820                 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7821                 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
7822                 (mddev->external == 0 && mddev->safemode == 1) ||
7823                 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
7824                  && !mddev->in_sync && mddev->recovery_cp == MaxSector)
7825                 ))
7826                 return;
7827
7828         if (mddev_trylock(mddev)) {
7829                 int spares = 0;
7830
7831                 if (mddev->ro) {
7832                         /* On a read-only array we can:
7833                          * - remove failed devices
7834                          * - add already-in_sync devices if the array itself
7835                          *   is in-sync.
7836                          * As we only add devices that are already in-sync,
7837                          * we can activate the spares immediately.
7838                          */
7839                         remove_and_add_spares(mddev, NULL);
7840                         /* There is no thread, but we need to call
7841                          * ->spare_active and clear saved_raid_disk
7842                          */
7843                         md_reap_sync_thread(mddev);
7844                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7845                         goto unlock;
7846                 }
7847
7848                 if (!mddev->external) {
7849                         int did_change = 0;
7850                         spin_lock_irq(&mddev->write_lock);
7851                         if (mddev->safemode &&
7852                             !atomic_read(&mddev->writes_pending) &&
7853                             !mddev->in_sync &&
7854                             mddev->recovery_cp == MaxSector) {
7855                                 mddev->in_sync = 1;
7856                                 did_change = 1;
7857                                 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7858                         }
7859                         if (mddev->safemode == 1)
7860                                 mddev->safemode = 0;
7861                         spin_unlock_irq(&mddev->write_lock);
7862                         if (did_change)
7863                                 sysfs_notify_dirent_safe(mddev->sysfs_state);
7864                 }
7865
7866                 if (mddev->flags & MD_UPDATE_SB_FLAGS)
7867                         md_update_sb(mddev, 0);
7868
7869                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
7870                     !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
7871                         /* resync/recovery still happening */
7872                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7873                         goto unlock;
7874                 }
7875                 if (mddev->sync_thread) {
7876                         md_reap_sync_thread(mddev);
7877                         goto unlock;
7878                 }
7879                 /* Set RUNNING before clearing NEEDED to avoid
7880                  * any transients in the value of "sync_action".
7881                  */
7882                 mddev->curr_resync_completed = 0;
7883                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7884                 /* Clear some bits that don't mean anything, but
7885                  * might be left set
7886                  */
7887                 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
7888                 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7889
7890                 if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7891                     test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
7892                         goto unlock;
7893                 /* no recovery is running.
7894                  * remove any failed drives, then
7895                  * add spares if possible.
7896                  * Spares are also removed and re-added, to allow
7897                  * the personality to fail the re-add.
7898                  */
7899
7900                 if (mddev->reshape_position != MaxSector) {
7901                         if (mddev->pers->check_reshape == NULL ||
7902                             mddev->pers->check_reshape(mddev) != 0)
7903                                 /* Cannot proceed */
7904                                 goto unlock;
7905                         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7906                         clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7907                 } else if ((spares = remove_and_add_spares(mddev, NULL))) {
7908                         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7909                         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7910                         clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7911                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7912                 } else if (mddev->recovery_cp < MaxSector) {
7913                         set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7914                         clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7915                 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
7916                         /* nothing to be done ... */
7917                         goto unlock;
7918
7919                 if (mddev->pers->sync_request) {
7920                         if (spares) {
7921                                 /* We are adding a device or devices to an array
7922                                  * which has the bitmap stored on all devices.
7923                                  * So make sure all bitmap pages get written
7924                                  */
7925                                 bitmap_write_all(mddev->bitmap);
7926                         }
7927                         mddev->sync_thread = md_register_thread(md_do_sync,
7928                                                                 mddev,
7929                                                                 "resync");
7930                         if (!mddev->sync_thread) {
7931                                 printk(KERN_ERR "%s: could not start resync"
7932                                         " thread...\n", 
7933                                         mdname(mddev));
7934                                 /* leave the spares where they are, it shouldn't hurt */
7935                                 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7936                                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7937                                 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7938                                 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7939                                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7940                         } else
7941                                 md_wakeup_thread(mddev->sync_thread);
7942                         sysfs_notify_dirent_safe(mddev->sysfs_action);
7943                         md_new_event(mddev);
7944                 }
7945         unlock:
7946                 wake_up(&mddev->sb_wait);
7947
7948                 if (!mddev->sync_thread) {
7949                         clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7950                         if (test_and_clear_bit(MD_RECOVERY_RECOVER,
7951                                                &mddev->recovery))
7952                                 if (mddev->sysfs_action)
7953                                         sysfs_notify_dirent_safe(mddev->sysfs_action);
7954                 }
7955                 mddev_unlock(mddev);
7956         }
7957 }
7958
7959 void md_reap_sync_thread(struct mddev *mddev)
7960 {
7961         struct md_rdev *rdev;
7962
7963         /* resync has finished, collect result */
7964         md_unregister_thread(&mddev->sync_thread);
7965         wake_up(&resync_wait);
7966         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
7967             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
7968                 /* success...*/
7969                 /* activate any spares */
7970                 if (mddev->pers->spare_active(mddev)) {
7971                         sysfs_notify(&mddev->kobj, NULL,
7972                                      "degraded");
7973                         set_bit(MD_CHANGE_DEVS, &mddev->flags);
7974                 }
7975         }
7976         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7977             mddev->pers->finish_reshape)
7978                 mddev->pers->finish_reshape(mddev);
7979
7980         /* If array is no-longer degraded, then any saved_raid_disk
7981          * information must be scrapped.
7982          */
7983         if (!mddev->degraded)
7984                 rdev_for_each(rdev, mddev)
7985                         rdev->saved_raid_disk = -1;
7986
7987         md_update_sb(mddev, 1);
7988         clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7989         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7990         clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7991         clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7992         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7993         /* flag recovery needed just to double check */
7994         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7995         sysfs_notify_dirent_safe(mddev->sysfs_action);
7996         md_new_event(mddev);
7997         if (mddev->event_work.func)
7998                 queue_work(md_misc_wq, &mddev->event_work);
7999 }
8000
8001 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
8002 {
8003         sysfs_notify_dirent_safe(rdev->sysfs_state);
8004         wait_event_timeout(rdev->blocked_wait,
8005                            !test_bit(Blocked, &rdev->flags) &&
8006                            !test_bit(BlockedBadBlocks, &rdev->flags),
8007                            msecs_to_jiffies(5000));
8008         rdev_dec_pending(rdev, mddev);
8009 }
8010 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
8011
8012 void md_finish_reshape(struct mddev *mddev)
8013 {
8014         /* called be personality module when reshape completes. */
8015         struct md_rdev *rdev;
8016
8017         rdev_for_each(rdev, mddev) {
8018                 if (rdev->data_offset > rdev->new_data_offset)
8019                         rdev->sectors += rdev->data_offset - rdev->new_data_offset;
8020                 else
8021                         rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
8022                 rdev->data_offset = rdev->new_data_offset;
8023         }
8024 }
8025 EXPORT_SYMBOL(md_finish_reshape);
8026
8027 /* Bad block management.
8028  * We can record which blocks on each device are 'bad' and so just
8029  * fail those blocks, or that stripe, rather than the whole device.
8030  * Entries in the bad-block table are 64bits wide.  This comprises:
8031  * Length of bad-range, in sectors: 0-511 for lengths 1-512
8032  * Start of bad-range, sector offset, 54 bits (allows 8 exbibytes)
8033  *  A 'shift' can be set so that larger blocks are tracked and
8034  *  consequently larger devices can be covered.
8035  * 'Acknowledged' flag - 1 bit. - the most significant bit.
8036  *
8037  * Locking of the bad-block table uses a seqlock so md_is_badblock
8038  * might need to retry if it is very unlucky.
8039  * We will sometimes want to check for bad blocks in a bi_end_io function,
8040  * so we use the write_seqlock_irq variant.
8041  *
8042  * When looking for a bad block we specify a range and want to
8043  * know if any block in the range is bad.  So we binary-search
8044  * to the last range that starts at-or-before the given endpoint,
8045  * (or "before the sector after the target range")
8046  * then see if it ends after the given start.
8047  * We return
8048  *  0 if there are no known bad blocks in the range
8049  *  1 if there are known bad block which are all acknowledged
8050  * -1 if there are bad blocks which have not yet been acknowledged in metadata.
8051  * plus the start/length of the first bad section we overlap.
8052  */
8053 int md_is_badblock(struct badblocks *bb, sector_t s, int sectors,
8054                    sector_t *first_bad, int *bad_sectors)
8055 {
8056         int hi;
8057         int lo;
8058         u64 *p = bb->page;
8059         int rv;
8060         sector_t target = s + sectors;
8061         unsigned seq;
8062
8063         if (bb->shift > 0) {
8064                 /* round the start down, and the end up */
8065                 s >>= bb->shift;
8066                 target += (1<<bb->shift) - 1;
8067                 target >>= bb->shift;
8068                 sectors = target - s;
8069         }
8070         /* 'target' is now the first block after the bad range */
8071
8072 retry:
8073         seq = read_seqbegin(&bb->lock);
8074         lo = 0;
8075         rv = 0;
8076         hi = bb->count;
8077
8078         /* Binary search between lo and hi for 'target'
8079          * i.e. for the last range that starts before 'target'
8080          */
8081         /* INVARIANT: ranges before 'lo' and at-or-after 'hi'
8082          * are known not to be the last range before target.
8083          * VARIANT: hi-lo is the number of possible
8084          * ranges, and decreases until it reaches 1
8085          */
8086         while (hi - lo > 1) {
8087                 int mid = (lo + hi) / 2;
8088                 sector_t a = BB_OFFSET(p[mid]);
8089                 if (a < target)
8090                         /* This could still be the one, earlier ranges
8091                          * could not. */
8092                         lo = mid;
8093                 else
8094                         /* This and later ranges are definitely out. */
8095                         hi = mid;
8096         }
8097         /* 'lo' might be the last that started before target, but 'hi' isn't */
8098         if (hi > lo) {
8099                 /* need to check all range that end after 's' to see if
8100                  * any are unacknowledged.
8101                  */
8102                 while (lo >= 0 &&
8103                        BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
8104                         if (BB_OFFSET(p[lo]) < target) {
8105                                 /* starts before the end, and finishes after
8106                                  * the start, so they must overlap
8107                                  */
8108                                 if (rv != -1 && BB_ACK(p[lo]))
8109                                         rv = 1;
8110                                 else
8111                                         rv = -1;
8112                                 *first_bad = BB_OFFSET(p[lo]);
8113                                 *bad_sectors = BB_LEN(p[lo]);
8114                         }
8115                         lo--;
8116                 }
8117         }
8118
8119         if (read_seqretry(&bb->lock, seq))
8120                 goto retry;
8121
8122         return rv;
8123 }
8124 EXPORT_SYMBOL_GPL(md_is_badblock);
8125
8126 /*
8127  * Add a range of bad blocks to the table.
8128  * This might extend the table, or might contract it
8129  * if two adjacent ranges can be merged.
8130  * We binary-search to find the 'insertion' point, then
8131  * decide how best to handle it.
8132  */
8133 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
8134                             int acknowledged)
8135 {
8136         u64 *p;
8137         int lo, hi;
8138         int rv = 1;
8139         unsigned long flags;
8140
8141         if (bb->shift < 0)
8142                 /* badblocks are disabled */
8143                 return 0;
8144
8145         if (bb->shift) {
8146                 /* round the start down, and the end up */
8147                 sector_t next = s + sectors;
8148                 s >>= bb->shift;
8149                 next += (1<<bb->shift) - 1;
8150                 next >>= bb->shift;
8151                 sectors = next - s;
8152         }
8153
8154         write_seqlock_irqsave(&bb->lock, flags);
8155
8156         p = bb->page;
8157         lo = 0;
8158         hi = bb->count;
8159         /* Find the last range that starts at-or-before 's' */
8160         while (hi - lo > 1) {
8161                 int mid = (lo + hi) / 2;
8162                 sector_t a = BB_OFFSET(p[mid]);
8163                 if (a <= s)
8164                         lo = mid;
8165                 else
8166                         hi = mid;
8167         }
8168         if (hi > lo && BB_OFFSET(p[lo]) > s)
8169                 hi = lo;
8170
8171         if (hi > lo) {
8172                 /* we found a range that might merge with the start
8173                  * of our new range
8174                  */
8175                 sector_t a = BB_OFFSET(p[lo]);
8176                 sector_t e = a + BB_LEN(p[lo]);
8177                 int ack = BB_ACK(p[lo]);
8178                 if (e >= s) {
8179                         /* Yes, we can merge with a previous range */
8180                         if (s == a && s + sectors >= e)
8181                                 /* new range covers old */
8182                                 ack = acknowledged;
8183                         else
8184                                 ack = ack && acknowledged;
8185
8186                         if (e < s + sectors)
8187                                 e = s + sectors;
8188                         if (e - a <= BB_MAX_LEN) {
8189                                 p[lo] = BB_MAKE(a, e-a, ack);
8190                                 s = e;
8191                         } else {
8192                                 /* does not all fit in one range,
8193                                  * make p[lo] maximal
8194                                  */
8195                                 if (BB_LEN(p[lo]) != BB_MAX_LEN)
8196                                         p[lo] = BB_MAKE(a, BB_MAX_LEN, ack);
8197                                 s = a + BB_MAX_LEN;
8198                         }
8199                         sectors = e - s;
8200                 }
8201         }
8202         if (sectors && hi < bb->count) {
8203                 /* 'hi' points to the first range that starts after 's'.
8204                  * Maybe we can merge with the start of that range */
8205                 sector_t a = BB_OFFSET(p[hi]);
8206                 sector_t e = a + BB_LEN(p[hi]);
8207                 int ack = BB_ACK(p[hi]);
8208                 if (a <= s + sectors) {
8209                         /* merging is possible */
8210                         if (e <= s + sectors) {
8211                                 /* full overlap */
8212                                 e = s + sectors;
8213                                 ack = acknowledged;
8214                         } else
8215                                 ack = ack && acknowledged;
8216
8217                         a = s;
8218                         if (e - a <= BB_MAX_LEN) {
8219                                 p[hi] = BB_MAKE(a, e-a, ack);
8220                                 s = e;
8221                         } else {
8222                                 p[hi] = BB_MAKE(a, BB_MAX_LEN, ack);
8223                                 s = a + BB_MAX_LEN;
8224                         }
8225                         sectors = e - s;
8226                         lo = hi;
8227                         hi++;
8228                 }
8229         }
8230         if (sectors == 0 && hi < bb->count) {
8231                 /* we might be able to combine lo and hi */
8232                 /* Note: 's' is at the end of 'lo' */
8233                 sector_t a = BB_OFFSET(p[hi]);
8234                 int lolen = BB_LEN(p[lo]);
8235                 int hilen = BB_LEN(p[hi]);
8236                 int newlen = lolen + hilen - (s - a);
8237                 if (s >= a && newlen < BB_MAX_LEN) {
8238                         /* yes, we can combine them */
8239                         int ack = BB_ACK(p[lo]) && BB_ACK(p[hi]);
8240                         p[lo] = BB_MAKE(BB_OFFSET(p[lo]), newlen, ack);
8241                         memmove(p + hi, p + hi + 1,
8242                                 (bb->count - hi - 1) * 8);
8243                         bb->count--;
8244                 }
8245         }
8246         while (sectors) {
8247                 /* didn't merge (it all).
8248                  * Need to add a range just before 'hi' */
8249                 if (bb->count >= MD_MAX_BADBLOCKS) {
8250                         /* No room for more */
8251                         rv = 0;
8252                         break;
8253                 } else {
8254                         int this_sectors = sectors;
8255                         memmove(p + hi + 1, p + hi,
8256                                 (bb->count - hi) * 8);
8257                         bb->count++;
8258
8259                         if (this_sectors > BB_MAX_LEN)
8260                                 this_sectors = BB_MAX_LEN;
8261                         p[hi] = BB_MAKE(s, this_sectors, acknowledged);
8262                         sectors -= this_sectors;
8263                         s += this_sectors;
8264                 }
8265         }
8266
8267         bb->changed = 1;
8268         if (!acknowledged)
8269                 bb->unacked_exist = 1;
8270         write_sequnlock_irqrestore(&bb->lock, flags);
8271
8272         return rv;
8273 }
8274
8275 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
8276                        int is_new)
8277 {
8278         int rv;
8279         if (is_new)
8280                 s += rdev->new_data_offset;
8281         else
8282                 s += rdev->data_offset;
8283         rv = md_set_badblocks(&rdev->badblocks,
8284                               s, sectors, 0);
8285         if (rv) {
8286                 /* Make sure they get written out promptly */
8287                 sysfs_notify_dirent_safe(rdev->sysfs_state);
8288                 set_bit(MD_CHANGE_CLEAN, &rdev->mddev->flags);
8289                 md_wakeup_thread(rdev->mddev->thread);
8290         }
8291         return rv;
8292 }
8293 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
8294
8295 /*
8296  * Remove a range of bad blocks from the table.
8297  * This may involve extending the table if we spilt a region,
8298  * but it must not fail.  So if the table becomes full, we just
8299  * drop the remove request.
8300  */
8301 static int md_clear_badblocks(struct badblocks *bb, sector_t s, int sectors)
8302 {
8303         u64 *p;
8304         int lo, hi;
8305         sector_t target = s + sectors;
8306         int rv = 0;
8307
8308         if (bb->shift > 0) {
8309                 /* When clearing we round the start up and the end down.
8310                  * This should not matter as the shift should align with
8311                  * the block size and no rounding should ever be needed.
8312                  * However it is better the think a block is bad when it
8313                  * isn't than to think a block is not bad when it is.
8314                  */
8315                 s += (1<<bb->shift) - 1;
8316                 s >>= bb->shift;
8317                 target >>= bb->shift;
8318                 sectors = target - s;
8319         }
8320
8321         write_seqlock_irq(&bb->lock);
8322
8323         p = bb->page;
8324         lo = 0;
8325         hi = bb->count;
8326         /* Find the last range that starts before 'target' */
8327         while (hi - lo > 1) {
8328                 int mid = (lo + hi) / 2;
8329                 sector_t a = BB_OFFSET(p[mid]);
8330                 if (a < target)
8331                         lo = mid;
8332                 else
8333                         hi = mid;
8334         }
8335         if (hi > lo) {
8336                 /* p[lo] is the last range that could overlap the
8337                  * current range.  Earlier ranges could also overlap,
8338                  * but only this one can overlap the end of the range.
8339                  */
8340                 if (BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > target) {
8341                         /* Partial overlap, leave the tail of this range */
8342                         int ack = BB_ACK(p[lo]);
8343                         sector_t a = BB_OFFSET(p[lo]);
8344                         sector_t end = a + BB_LEN(p[lo]);
8345
8346                         if (a < s) {
8347                                 /* we need to split this range */
8348                                 if (bb->count >= MD_MAX_BADBLOCKS) {
8349                                         rv = 0;
8350                                         goto out;
8351                                 }
8352                                 memmove(p+lo+1, p+lo, (bb->count - lo) * 8);
8353                                 bb->count++;
8354                                 p[lo] = BB_MAKE(a, s-a, ack);
8355                                 lo++;
8356                         }
8357                         p[lo] = BB_MAKE(target, end - target, ack);
8358                         /* there is no longer an overlap */
8359                         hi = lo;
8360                         lo--;
8361                 }
8362                 while (lo >= 0 &&
8363                        BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
8364                         /* This range does overlap */
8365                         if (BB_OFFSET(p[lo]) < s) {
8366                                 /* Keep the early parts of this range. */
8367                                 int ack = BB_ACK(p[lo]);
8368                                 sector_t start = BB_OFFSET(p[lo]);
8369                                 p[lo] = BB_MAKE(start, s - start, ack);
8370                                 /* now low doesn't overlap, so.. */
8371                                 break;
8372                         }
8373                         lo--;
8374                 }
8375                 /* 'lo' is strictly before, 'hi' is strictly after,
8376                  * anything between needs to be discarded
8377                  */
8378                 if (hi - lo > 1) {
8379                         memmove(p+lo+1, p+hi, (bb->count - hi) * 8);
8380                         bb->count -= (hi - lo - 1);
8381                 }
8382         }
8383
8384         bb->changed = 1;
8385 out:
8386         write_sequnlock_irq(&bb->lock);
8387         return rv;
8388 }
8389
8390 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
8391                          int is_new)
8392 {
8393         if (is_new)
8394                 s += rdev->new_data_offset;
8395         else
8396                 s += rdev->data_offset;
8397         return md_clear_badblocks(&rdev->badblocks,
8398                                   s, sectors);
8399 }
8400 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
8401
8402 /*
8403  * Acknowledge all bad blocks in a list.
8404  * This only succeeds if ->changed is clear.  It is used by
8405  * in-kernel metadata updates
8406  */
8407 void md_ack_all_badblocks(struct badblocks *bb)
8408 {
8409         if (bb->page == NULL || bb->changed)
8410                 /* no point even trying */
8411                 return;
8412         write_seqlock_irq(&bb->lock);
8413
8414         if (bb->changed == 0 && bb->unacked_exist) {
8415                 u64 *p = bb->page;
8416                 int i;
8417                 for (i = 0; i < bb->count ; i++) {
8418                         if (!BB_ACK(p[i])) {
8419                                 sector_t start = BB_OFFSET(p[i]);
8420                                 int len = BB_LEN(p[i]);
8421                                 p[i] = BB_MAKE(start, len, 1);
8422                         }
8423                 }
8424                 bb->unacked_exist = 0;
8425         }
8426         write_sequnlock_irq(&bb->lock);
8427 }
8428 EXPORT_SYMBOL_GPL(md_ack_all_badblocks);
8429
8430 /* sysfs access to bad-blocks list.
8431  * We present two files.
8432  * 'bad-blocks' lists sector numbers and lengths of ranges that
8433  *    are recorded as bad.  The list is truncated to fit within
8434  *    the one-page limit of sysfs.
8435  *    Writing "sector length" to this file adds an acknowledged
8436  *    bad block list.
8437  * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
8438  *    been acknowledged.  Writing to this file adds bad blocks
8439  *    without acknowledging them.  This is largely for testing.
8440  */
8441
8442 static ssize_t
8443 badblocks_show(struct badblocks *bb, char *page, int unack)
8444 {
8445         size_t len;
8446         int i;
8447         u64 *p = bb->page;
8448         unsigned seq;
8449
8450         if (bb->shift < 0)
8451                 return 0;
8452
8453 retry:
8454         seq = read_seqbegin(&bb->lock);
8455
8456         len = 0;
8457         i = 0;
8458
8459         while (len < PAGE_SIZE && i < bb->count) {
8460                 sector_t s = BB_OFFSET(p[i]);
8461                 unsigned int length = BB_LEN(p[i]);
8462                 int ack = BB_ACK(p[i]);
8463                 i++;
8464
8465                 if (unack && ack)
8466                         continue;
8467
8468                 len += snprintf(page+len, PAGE_SIZE-len, "%llu %u\n",
8469                                 (unsigned long long)s << bb->shift,
8470                                 length << bb->shift);
8471         }
8472         if (unack && len == 0)
8473                 bb->unacked_exist = 0;
8474
8475         if (read_seqretry(&bb->lock, seq))
8476                 goto retry;
8477
8478         return len;
8479 }
8480
8481 #define DO_DEBUG 1
8482
8483 static ssize_t
8484 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack)
8485 {
8486         unsigned long long sector;
8487         int length;
8488         char newline;
8489 #ifdef DO_DEBUG
8490         /* Allow clearing via sysfs *only* for testing/debugging.
8491          * Normally only a successful write may clear a badblock
8492          */
8493         int clear = 0;
8494         if (page[0] == '-') {
8495                 clear = 1;
8496                 page++;
8497         }
8498 #endif /* DO_DEBUG */
8499
8500         switch (sscanf(page, "%llu %d%c", &sector, &length, &newline)) {
8501         case 3:
8502                 if (newline != '\n')
8503                         return -EINVAL;
8504         case 2:
8505                 if (length <= 0)
8506                         return -EINVAL;
8507                 break;
8508         default:
8509                 return -EINVAL;
8510         }
8511
8512 #ifdef DO_DEBUG
8513         if (clear) {
8514                 md_clear_badblocks(bb, sector, length);
8515                 return len;
8516         }
8517 #endif /* DO_DEBUG */
8518         if (md_set_badblocks(bb, sector, length, !unack))
8519                 return len;
8520         else
8521                 return -ENOSPC;
8522 }
8523
8524 static int md_notify_reboot(struct notifier_block *this,
8525                             unsigned long code, void *x)
8526 {
8527         struct list_head *tmp;
8528         struct mddev *mddev;
8529         int need_delay = 0;
8530
8531         for_each_mddev(mddev, tmp) {
8532                 if (mddev_trylock(mddev)) {
8533                         if (mddev->pers)
8534                                 __md_stop_writes(mddev);
8535                         mddev->safemode = 2;
8536                         mddev_unlock(mddev);
8537                 }
8538                 need_delay = 1;
8539         }
8540         /*
8541          * certain more exotic SCSI devices are known to be
8542          * volatile wrt too early system reboots. While the
8543          * right place to handle this issue is the given
8544          * driver, we do want to have a safe RAID driver ...
8545          */
8546         if (need_delay)
8547                 mdelay(1000*1);
8548
8549         return NOTIFY_DONE;
8550 }
8551
8552 static struct notifier_block md_notifier = {
8553         .notifier_call  = md_notify_reboot,
8554         .next           = NULL,
8555         .priority       = INT_MAX, /* before any real devices */
8556 };
8557
8558 static void md_geninit(void)
8559 {
8560         pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
8561
8562         proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
8563 }
8564
8565 static int __init md_init(void)
8566 {
8567         int ret = -ENOMEM;
8568
8569         md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
8570         if (!md_wq)
8571                 goto err_wq;
8572
8573         md_misc_wq = alloc_workqueue("md_misc", 0, 0);
8574         if (!md_misc_wq)
8575                 goto err_misc_wq;
8576
8577         if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
8578                 goto err_md;
8579
8580         if ((ret = register_blkdev(0, "mdp")) < 0)
8581                 goto err_mdp;
8582         mdp_major = ret;
8583
8584         blk_register_region(MKDEV(MD_MAJOR, 0), 1UL<<MINORBITS, THIS_MODULE,
8585                             md_probe, NULL, NULL);
8586         blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
8587                             md_probe, NULL, NULL);
8588
8589         register_reboot_notifier(&md_notifier);
8590         raid_table_header = register_sysctl_table(raid_root_table);
8591
8592         md_geninit();
8593         return 0;
8594
8595 err_mdp:
8596         unregister_blkdev(MD_MAJOR, "md");
8597 err_md:
8598         destroy_workqueue(md_misc_wq);
8599 err_misc_wq:
8600         destroy_workqueue(md_wq);
8601 err_wq:
8602         return ret;
8603 }
8604
8605 #ifndef MODULE
8606
8607 /*
8608  * Searches all registered partitions for autorun RAID arrays
8609  * at boot time.
8610  */
8611
8612 static LIST_HEAD(all_detected_devices);
8613 struct detected_devices_node {
8614         struct list_head list;
8615         dev_t dev;
8616 };
8617
8618 void md_autodetect_dev(dev_t dev)
8619 {
8620         struct detected_devices_node *node_detected_dev;
8621
8622         node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
8623         if (node_detected_dev) {
8624                 node_detected_dev->dev = dev;
8625                 list_add_tail(&node_detected_dev->list, &all_detected_devices);
8626         } else {
8627                 printk(KERN_CRIT "md: md_autodetect_dev: kzalloc failed"
8628                         ", skipping dev(%d,%d)\n", MAJOR(dev), MINOR(dev));
8629         }
8630 }
8631
8632
8633 static void autostart_arrays(int part)
8634 {
8635         struct md_rdev *rdev;
8636         struct detected_devices_node *node_detected_dev;
8637         dev_t dev;
8638         int i_scanned, i_passed;
8639
8640         i_scanned = 0;
8641         i_passed = 0;
8642
8643         printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
8644
8645         while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
8646                 i_scanned++;
8647                 node_detected_dev = list_entry(all_detected_devices.next,
8648                                         struct detected_devices_node, list);
8649                 list_del(&node_detected_dev->list);
8650                 dev = node_detected_dev->dev;
8651                 kfree(node_detected_dev);
8652                 rdev = md_import_device(dev,0, 90);
8653                 if (IS_ERR(rdev))
8654                         continue;
8655
8656                 if (test_bit(Faulty, &rdev->flags)) {
8657                         MD_BUG();
8658                         continue;
8659                 }
8660                 set_bit(AutoDetected, &rdev->flags);
8661                 list_add(&rdev->same_set, &pending_raid_disks);
8662                 i_passed++;
8663         }
8664
8665         printk(KERN_INFO "md: Scanned %d and added %d devices.\n",
8666                                                 i_scanned, i_passed);
8667
8668         autorun_devices(part);
8669 }
8670
8671 #endif /* !MODULE */
8672
8673 static __exit void md_exit(void)
8674 {
8675         struct mddev *mddev;
8676         struct list_head *tmp;
8677
8678         blk_unregister_region(MKDEV(MD_MAJOR,0), 1U << MINORBITS);
8679         blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
8680
8681         unregister_blkdev(MD_MAJOR,"md");
8682         unregister_blkdev(mdp_major, "mdp");
8683         unregister_reboot_notifier(&md_notifier);
8684         unregister_sysctl_table(raid_table_header);
8685         remove_proc_entry("mdstat", NULL);
8686         for_each_mddev(mddev, tmp) {
8687                 export_array(mddev);
8688                 mddev->hold_active = 0;
8689         }
8690         destroy_workqueue(md_misc_wq);
8691         destroy_workqueue(md_wq);
8692 }
8693
8694 subsys_initcall(md_init);
8695 module_exit(md_exit)
8696
8697 static int get_ro(char *buffer, struct kernel_param *kp)
8698 {
8699         return sprintf(buffer, "%d", start_readonly);
8700 }
8701 static int set_ro(const char *val, struct kernel_param *kp)
8702 {
8703         char *e;
8704         int num = simple_strtoul(val, &e, 10);
8705         if (*val && (*e == '\0' || *e == '\n')) {
8706                 start_readonly = num;
8707                 return 0;
8708         }
8709         return -EINVAL;
8710 }
8711
8712 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
8713 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
8714
8715 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
8716
8717 EXPORT_SYMBOL(register_md_personality);
8718 EXPORT_SYMBOL(unregister_md_personality);
8719 EXPORT_SYMBOL(md_error);
8720 EXPORT_SYMBOL(md_done_sync);
8721 EXPORT_SYMBOL(md_write_start);
8722 EXPORT_SYMBOL(md_write_end);
8723 EXPORT_SYMBOL(md_register_thread);
8724 EXPORT_SYMBOL(md_unregister_thread);
8725 EXPORT_SYMBOL(md_wakeup_thread);
8726 EXPORT_SYMBOL(md_check_recovery);
8727 EXPORT_SYMBOL(md_reap_sync_thread);
8728 MODULE_LICENSE("GPL");
8729 MODULE_DESCRIPTION("MD RAID framework");
8730 MODULE_ALIAS("md");
8731 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);