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