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