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