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