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