xref: /openbmc/linux/drivers/md/md.c (revision 6e63153d)
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 	flush_workqueue(md_rdev_misc_wq);
5624 
5625 	mutex_lock(&disks_mutex);
5626 	mddev = mddev_alloc(dev);
5627 	if (IS_ERR(mddev)) {
5628 		error = PTR_ERR(mddev);
5629 		goto out_unlock;
5630 	}
5631 
5632 	partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
5633 	shift = partitioned ? MdpMinorShift : 0;
5634 	unit = MINOR(mddev->unit) >> shift;
5635 
5636 	if (name && !dev) {
5637 		/* Need to ensure that 'name' is not a duplicate.
5638 		 */
5639 		struct mddev *mddev2;
5640 		spin_lock(&all_mddevs_lock);
5641 
5642 		list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
5643 			if (mddev2->gendisk &&
5644 			    strcmp(mddev2->gendisk->disk_name, name) == 0) {
5645 				spin_unlock(&all_mddevs_lock);
5646 				error = -EEXIST;
5647 				goto out_free_mddev;
5648 			}
5649 		spin_unlock(&all_mddevs_lock);
5650 	}
5651 	if (name && dev)
5652 		/*
5653 		 * Creating /dev/mdNNN via "newarray", so adjust hold_active.
5654 		 */
5655 		mddev->hold_active = UNTIL_STOP;
5656 
5657 	error = -ENOMEM;
5658 	disk = blk_alloc_disk(NUMA_NO_NODE);
5659 	if (!disk)
5660 		goto out_free_mddev;
5661 
5662 	disk->major = MAJOR(mddev->unit);
5663 	disk->first_minor = unit << shift;
5664 	disk->minors = 1 << shift;
5665 	if (name)
5666 		strcpy(disk->disk_name, name);
5667 	else if (partitioned)
5668 		sprintf(disk->disk_name, "md_d%d", unit);
5669 	else
5670 		sprintf(disk->disk_name, "md%d", unit);
5671 	disk->fops = &md_fops;
5672 	disk->private_data = mddev;
5673 
5674 	mddev->queue = disk->queue;
5675 	blk_set_stacking_limits(&mddev->queue->limits);
5676 	blk_queue_write_cache(mddev->queue, true, true);
5677 	disk->events |= DISK_EVENT_MEDIA_CHANGE;
5678 	mddev->gendisk = disk;
5679 	error = add_disk(disk);
5680 	if (error)
5681 		goto out_put_disk;
5682 
5683 	kobject_init(&mddev->kobj, &md_ktype);
5684 	error = kobject_add(&mddev->kobj, &disk_to_dev(disk)->kobj, "%s", "md");
5685 	if (error) {
5686 		/*
5687 		 * The disk is already live at this point.  Clear the hold flag
5688 		 * and let mddev_put take care of the deletion, as it isn't any
5689 		 * different from a normal close on last release now.
5690 		 */
5691 		mddev->hold_active = 0;
5692 		mutex_unlock(&disks_mutex);
5693 		mddev_put(mddev);
5694 		return ERR_PTR(error);
5695 	}
5696 
5697 	kobject_uevent(&mddev->kobj, KOBJ_ADD);
5698 	mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
5699 	mddev->sysfs_level = sysfs_get_dirent_safe(mddev->kobj.sd, "level");
5700 	mutex_unlock(&disks_mutex);
5701 	return mddev;
5702 
5703 out_put_disk:
5704 	put_disk(disk);
5705 out_free_mddev:
5706 	mddev_free(mddev);
5707 out_unlock:
5708 	mutex_unlock(&disks_mutex);
5709 	return ERR_PTR(error);
5710 }
5711 
5712 static int md_alloc_and_put(dev_t dev, char *name)
5713 {
5714 	struct mddev *mddev = md_alloc(dev, name);
5715 
5716 	if (IS_ERR(mddev))
5717 		return PTR_ERR(mddev);
5718 	mddev_put(mddev);
5719 	return 0;
5720 }
5721 
5722 static void md_probe(dev_t dev)
5723 {
5724 	if (MAJOR(dev) == MD_MAJOR && MINOR(dev) >= 512)
5725 		return;
5726 	if (create_on_open)
5727 		md_alloc_and_put(dev, NULL);
5728 }
5729 
5730 static int add_named_array(const char *val, const struct kernel_param *kp)
5731 {
5732 	/*
5733 	 * val must be "md_*" or "mdNNN".
5734 	 * For "md_*" we allocate an array with a large free minor number, and
5735 	 * set the name to val.  val must not already be an active name.
5736 	 * For "mdNNN" we allocate an array with the minor number NNN
5737 	 * which must not already be in use.
5738 	 */
5739 	int len = strlen(val);
5740 	char buf[DISK_NAME_LEN];
5741 	unsigned long devnum;
5742 
5743 	while (len && val[len-1] == '\n')
5744 		len--;
5745 	if (len >= DISK_NAME_LEN)
5746 		return -E2BIG;
5747 	strscpy(buf, val, len+1);
5748 	if (strncmp(buf, "md_", 3) == 0)
5749 		return md_alloc_and_put(0, buf);
5750 	if (strncmp(buf, "md", 2) == 0 &&
5751 	    isdigit(buf[2]) &&
5752 	    kstrtoul(buf+2, 10, &devnum) == 0 &&
5753 	    devnum <= MINORMASK)
5754 		return md_alloc_and_put(MKDEV(MD_MAJOR, devnum), NULL);
5755 
5756 	return -EINVAL;
5757 }
5758 
5759 static void md_safemode_timeout(struct timer_list *t)
5760 {
5761 	struct mddev *mddev = from_timer(mddev, t, safemode_timer);
5762 
5763 	mddev->safemode = 1;
5764 	if (mddev->external)
5765 		sysfs_notify_dirent_safe(mddev->sysfs_state);
5766 
5767 	md_wakeup_thread(mddev->thread);
5768 }
5769 
5770 static int start_dirty_degraded;
5771 
5772 int md_run(struct mddev *mddev)
5773 {
5774 	int err;
5775 	struct md_rdev *rdev;
5776 	struct md_personality *pers;
5777 	bool nowait = true;
5778 
5779 	if (list_empty(&mddev->disks))
5780 		/* cannot run an array with no devices.. */
5781 		return -EINVAL;
5782 
5783 	if (mddev->pers)
5784 		return -EBUSY;
5785 	/* Cannot run until previous stop completes properly */
5786 	if (mddev->sysfs_active)
5787 		return -EBUSY;
5788 
5789 	/*
5790 	 * Analyze all RAID superblock(s)
5791 	 */
5792 	if (!mddev->raid_disks) {
5793 		if (!mddev->persistent)
5794 			return -EINVAL;
5795 		err = analyze_sbs(mddev);
5796 		if (err)
5797 			return -EINVAL;
5798 	}
5799 
5800 	if (mddev->level != LEVEL_NONE)
5801 		request_module("md-level-%d", mddev->level);
5802 	else if (mddev->clevel[0])
5803 		request_module("md-%s", mddev->clevel);
5804 
5805 	/*
5806 	 * Drop all container device buffers, from now on
5807 	 * the only valid external interface is through the md
5808 	 * device.
5809 	 */
5810 	mddev->has_superblocks = false;
5811 	rdev_for_each(rdev, mddev) {
5812 		if (test_bit(Faulty, &rdev->flags))
5813 			continue;
5814 		sync_blockdev(rdev->bdev);
5815 		invalidate_bdev(rdev->bdev);
5816 		if (mddev->ro != 1 && rdev_read_only(rdev)) {
5817 			mddev->ro = 1;
5818 			if (mddev->gendisk)
5819 				set_disk_ro(mddev->gendisk, 1);
5820 		}
5821 
5822 		if (rdev->sb_page)
5823 			mddev->has_superblocks = true;
5824 
5825 		/* perform some consistency tests on the device.
5826 		 * We don't want the data to overlap the metadata,
5827 		 * Internal Bitmap issues have been handled elsewhere.
5828 		 */
5829 		if (rdev->meta_bdev) {
5830 			/* Nothing to check */;
5831 		} else if (rdev->data_offset < rdev->sb_start) {
5832 			if (mddev->dev_sectors &&
5833 			    rdev->data_offset + mddev->dev_sectors
5834 			    > rdev->sb_start) {
5835 				pr_warn("md: %s: data overlaps metadata\n",
5836 					mdname(mddev));
5837 				return -EINVAL;
5838 			}
5839 		} else {
5840 			if (rdev->sb_start + rdev->sb_size/512
5841 			    > rdev->data_offset) {
5842 				pr_warn("md: %s: metadata overlaps data\n",
5843 					mdname(mddev));
5844 				return -EINVAL;
5845 			}
5846 		}
5847 		sysfs_notify_dirent_safe(rdev->sysfs_state);
5848 		nowait = nowait && bdev_nowait(rdev->bdev);
5849 	}
5850 
5851 	if (!bioset_initialized(&mddev->bio_set)) {
5852 		err = bioset_init(&mddev->bio_set, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5853 		if (err)
5854 			return err;
5855 	}
5856 	if (!bioset_initialized(&mddev->sync_set)) {
5857 		err = bioset_init(&mddev->sync_set, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5858 		if (err)
5859 			goto exit_bio_set;
5860 	}
5861 
5862 	spin_lock(&pers_lock);
5863 	pers = find_pers(mddev->level, mddev->clevel);
5864 	if (!pers || !try_module_get(pers->owner)) {
5865 		spin_unlock(&pers_lock);
5866 		if (mddev->level != LEVEL_NONE)
5867 			pr_warn("md: personality for level %d is not loaded!\n",
5868 				mddev->level);
5869 		else
5870 			pr_warn("md: personality for level %s is not loaded!\n",
5871 				mddev->clevel);
5872 		err = -EINVAL;
5873 		goto abort;
5874 	}
5875 	spin_unlock(&pers_lock);
5876 	if (mddev->level != pers->level) {
5877 		mddev->level = pers->level;
5878 		mddev->new_level = pers->level;
5879 	}
5880 	strscpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5881 
5882 	if (mddev->reshape_position != MaxSector &&
5883 	    pers->start_reshape == NULL) {
5884 		/* This personality cannot handle reshaping... */
5885 		module_put(pers->owner);
5886 		err = -EINVAL;
5887 		goto abort;
5888 	}
5889 
5890 	if (pers->sync_request) {
5891 		/* Warn if this is a potentially silly
5892 		 * configuration.
5893 		 */
5894 		struct md_rdev *rdev2;
5895 		int warned = 0;
5896 
5897 		rdev_for_each(rdev, mddev)
5898 			rdev_for_each(rdev2, mddev) {
5899 				if (rdev < rdev2 &&
5900 				    rdev->bdev->bd_disk ==
5901 				    rdev2->bdev->bd_disk) {
5902 					pr_warn("%s: WARNING: %pg appears to be on the same physical disk as %pg.\n",
5903 						mdname(mddev),
5904 						rdev->bdev,
5905 						rdev2->bdev);
5906 					warned = 1;
5907 				}
5908 			}
5909 
5910 		if (warned)
5911 			pr_warn("True protection against single-disk failure might be compromised.\n");
5912 	}
5913 
5914 	mddev->recovery = 0;
5915 	/* may be over-ridden by personality */
5916 	mddev->resync_max_sectors = mddev->dev_sectors;
5917 
5918 	mddev->ok_start_degraded = start_dirty_degraded;
5919 
5920 	if (start_readonly && mddev->ro == 0)
5921 		mddev->ro = 2; /* read-only, but switch on first write */
5922 
5923 	err = pers->run(mddev);
5924 	if (err)
5925 		pr_warn("md: pers->run() failed ...\n");
5926 	else if (pers->size(mddev, 0, 0) < mddev->array_sectors) {
5927 		WARN_ONCE(!mddev->external_size,
5928 			  "%s: default size too small, but 'external_size' not in effect?\n",
5929 			  __func__);
5930 		pr_warn("md: invalid array_size %llu > default size %llu\n",
5931 			(unsigned long long)mddev->array_sectors / 2,
5932 			(unsigned long long)pers->size(mddev, 0, 0) / 2);
5933 		err = -EINVAL;
5934 	}
5935 	if (err == 0 && pers->sync_request &&
5936 	    (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5937 		struct bitmap *bitmap;
5938 
5939 		bitmap = md_bitmap_create(mddev, -1);
5940 		if (IS_ERR(bitmap)) {
5941 			err = PTR_ERR(bitmap);
5942 			pr_warn("%s: failed to create bitmap (%d)\n",
5943 				mdname(mddev), err);
5944 		} else
5945 			mddev->bitmap = bitmap;
5946 
5947 	}
5948 	if (err)
5949 		goto bitmap_abort;
5950 
5951 	if (mddev->bitmap_info.max_write_behind > 0) {
5952 		bool create_pool = false;
5953 
5954 		rdev_for_each(rdev, mddev) {
5955 			if (test_bit(WriteMostly, &rdev->flags) &&
5956 			    rdev_init_serial(rdev))
5957 				create_pool = true;
5958 		}
5959 		if (create_pool && mddev->serial_info_pool == NULL) {
5960 			mddev->serial_info_pool =
5961 				mempool_create_kmalloc_pool(NR_SERIAL_INFOS,
5962 						    sizeof(struct serial_info));
5963 			if (!mddev->serial_info_pool) {
5964 				err = -ENOMEM;
5965 				goto bitmap_abort;
5966 			}
5967 		}
5968 	}
5969 
5970 	if (mddev->queue) {
5971 		bool nonrot = true;
5972 
5973 		rdev_for_each(rdev, mddev) {
5974 			if (rdev->raid_disk >= 0 && !bdev_nonrot(rdev->bdev)) {
5975 				nonrot = false;
5976 				break;
5977 			}
5978 		}
5979 		if (mddev->degraded)
5980 			nonrot = false;
5981 		if (nonrot)
5982 			blk_queue_flag_set(QUEUE_FLAG_NONROT, mddev->queue);
5983 		else
5984 			blk_queue_flag_clear(QUEUE_FLAG_NONROT, mddev->queue);
5985 		blk_queue_flag_set(QUEUE_FLAG_IO_STAT, mddev->queue);
5986 
5987 		/* Set the NOWAIT flags if all underlying devices support it */
5988 		if (nowait)
5989 			blk_queue_flag_set(QUEUE_FLAG_NOWAIT, mddev->queue);
5990 	}
5991 	if (pers->sync_request) {
5992 		if (mddev->kobj.sd &&
5993 		    sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5994 			pr_warn("md: cannot register extra attributes for %s\n",
5995 				mdname(mddev));
5996 		mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5997 		mddev->sysfs_completed = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_completed");
5998 		mddev->sysfs_degraded = sysfs_get_dirent_safe(mddev->kobj.sd, "degraded");
5999 	} else if (mddev->ro == 2) /* auto-readonly not meaningful */
6000 		mddev->ro = 0;
6001 
6002 	atomic_set(&mddev->max_corr_read_errors,
6003 		   MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
6004 	mddev->safemode = 0;
6005 	if (mddev_is_clustered(mddev))
6006 		mddev->safemode_delay = 0;
6007 	else
6008 		mddev->safemode_delay = DEFAULT_SAFEMODE_DELAY;
6009 	mddev->in_sync = 1;
6010 	smp_wmb();
6011 	spin_lock(&mddev->lock);
6012 	mddev->pers = pers;
6013 	spin_unlock(&mddev->lock);
6014 	rdev_for_each(rdev, mddev)
6015 		if (rdev->raid_disk >= 0)
6016 			sysfs_link_rdev(mddev, rdev); /* failure here is OK */
6017 
6018 	if (mddev->degraded && !mddev->ro)
6019 		/* This ensures that recovering status is reported immediately
6020 		 * via sysfs - until a lack of spares is confirmed.
6021 		 */
6022 		set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6023 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6024 
6025 	if (mddev->sb_flags)
6026 		md_update_sb(mddev, 0);
6027 
6028 	md_new_event();
6029 	return 0;
6030 
6031 bitmap_abort:
6032 	mddev_detach(mddev);
6033 	if (mddev->private)
6034 		pers->free(mddev, mddev->private);
6035 	mddev->private = NULL;
6036 	module_put(pers->owner);
6037 	md_bitmap_destroy(mddev);
6038 abort:
6039 	bioset_exit(&mddev->sync_set);
6040 exit_bio_set:
6041 	bioset_exit(&mddev->bio_set);
6042 	return err;
6043 }
6044 EXPORT_SYMBOL_GPL(md_run);
6045 
6046 int do_md_run(struct mddev *mddev)
6047 {
6048 	int err;
6049 
6050 	set_bit(MD_NOT_READY, &mddev->flags);
6051 	err = md_run(mddev);
6052 	if (err)
6053 		goto out;
6054 	err = md_bitmap_load(mddev);
6055 	if (err) {
6056 		md_bitmap_destroy(mddev);
6057 		goto out;
6058 	}
6059 
6060 	if (mddev_is_clustered(mddev))
6061 		md_allow_write(mddev);
6062 
6063 	/* run start up tasks that require md_thread */
6064 	md_start(mddev);
6065 
6066 	md_wakeup_thread(mddev->thread);
6067 	md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
6068 
6069 	set_capacity_and_notify(mddev->gendisk, mddev->array_sectors);
6070 	clear_bit(MD_NOT_READY, &mddev->flags);
6071 	mddev->changed = 1;
6072 	kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
6073 	sysfs_notify_dirent_safe(mddev->sysfs_state);
6074 	sysfs_notify_dirent_safe(mddev->sysfs_action);
6075 	sysfs_notify_dirent_safe(mddev->sysfs_degraded);
6076 out:
6077 	clear_bit(MD_NOT_READY, &mddev->flags);
6078 	return err;
6079 }
6080 
6081 int md_start(struct mddev *mddev)
6082 {
6083 	int ret = 0;
6084 
6085 	if (mddev->pers->start) {
6086 		set_bit(MD_RECOVERY_WAIT, &mddev->recovery);
6087 		md_wakeup_thread(mddev->thread);
6088 		ret = mddev->pers->start(mddev);
6089 		clear_bit(MD_RECOVERY_WAIT, &mddev->recovery);
6090 		md_wakeup_thread(mddev->sync_thread);
6091 	}
6092 	return ret;
6093 }
6094 EXPORT_SYMBOL_GPL(md_start);
6095 
6096 static int restart_array(struct mddev *mddev)
6097 {
6098 	struct gendisk *disk = mddev->gendisk;
6099 	struct md_rdev *rdev;
6100 	bool has_journal = false;
6101 	bool has_readonly = false;
6102 
6103 	/* Complain if it has no devices */
6104 	if (list_empty(&mddev->disks))
6105 		return -ENXIO;
6106 	if (!mddev->pers)
6107 		return -EINVAL;
6108 	if (!mddev->ro)
6109 		return -EBUSY;
6110 
6111 	rcu_read_lock();
6112 	rdev_for_each_rcu(rdev, mddev) {
6113 		if (test_bit(Journal, &rdev->flags) &&
6114 		    !test_bit(Faulty, &rdev->flags))
6115 			has_journal = true;
6116 		if (rdev_read_only(rdev))
6117 			has_readonly = true;
6118 	}
6119 	rcu_read_unlock();
6120 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !has_journal)
6121 		/* Don't restart rw with journal missing/faulty */
6122 			return -EINVAL;
6123 	if (has_readonly)
6124 		return -EROFS;
6125 
6126 	mddev->safemode = 0;
6127 	mddev->ro = 0;
6128 	set_disk_ro(disk, 0);
6129 	pr_debug("md: %s switched to read-write mode.\n", mdname(mddev));
6130 	/* Kick recovery or resync if necessary */
6131 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6132 	md_wakeup_thread(mddev->thread);
6133 	md_wakeup_thread(mddev->sync_thread);
6134 	sysfs_notify_dirent_safe(mddev->sysfs_state);
6135 	return 0;
6136 }
6137 
6138 static void md_clean(struct mddev *mddev)
6139 {
6140 	mddev->array_sectors = 0;
6141 	mddev->external_size = 0;
6142 	mddev->dev_sectors = 0;
6143 	mddev->raid_disks = 0;
6144 	mddev->recovery_cp = 0;
6145 	mddev->resync_min = 0;
6146 	mddev->resync_max = MaxSector;
6147 	mddev->reshape_position = MaxSector;
6148 	mddev->external = 0;
6149 	mddev->persistent = 0;
6150 	mddev->level = LEVEL_NONE;
6151 	mddev->clevel[0] = 0;
6152 	mddev->flags = 0;
6153 	mddev->sb_flags = 0;
6154 	mddev->ro = 0;
6155 	mddev->metadata_type[0] = 0;
6156 	mddev->chunk_sectors = 0;
6157 	mddev->ctime = mddev->utime = 0;
6158 	mddev->layout = 0;
6159 	mddev->max_disks = 0;
6160 	mddev->events = 0;
6161 	mddev->can_decrease_events = 0;
6162 	mddev->delta_disks = 0;
6163 	mddev->reshape_backwards = 0;
6164 	mddev->new_level = LEVEL_NONE;
6165 	mddev->new_layout = 0;
6166 	mddev->new_chunk_sectors = 0;
6167 	mddev->curr_resync = 0;
6168 	atomic64_set(&mddev->resync_mismatches, 0);
6169 	mddev->suspend_lo = mddev->suspend_hi = 0;
6170 	mddev->sync_speed_min = mddev->sync_speed_max = 0;
6171 	mddev->recovery = 0;
6172 	mddev->in_sync = 0;
6173 	mddev->changed = 0;
6174 	mddev->degraded = 0;
6175 	mddev->safemode = 0;
6176 	mddev->private = NULL;
6177 	mddev->cluster_info = NULL;
6178 	mddev->bitmap_info.offset = 0;
6179 	mddev->bitmap_info.default_offset = 0;
6180 	mddev->bitmap_info.default_space = 0;
6181 	mddev->bitmap_info.chunksize = 0;
6182 	mddev->bitmap_info.daemon_sleep = 0;
6183 	mddev->bitmap_info.max_write_behind = 0;
6184 	mddev->bitmap_info.nodes = 0;
6185 }
6186 
6187 static void __md_stop_writes(struct mddev *mddev)
6188 {
6189 	set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6190 	if (work_pending(&mddev->del_work))
6191 		flush_workqueue(md_misc_wq);
6192 	if (mddev->sync_thread) {
6193 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6194 		md_unregister_thread(&mddev->sync_thread);
6195 		md_reap_sync_thread(mddev);
6196 	}
6197 
6198 	del_timer_sync(&mddev->safemode_timer);
6199 
6200 	if (mddev->pers && mddev->pers->quiesce) {
6201 		mddev->pers->quiesce(mddev, 1);
6202 		mddev->pers->quiesce(mddev, 0);
6203 	}
6204 	md_bitmap_flush(mddev);
6205 
6206 	if (mddev->ro == 0 &&
6207 	    ((!mddev->in_sync && !mddev_is_clustered(mddev)) ||
6208 	     mddev->sb_flags)) {
6209 		/* mark array as shutdown cleanly */
6210 		if (!mddev_is_clustered(mddev))
6211 			mddev->in_sync = 1;
6212 		md_update_sb(mddev, 1);
6213 	}
6214 	/* disable policy to guarantee rdevs free resources for serialization */
6215 	mddev->serialize_policy = 0;
6216 	mddev_destroy_serial_pool(mddev, NULL, true);
6217 }
6218 
6219 void md_stop_writes(struct mddev *mddev)
6220 {
6221 	mddev_lock_nointr(mddev);
6222 	__md_stop_writes(mddev);
6223 	mddev_unlock(mddev);
6224 }
6225 EXPORT_SYMBOL_GPL(md_stop_writes);
6226 
6227 static void mddev_detach(struct mddev *mddev)
6228 {
6229 	md_bitmap_wait_behind_writes(mddev);
6230 	if (mddev->pers && mddev->pers->quiesce && !mddev->suspended) {
6231 		mddev->pers->quiesce(mddev, 1);
6232 		mddev->pers->quiesce(mddev, 0);
6233 	}
6234 	md_unregister_thread(&mddev->thread);
6235 	if (mddev->queue)
6236 		blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
6237 }
6238 
6239 static void __md_stop(struct mddev *mddev)
6240 {
6241 	struct md_personality *pers = mddev->pers;
6242 	md_bitmap_destroy(mddev);
6243 	mddev_detach(mddev);
6244 	/* Ensure ->event_work is done */
6245 	if (mddev->event_work.func)
6246 		flush_workqueue(md_misc_wq);
6247 	spin_lock(&mddev->lock);
6248 	mddev->pers = NULL;
6249 	spin_unlock(&mddev->lock);
6250 	if (mddev->private)
6251 		pers->free(mddev, mddev->private);
6252 	mddev->private = NULL;
6253 	if (pers->sync_request && mddev->to_remove == NULL)
6254 		mddev->to_remove = &md_redundancy_group;
6255 	module_put(pers->owner);
6256 	clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6257 }
6258 
6259 void md_stop(struct mddev *mddev)
6260 {
6261 	/* stop the array and free an attached data structures.
6262 	 * This is called from dm-raid
6263 	 */
6264 	__md_stop_writes(mddev);
6265 	__md_stop(mddev);
6266 	bioset_exit(&mddev->bio_set);
6267 	bioset_exit(&mddev->sync_set);
6268 }
6269 
6270 EXPORT_SYMBOL_GPL(md_stop);
6271 
6272 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
6273 {
6274 	int err = 0;
6275 	int did_freeze = 0;
6276 
6277 	if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
6278 		did_freeze = 1;
6279 		set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6280 		md_wakeup_thread(mddev->thread);
6281 	}
6282 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
6283 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6284 	if (mddev->sync_thread)
6285 		/* Thread might be blocked waiting for metadata update
6286 		 * which will now never happen */
6287 		wake_up_process(mddev->sync_thread->tsk);
6288 
6289 	if (mddev->external && test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
6290 		return -EBUSY;
6291 	mddev_unlock(mddev);
6292 	wait_event(resync_wait, !test_bit(MD_RECOVERY_RUNNING,
6293 					  &mddev->recovery));
6294 	wait_event(mddev->sb_wait,
6295 		   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
6296 	mddev_lock_nointr(mddev);
6297 
6298 	mutex_lock(&mddev->open_mutex);
6299 	if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
6300 	    mddev->sync_thread ||
6301 	    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
6302 		pr_warn("md: %s still in use.\n",mdname(mddev));
6303 		if (did_freeze) {
6304 			clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6305 			set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6306 			md_wakeup_thread(mddev->thread);
6307 		}
6308 		err = -EBUSY;
6309 		goto out;
6310 	}
6311 	if (mddev->pers) {
6312 		__md_stop_writes(mddev);
6313 
6314 		err  = -ENXIO;
6315 		if (mddev->ro==1)
6316 			goto out;
6317 		mddev->ro = 1;
6318 		set_disk_ro(mddev->gendisk, 1);
6319 		clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6320 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6321 		md_wakeup_thread(mddev->thread);
6322 		sysfs_notify_dirent_safe(mddev->sysfs_state);
6323 		err = 0;
6324 	}
6325 out:
6326 	mutex_unlock(&mddev->open_mutex);
6327 	return err;
6328 }
6329 
6330 /* mode:
6331  *   0 - completely stop and dis-assemble array
6332  *   2 - stop but do not disassemble array
6333  */
6334 static int do_md_stop(struct mddev *mddev, int mode,
6335 		      struct block_device *bdev)
6336 {
6337 	struct gendisk *disk = mddev->gendisk;
6338 	struct md_rdev *rdev;
6339 	int did_freeze = 0;
6340 
6341 	if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
6342 		did_freeze = 1;
6343 		set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6344 		md_wakeup_thread(mddev->thread);
6345 	}
6346 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
6347 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6348 	if (mddev->sync_thread)
6349 		/* Thread might be blocked waiting for metadata update
6350 		 * which will now never happen */
6351 		wake_up_process(mddev->sync_thread->tsk);
6352 
6353 	mddev_unlock(mddev);
6354 	wait_event(resync_wait, (mddev->sync_thread == NULL &&
6355 				 !test_bit(MD_RECOVERY_RUNNING,
6356 					   &mddev->recovery)));
6357 	mddev_lock_nointr(mddev);
6358 
6359 	mutex_lock(&mddev->open_mutex);
6360 	if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
6361 	    mddev->sysfs_active ||
6362 	    mddev->sync_thread ||
6363 	    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
6364 		pr_warn("md: %s still in use.\n",mdname(mddev));
6365 		mutex_unlock(&mddev->open_mutex);
6366 		if (did_freeze) {
6367 			clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6368 			set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6369 			md_wakeup_thread(mddev->thread);
6370 		}
6371 		return -EBUSY;
6372 	}
6373 	if (mddev->pers) {
6374 		if (mddev->ro)
6375 			set_disk_ro(disk, 0);
6376 
6377 		__md_stop_writes(mddev);
6378 		__md_stop(mddev);
6379 
6380 		/* tell userspace to handle 'inactive' */
6381 		sysfs_notify_dirent_safe(mddev->sysfs_state);
6382 
6383 		rdev_for_each(rdev, mddev)
6384 			if (rdev->raid_disk >= 0)
6385 				sysfs_unlink_rdev(mddev, rdev);
6386 
6387 		set_capacity_and_notify(disk, 0);
6388 		mutex_unlock(&mddev->open_mutex);
6389 		mddev->changed = 1;
6390 
6391 		if (mddev->ro)
6392 			mddev->ro = 0;
6393 	} else
6394 		mutex_unlock(&mddev->open_mutex);
6395 	/*
6396 	 * Free resources if final stop
6397 	 */
6398 	if (mode == 0) {
6399 		pr_info("md: %s stopped.\n", mdname(mddev));
6400 
6401 		if (mddev->bitmap_info.file) {
6402 			struct file *f = mddev->bitmap_info.file;
6403 			spin_lock(&mddev->lock);
6404 			mddev->bitmap_info.file = NULL;
6405 			spin_unlock(&mddev->lock);
6406 			fput(f);
6407 		}
6408 		mddev->bitmap_info.offset = 0;
6409 
6410 		export_array(mddev);
6411 
6412 		md_clean(mddev);
6413 		if (mddev->hold_active == UNTIL_STOP)
6414 			mddev->hold_active = 0;
6415 	}
6416 	md_new_event();
6417 	sysfs_notify_dirent_safe(mddev->sysfs_state);
6418 	return 0;
6419 }
6420 
6421 #ifndef MODULE
6422 static void autorun_array(struct mddev *mddev)
6423 {
6424 	struct md_rdev *rdev;
6425 	int err;
6426 
6427 	if (list_empty(&mddev->disks))
6428 		return;
6429 
6430 	pr_info("md: running: ");
6431 
6432 	rdev_for_each(rdev, mddev) {
6433 		pr_cont("<%pg>", rdev->bdev);
6434 	}
6435 	pr_cont("\n");
6436 
6437 	err = do_md_run(mddev);
6438 	if (err) {
6439 		pr_warn("md: do_md_run() returned %d\n", err);
6440 		do_md_stop(mddev, 0, NULL);
6441 	}
6442 }
6443 
6444 /*
6445  * lets try to run arrays based on all disks that have arrived
6446  * until now. (those are in pending_raid_disks)
6447  *
6448  * the method: pick the first pending disk, collect all disks with
6449  * the same UUID, remove all from the pending list and put them into
6450  * the 'same_array' list. Then order this list based on superblock
6451  * update time (freshest comes first), kick out 'old' disks and
6452  * compare superblocks. If everything's fine then run it.
6453  *
6454  * If "unit" is allocated, then bump its reference count
6455  */
6456 static void autorun_devices(int part)
6457 {
6458 	struct md_rdev *rdev0, *rdev, *tmp;
6459 	struct mddev *mddev;
6460 
6461 	pr_info("md: autorun ...\n");
6462 	while (!list_empty(&pending_raid_disks)) {
6463 		int unit;
6464 		dev_t dev;
6465 		LIST_HEAD(candidates);
6466 		rdev0 = list_entry(pending_raid_disks.next,
6467 					 struct md_rdev, same_set);
6468 
6469 		pr_debug("md: considering %pg ...\n", rdev0->bdev);
6470 		INIT_LIST_HEAD(&candidates);
6471 		rdev_for_each_list(rdev, tmp, &pending_raid_disks)
6472 			if (super_90_load(rdev, rdev0, 0) >= 0) {
6473 				pr_debug("md:  adding %pg ...\n",
6474 					 rdev->bdev);
6475 				list_move(&rdev->same_set, &candidates);
6476 			}
6477 		/*
6478 		 * now we have a set of devices, with all of them having
6479 		 * mostly sane superblocks. It's time to allocate the
6480 		 * mddev.
6481 		 */
6482 		if (part) {
6483 			dev = MKDEV(mdp_major,
6484 				    rdev0->preferred_minor << MdpMinorShift);
6485 			unit = MINOR(dev) >> MdpMinorShift;
6486 		} else {
6487 			dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
6488 			unit = MINOR(dev);
6489 		}
6490 		if (rdev0->preferred_minor != unit) {
6491 			pr_warn("md: unit number in %pg is bad: %d\n",
6492 				rdev0->bdev, rdev0->preferred_minor);
6493 			break;
6494 		}
6495 
6496 		mddev = md_alloc(dev, NULL);
6497 		if (IS_ERR(mddev))
6498 			break;
6499 
6500 		if (mddev_lock(mddev))
6501 			pr_warn("md: %s locked, cannot run\n", mdname(mddev));
6502 		else if (mddev->raid_disks || mddev->major_version
6503 			 || !list_empty(&mddev->disks)) {
6504 			pr_warn("md: %s already running, cannot run %pg\n",
6505 				mdname(mddev), rdev0->bdev);
6506 			mddev_unlock(mddev);
6507 		} else {
6508 			pr_debug("md: created %s\n", mdname(mddev));
6509 			mddev->persistent = 1;
6510 			rdev_for_each_list(rdev, tmp, &candidates) {
6511 				list_del_init(&rdev->same_set);
6512 				if (bind_rdev_to_array(rdev, mddev))
6513 					export_rdev(rdev);
6514 			}
6515 			autorun_array(mddev);
6516 			mddev_unlock(mddev);
6517 		}
6518 		/* on success, candidates will be empty, on error
6519 		 * it won't...
6520 		 */
6521 		rdev_for_each_list(rdev, tmp, &candidates) {
6522 			list_del_init(&rdev->same_set);
6523 			export_rdev(rdev);
6524 		}
6525 		mddev_put(mddev);
6526 	}
6527 	pr_info("md: ... autorun DONE.\n");
6528 }
6529 #endif /* !MODULE */
6530 
6531 static int get_version(void __user *arg)
6532 {
6533 	mdu_version_t ver;
6534 
6535 	ver.major = MD_MAJOR_VERSION;
6536 	ver.minor = MD_MINOR_VERSION;
6537 	ver.patchlevel = MD_PATCHLEVEL_VERSION;
6538 
6539 	if (copy_to_user(arg, &ver, sizeof(ver)))
6540 		return -EFAULT;
6541 
6542 	return 0;
6543 }
6544 
6545 static int get_array_info(struct mddev *mddev, void __user *arg)
6546 {
6547 	mdu_array_info_t info;
6548 	int nr,working,insync,failed,spare;
6549 	struct md_rdev *rdev;
6550 
6551 	nr = working = insync = failed = spare = 0;
6552 	rcu_read_lock();
6553 	rdev_for_each_rcu(rdev, mddev) {
6554 		nr++;
6555 		if (test_bit(Faulty, &rdev->flags))
6556 			failed++;
6557 		else {
6558 			working++;
6559 			if (test_bit(In_sync, &rdev->flags))
6560 				insync++;
6561 			else if (test_bit(Journal, &rdev->flags))
6562 				/* TODO: add journal count to md_u.h */
6563 				;
6564 			else
6565 				spare++;
6566 		}
6567 	}
6568 	rcu_read_unlock();
6569 
6570 	info.major_version = mddev->major_version;
6571 	info.minor_version = mddev->minor_version;
6572 	info.patch_version = MD_PATCHLEVEL_VERSION;
6573 	info.ctime         = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
6574 	info.level         = mddev->level;
6575 	info.size          = mddev->dev_sectors / 2;
6576 	if (info.size != mddev->dev_sectors / 2) /* overflow */
6577 		info.size = -1;
6578 	info.nr_disks      = nr;
6579 	info.raid_disks    = mddev->raid_disks;
6580 	info.md_minor      = mddev->md_minor;
6581 	info.not_persistent= !mddev->persistent;
6582 
6583 	info.utime         = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
6584 	info.state         = 0;
6585 	if (mddev->in_sync)
6586 		info.state = (1<<MD_SB_CLEAN);
6587 	if (mddev->bitmap && mddev->bitmap_info.offset)
6588 		info.state |= (1<<MD_SB_BITMAP_PRESENT);
6589 	if (mddev_is_clustered(mddev))
6590 		info.state |= (1<<MD_SB_CLUSTERED);
6591 	info.active_disks  = insync;
6592 	info.working_disks = working;
6593 	info.failed_disks  = failed;
6594 	info.spare_disks   = spare;
6595 
6596 	info.layout        = mddev->layout;
6597 	info.chunk_size    = mddev->chunk_sectors << 9;
6598 
6599 	if (copy_to_user(arg, &info, sizeof(info)))
6600 		return -EFAULT;
6601 
6602 	return 0;
6603 }
6604 
6605 static int get_bitmap_file(struct mddev *mddev, void __user * arg)
6606 {
6607 	mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
6608 	char *ptr;
6609 	int err;
6610 
6611 	file = kzalloc(sizeof(*file), GFP_NOIO);
6612 	if (!file)
6613 		return -ENOMEM;
6614 
6615 	err = 0;
6616 	spin_lock(&mddev->lock);
6617 	/* bitmap enabled */
6618 	if (mddev->bitmap_info.file) {
6619 		ptr = file_path(mddev->bitmap_info.file, file->pathname,
6620 				sizeof(file->pathname));
6621 		if (IS_ERR(ptr))
6622 			err = PTR_ERR(ptr);
6623 		else
6624 			memmove(file->pathname, ptr,
6625 				sizeof(file->pathname)-(ptr-file->pathname));
6626 	}
6627 	spin_unlock(&mddev->lock);
6628 
6629 	if (err == 0 &&
6630 	    copy_to_user(arg, file, sizeof(*file)))
6631 		err = -EFAULT;
6632 
6633 	kfree(file);
6634 	return err;
6635 }
6636 
6637 static int get_disk_info(struct mddev *mddev, void __user * arg)
6638 {
6639 	mdu_disk_info_t info;
6640 	struct md_rdev *rdev;
6641 
6642 	if (copy_from_user(&info, arg, sizeof(info)))
6643 		return -EFAULT;
6644 
6645 	rcu_read_lock();
6646 	rdev = md_find_rdev_nr_rcu(mddev, info.number);
6647 	if (rdev) {
6648 		info.major = MAJOR(rdev->bdev->bd_dev);
6649 		info.minor = MINOR(rdev->bdev->bd_dev);
6650 		info.raid_disk = rdev->raid_disk;
6651 		info.state = 0;
6652 		if (test_bit(Faulty, &rdev->flags))
6653 			info.state |= (1<<MD_DISK_FAULTY);
6654 		else if (test_bit(In_sync, &rdev->flags)) {
6655 			info.state |= (1<<MD_DISK_ACTIVE);
6656 			info.state |= (1<<MD_DISK_SYNC);
6657 		}
6658 		if (test_bit(Journal, &rdev->flags))
6659 			info.state |= (1<<MD_DISK_JOURNAL);
6660 		if (test_bit(WriteMostly, &rdev->flags))
6661 			info.state |= (1<<MD_DISK_WRITEMOSTLY);
6662 		if (test_bit(FailFast, &rdev->flags))
6663 			info.state |= (1<<MD_DISK_FAILFAST);
6664 	} else {
6665 		info.major = info.minor = 0;
6666 		info.raid_disk = -1;
6667 		info.state = (1<<MD_DISK_REMOVED);
6668 	}
6669 	rcu_read_unlock();
6670 
6671 	if (copy_to_user(arg, &info, sizeof(info)))
6672 		return -EFAULT;
6673 
6674 	return 0;
6675 }
6676 
6677 int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info)
6678 {
6679 	struct md_rdev *rdev;
6680 	dev_t dev = MKDEV(info->major,info->minor);
6681 
6682 	if (mddev_is_clustered(mddev) &&
6683 		!(info->state & ((1 << MD_DISK_CLUSTER_ADD) | (1 << MD_DISK_CANDIDATE)))) {
6684 		pr_warn("%s: Cannot add to clustered mddev.\n",
6685 			mdname(mddev));
6686 		return -EINVAL;
6687 	}
6688 
6689 	if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
6690 		return -EOVERFLOW;
6691 
6692 	if (!mddev->raid_disks) {
6693 		int err;
6694 		/* expecting a device which has a superblock */
6695 		rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
6696 		if (IS_ERR(rdev)) {
6697 			pr_warn("md: md_import_device returned %ld\n",
6698 				PTR_ERR(rdev));
6699 			return PTR_ERR(rdev);
6700 		}
6701 		if (!list_empty(&mddev->disks)) {
6702 			struct md_rdev *rdev0
6703 				= list_entry(mddev->disks.next,
6704 					     struct md_rdev, same_set);
6705 			err = super_types[mddev->major_version]
6706 				.load_super(rdev, rdev0, mddev->minor_version);
6707 			if (err < 0) {
6708 				pr_warn("md: %pg has different UUID to %pg\n",
6709 					rdev->bdev,
6710 					rdev0->bdev);
6711 				export_rdev(rdev);
6712 				return -EINVAL;
6713 			}
6714 		}
6715 		err = bind_rdev_to_array(rdev, mddev);
6716 		if (err)
6717 			export_rdev(rdev);
6718 		return err;
6719 	}
6720 
6721 	/*
6722 	 * md_add_new_disk can be used once the array is assembled
6723 	 * to add "hot spares".  They must already have a superblock
6724 	 * written
6725 	 */
6726 	if (mddev->pers) {
6727 		int err;
6728 		if (!mddev->pers->hot_add_disk) {
6729 			pr_warn("%s: personality does not support diskops!\n",
6730 				mdname(mddev));
6731 			return -EINVAL;
6732 		}
6733 		if (mddev->persistent)
6734 			rdev = md_import_device(dev, mddev->major_version,
6735 						mddev->minor_version);
6736 		else
6737 			rdev = md_import_device(dev, -1, -1);
6738 		if (IS_ERR(rdev)) {
6739 			pr_warn("md: md_import_device returned %ld\n",
6740 				PTR_ERR(rdev));
6741 			return PTR_ERR(rdev);
6742 		}
6743 		/* set saved_raid_disk if appropriate */
6744 		if (!mddev->persistent) {
6745 			if (info->state & (1<<MD_DISK_SYNC)  &&
6746 			    info->raid_disk < mddev->raid_disks) {
6747 				rdev->raid_disk = info->raid_disk;
6748 				set_bit(In_sync, &rdev->flags);
6749 				clear_bit(Bitmap_sync, &rdev->flags);
6750 			} else
6751 				rdev->raid_disk = -1;
6752 			rdev->saved_raid_disk = rdev->raid_disk;
6753 		} else
6754 			super_types[mddev->major_version].
6755 				validate_super(mddev, rdev);
6756 		if ((info->state & (1<<MD_DISK_SYNC)) &&
6757 		     rdev->raid_disk != info->raid_disk) {
6758 			/* This was a hot-add request, but events doesn't
6759 			 * match, so reject it.
6760 			 */
6761 			export_rdev(rdev);
6762 			return -EINVAL;
6763 		}
6764 
6765 		clear_bit(In_sync, &rdev->flags); /* just to be sure */
6766 		if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6767 			set_bit(WriteMostly, &rdev->flags);
6768 		else
6769 			clear_bit(WriteMostly, &rdev->flags);
6770 		if (info->state & (1<<MD_DISK_FAILFAST))
6771 			set_bit(FailFast, &rdev->flags);
6772 		else
6773 			clear_bit(FailFast, &rdev->flags);
6774 
6775 		if (info->state & (1<<MD_DISK_JOURNAL)) {
6776 			struct md_rdev *rdev2;
6777 			bool has_journal = false;
6778 
6779 			/* make sure no existing journal disk */
6780 			rdev_for_each(rdev2, mddev) {
6781 				if (test_bit(Journal, &rdev2->flags)) {
6782 					has_journal = true;
6783 					break;
6784 				}
6785 			}
6786 			if (has_journal || mddev->bitmap) {
6787 				export_rdev(rdev);
6788 				return -EBUSY;
6789 			}
6790 			set_bit(Journal, &rdev->flags);
6791 		}
6792 		/*
6793 		 * check whether the device shows up in other nodes
6794 		 */
6795 		if (mddev_is_clustered(mddev)) {
6796 			if (info->state & (1 << MD_DISK_CANDIDATE))
6797 				set_bit(Candidate, &rdev->flags);
6798 			else if (info->state & (1 << MD_DISK_CLUSTER_ADD)) {
6799 				/* --add initiated by this node */
6800 				err = md_cluster_ops->add_new_disk(mddev, rdev);
6801 				if (err) {
6802 					export_rdev(rdev);
6803 					return err;
6804 				}
6805 			}
6806 		}
6807 
6808 		rdev->raid_disk = -1;
6809 		err = bind_rdev_to_array(rdev, mddev);
6810 
6811 		if (err)
6812 			export_rdev(rdev);
6813 
6814 		if (mddev_is_clustered(mddev)) {
6815 			if (info->state & (1 << MD_DISK_CANDIDATE)) {
6816 				if (!err) {
6817 					err = md_cluster_ops->new_disk_ack(mddev,
6818 						err == 0);
6819 					if (err)
6820 						md_kick_rdev_from_array(rdev);
6821 				}
6822 			} else {
6823 				if (err)
6824 					md_cluster_ops->add_new_disk_cancel(mddev);
6825 				else
6826 					err = add_bound_rdev(rdev);
6827 			}
6828 
6829 		} else if (!err)
6830 			err = add_bound_rdev(rdev);
6831 
6832 		return err;
6833 	}
6834 
6835 	/* otherwise, md_add_new_disk is only allowed
6836 	 * for major_version==0 superblocks
6837 	 */
6838 	if (mddev->major_version != 0) {
6839 		pr_warn("%s: ADD_NEW_DISK not supported\n", mdname(mddev));
6840 		return -EINVAL;
6841 	}
6842 
6843 	if (!(info->state & (1<<MD_DISK_FAULTY))) {
6844 		int err;
6845 		rdev = md_import_device(dev, -1, 0);
6846 		if (IS_ERR(rdev)) {
6847 			pr_warn("md: error, md_import_device() returned %ld\n",
6848 				PTR_ERR(rdev));
6849 			return PTR_ERR(rdev);
6850 		}
6851 		rdev->desc_nr = info->number;
6852 		if (info->raid_disk < mddev->raid_disks)
6853 			rdev->raid_disk = info->raid_disk;
6854 		else
6855 			rdev->raid_disk = -1;
6856 
6857 		if (rdev->raid_disk < mddev->raid_disks)
6858 			if (info->state & (1<<MD_DISK_SYNC))
6859 				set_bit(In_sync, &rdev->flags);
6860 
6861 		if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6862 			set_bit(WriteMostly, &rdev->flags);
6863 		if (info->state & (1<<MD_DISK_FAILFAST))
6864 			set_bit(FailFast, &rdev->flags);
6865 
6866 		if (!mddev->persistent) {
6867 			pr_debug("md: nonpersistent superblock ...\n");
6868 			rdev->sb_start = bdev_nr_sectors(rdev->bdev);
6869 		} else
6870 			rdev->sb_start = calc_dev_sboffset(rdev);
6871 		rdev->sectors = rdev->sb_start;
6872 
6873 		err = bind_rdev_to_array(rdev, mddev);
6874 		if (err) {
6875 			export_rdev(rdev);
6876 			return err;
6877 		}
6878 	}
6879 
6880 	return 0;
6881 }
6882 
6883 static int hot_remove_disk(struct mddev *mddev, dev_t dev)
6884 {
6885 	struct md_rdev *rdev;
6886 
6887 	if (!mddev->pers)
6888 		return -ENODEV;
6889 
6890 	rdev = find_rdev(mddev, dev);
6891 	if (!rdev)
6892 		return -ENXIO;
6893 
6894 	if (rdev->raid_disk < 0)
6895 		goto kick_rdev;
6896 
6897 	clear_bit(Blocked, &rdev->flags);
6898 	remove_and_add_spares(mddev, rdev);
6899 
6900 	if (rdev->raid_disk >= 0)
6901 		goto busy;
6902 
6903 kick_rdev:
6904 	if (mddev_is_clustered(mddev)) {
6905 		if (md_cluster_ops->remove_disk(mddev, rdev))
6906 			goto busy;
6907 	}
6908 
6909 	md_kick_rdev_from_array(rdev);
6910 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6911 	if (mddev->thread)
6912 		md_wakeup_thread(mddev->thread);
6913 	else
6914 		md_update_sb(mddev, 1);
6915 	md_new_event();
6916 
6917 	return 0;
6918 busy:
6919 	pr_debug("md: cannot remove active disk %pg from %s ...\n",
6920 		 rdev->bdev, mdname(mddev));
6921 	return -EBUSY;
6922 }
6923 
6924 static int hot_add_disk(struct mddev *mddev, dev_t dev)
6925 {
6926 	int err;
6927 	struct md_rdev *rdev;
6928 
6929 	if (!mddev->pers)
6930 		return -ENODEV;
6931 
6932 	if (mddev->major_version != 0) {
6933 		pr_warn("%s: HOT_ADD may only be used with version-0 superblocks.\n",
6934 			mdname(mddev));
6935 		return -EINVAL;
6936 	}
6937 	if (!mddev->pers->hot_add_disk) {
6938 		pr_warn("%s: personality does not support diskops!\n",
6939 			mdname(mddev));
6940 		return -EINVAL;
6941 	}
6942 
6943 	rdev = md_import_device(dev, -1, 0);
6944 	if (IS_ERR(rdev)) {
6945 		pr_warn("md: error, md_import_device() returned %ld\n",
6946 			PTR_ERR(rdev));
6947 		return -EINVAL;
6948 	}
6949 
6950 	if (mddev->persistent)
6951 		rdev->sb_start = calc_dev_sboffset(rdev);
6952 	else
6953 		rdev->sb_start = bdev_nr_sectors(rdev->bdev);
6954 
6955 	rdev->sectors = rdev->sb_start;
6956 
6957 	if (test_bit(Faulty, &rdev->flags)) {
6958 		pr_warn("md: can not hot-add faulty %pg disk to %s!\n",
6959 			rdev->bdev, mdname(mddev));
6960 		err = -EINVAL;
6961 		goto abort_export;
6962 	}
6963 
6964 	clear_bit(In_sync, &rdev->flags);
6965 	rdev->desc_nr = -1;
6966 	rdev->saved_raid_disk = -1;
6967 	err = bind_rdev_to_array(rdev, mddev);
6968 	if (err)
6969 		goto abort_export;
6970 
6971 	/*
6972 	 * The rest should better be atomic, we can have disk failures
6973 	 * noticed in interrupt contexts ...
6974 	 */
6975 
6976 	rdev->raid_disk = -1;
6977 
6978 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6979 	if (!mddev->thread)
6980 		md_update_sb(mddev, 1);
6981 	/*
6982 	 * If the new disk does not support REQ_NOWAIT,
6983 	 * disable on the whole MD.
6984 	 */
6985 	if (!bdev_nowait(rdev->bdev)) {
6986 		pr_info("%s: Disabling nowait because %pg does not support nowait\n",
6987 			mdname(mddev), rdev->bdev);
6988 		blk_queue_flag_clear(QUEUE_FLAG_NOWAIT, mddev->queue);
6989 	}
6990 	/*
6991 	 * Kick recovery, maybe this spare has to be added to the
6992 	 * array immediately.
6993 	 */
6994 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6995 	md_wakeup_thread(mddev->thread);
6996 	md_new_event();
6997 	return 0;
6998 
6999 abort_export:
7000 	export_rdev(rdev);
7001 	return err;
7002 }
7003 
7004 static int set_bitmap_file(struct mddev *mddev, int fd)
7005 {
7006 	int err = 0;
7007 
7008 	if (mddev->pers) {
7009 		if (!mddev->pers->quiesce || !mddev->thread)
7010 			return -EBUSY;
7011 		if (mddev->recovery || mddev->sync_thread)
7012 			return -EBUSY;
7013 		/* we should be able to change the bitmap.. */
7014 	}
7015 
7016 	if (fd >= 0) {
7017 		struct inode *inode;
7018 		struct file *f;
7019 
7020 		if (mddev->bitmap || mddev->bitmap_info.file)
7021 			return -EEXIST; /* cannot add when bitmap is present */
7022 		f = fget(fd);
7023 
7024 		if (f == NULL) {
7025 			pr_warn("%s: error: failed to get bitmap file\n",
7026 				mdname(mddev));
7027 			return -EBADF;
7028 		}
7029 
7030 		inode = f->f_mapping->host;
7031 		if (!S_ISREG(inode->i_mode)) {
7032 			pr_warn("%s: error: bitmap file must be a regular file\n",
7033 				mdname(mddev));
7034 			err = -EBADF;
7035 		} else if (!(f->f_mode & FMODE_WRITE)) {
7036 			pr_warn("%s: error: bitmap file must open for write\n",
7037 				mdname(mddev));
7038 			err = -EBADF;
7039 		} else if (atomic_read(&inode->i_writecount) != 1) {
7040 			pr_warn("%s: error: bitmap file is already in use\n",
7041 				mdname(mddev));
7042 			err = -EBUSY;
7043 		}
7044 		if (err) {
7045 			fput(f);
7046 			return err;
7047 		}
7048 		mddev->bitmap_info.file = f;
7049 		mddev->bitmap_info.offset = 0; /* file overrides offset */
7050 	} else if (mddev->bitmap == NULL)
7051 		return -ENOENT; /* cannot remove what isn't there */
7052 	err = 0;
7053 	if (mddev->pers) {
7054 		if (fd >= 0) {
7055 			struct bitmap *bitmap;
7056 
7057 			bitmap = md_bitmap_create(mddev, -1);
7058 			mddev_suspend(mddev);
7059 			if (!IS_ERR(bitmap)) {
7060 				mddev->bitmap = bitmap;
7061 				err = md_bitmap_load(mddev);
7062 			} else
7063 				err = PTR_ERR(bitmap);
7064 			if (err) {
7065 				md_bitmap_destroy(mddev);
7066 				fd = -1;
7067 			}
7068 			mddev_resume(mddev);
7069 		} else if (fd < 0) {
7070 			mddev_suspend(mddev);
7071 			md_bitmap_destroy(mddev);
7072 			mddev_resume(mddev);
7073 		}
7074 	}
7075 	if (fd < 0) {
7076 		struct file *f = mddev->bitmap_info.file;
7077 		if (f) {
7078 			spin_lock(&mddev->lock);
7079 			mddev->bitmap_info.file = NULL;
7080 			spin_unlock(&mddev->lock);
7081 			fput(f);
7082 		}
7083 	}
7084 
7085 	return err;
7086 }
7087 
7088 /*
7089  * md_set_array_info is used two different ways
7090  * The original usage is when creating a new array.
7091  * In this usage, raid_disks is > 0 and it together with
7092  *  level, size, not_persistent,layout,chunksize determine the
7093  *  shape of the array.
7094  *  This will always create an array with a type-0.90.0 superblock.
7095  * The newer usage is when assembling an array.
7096  *  In this case raid_disks will be 0, and the major_version field is
7097  *  use to determine which style super-blocks are to be found on the devices.
7098  *  The minor and patch _version numbers are also kept incase the
7099  *  super_block handler wishes to interpret them.
7100  */
7101 int md_set_array_info(struct mddev *mddev, struct mdu_array_info_s *info)
7102 {
7103 	if (info->raid_disks == 0) {
7104 		/* just setting version number for superblock loading */
7105 		if (info->major_version < 0 ||
7106 		    info->major_version >= ARRAY_SIZE(super_types) ||
7107 		    super_types[info->major_version].name == NULL) {
7108 			/* maybe try to auto-load a module? */
7109 			pr_warn("md: superblock version %d not known\n",
7110 				info->major_version);
7111 			return -EINVAL;
7112 		}
7113 		mddev->major_version = info->major_version;
7114 		mddev->minor_version = info->minor_version;
7115 		mddev->patch_version = info->patch_version;
7116 		mddev->persistent = !info->not_persistent;
7117 		/* ensure mddev_put doesn't delete this now that there
7118 		 * is some minimal configuration.
7119 		 */
7120 		mddev->ctime         = ktime_get_real_seconds();
7121 		return 0;
7122 	}
7123 	mddev->major_version = MD_MAJOR_VERSION;
7124 	mddev->minor_version = MD_MINOR_VERSION;
7125 	mddev->patch_version = MD_PATCHLEVEL_VERSION;
7126 	mddev->ctime         = ktime_get_real_seconds();
7127 
7128 	mddev->level         = info->level;
7129 	mddev->clevel[0]     = 0;
7130 	mddev->dev_sectors   = 2 * (sector_t)info->size;
7131 	mddev->raid_disks    = info->raid_disks;
7132 	/* don't set md_minor, it is determined by which /dev/md* was
7133 	 * openned
7134 	 */
7135 	if (info->state & (1<<MD_SB_CLEAN))
7136 		mddev->recovery_cp = MaxSector;
7137 	else
7138 		mddev->recovery_cp = 0;
7139 	mddev->persistent    = ! info->not_persistent;
7140 	mddev->external	     = 0;
7141 
7142 	mddev->layout        = info->layout;
7143 	if (mddev->level == 0)
7144 		/* Cannot trust RAID0 layout info here */
7145 		mddev->layout = -1;
7146 	mddev->chunk_sectors = info->chunk_size >> 9;
7147 
7148 	if (mddev->persistent) {
7149 		mddev->max_disks = MD_SB_DISKS;
7150 		mddev->flags = 0;
7151 		mddev->sb_flags = 0;
7152 	}
7153 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
7154 
7155 	mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
7156 	mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
7157 	mddev->bitmap_info.offset = 0;
7158 
7159 	mddev->reshape_position = MaxSector;
7160 
7161 	/*
7162 	 * Generate a 128 bit UUID
7163 	 */
7164 	get_random_bytes(mddev->uuid, 16);
7165 
7166 	mddev->new_level = mddev->level;
7167 	mddev->new_chunk_sectors = mddev->chunk_sectors;
7168 	mddev->new_layout = mddev->layout;
7169 	mddev->delta_disks = 0;
7170 	mddev->reshape_backwards = 0;
7171 
7172 	return 0;
7173 }
7174 
7175 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
7176 {
7177 	lockdep_assert_held(&mddev->reconfig_mutex);
7178 
7179 	if (mddev->external_size)
7180 		return;
7181 
7182 	mddev->array_sectors = array_sectors;
7183 }
7184 EXPORT_SYMBOL(md_set_array_sectors);
7185 
7186 static int update_size(struct mddev *mddev, sector_t num_sectors)
7187 {
7188 	struct md_rdev *rdev;
7189 	int rv;
7190 	int fit = (num_sectors == 0);
7191 	sector_t old_dev_sectors = mddev->dev_sectors;
7192 
7193 	if (mddev->pers->resize == NULL)
7194 		return -EINVAL;
7195 	/* The "num_sectors" is the number of sectors of each device that
7196 	 * is used.  This can only make sense for arrays with redundancy.
7197 	 * linear and raid0 always use whatever space is available. We can only
7198 	 * consider changing this number if no resync or reconstruction is
7199 	 * happening, and if the new size is acceptable. It must fit before the
7200 	 * sb_start or, if that is <data_offset, it must fit before the size
7201 	 * of each device.  If num_sectors is zero, we find the largest size
7202 	 * that fits.
7203 	 */
7204 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
7205 	    mddev->sync_thread)
7206 		return -EBUSY;
7207 	if (mddev->ro)
7208 		return -EROFS;
7209 
7210 	rdev_for_each(rdev, mddev) {
7211 		sector_t avail = rdev->sectors;
7212 
7213 		if (fit && (num_sectors == 0 || num_sectors > avail))
7214 			num_sectors = avail;
7215 		if (avail < num_sectors)
7216 			return -ENOSPC;
7217 	}
7218 	rv = mddev->pers->resize(mddev, num_sectors);
7219 	if (!rv) {
7220 		if (mddev_is_clustered(mddev))
7221 			md_cluster_ops->update_size(mddev, old_dev_sectors);
7222 		else if (mddev->queue) {
7223 			set_capacity_and_notify(mddev->gendisk,
7224 						mddev->array_sectors);
7225 		}
7226 	}
7227 	return rv;
7228 }
7229 
7230 static int update_raid_disks(struct mddev *mddev, int raid_disks)
7231 {
7232 	int rv;
7233 	struct md_rdev *rdev;
7234 	/* change the number of raid disks */
7235 	if (mddev->pers->check_reshape == NULL)
7236 		return -EINVAL;
7237 	if (mddev->ro)
7238 		return -EROFS;
7239 	if (raid_disks <= 0 ||
7240 	    (mddev->max_disks && raid_disks >= mddev->max_disks))
7241 		return -EINVAL;
7242 	if (mddev->sync_thread ||
7243 	    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
7244 	    test_bit(MD_RESYNCING_REMOTE, &mddev->recovery) ||
7245 	    mddev->reshape_position != MaxSector)
7246 		return -EBUSY;
7247 
7248 	rdev_for_each(rdev, mddev) {
7249 		if (mddev->raid_disks < raid_disks &&
7250 		    rdev->data_offset < rdev->new_data_offset)
7251 			return -EINVAL;
7252 		if (mddev->raid_disks > raid_disks &&
7253 		    rdev->data_offset > rdev->new_data_offset)
7254 			return -EINVAL;
7255 	}
7256 
7257 	mddev->delta_disks = raid_disks - mddev->raid_disks;
7258 	if (mddev->delta_disks < 0)
7259 		mddev->reshape_backwards = 1;
7260 	else if (mddev->delta_disks > 0)
7261 		mddev->reshape_backwards = 0;
7262 
7263 	rv = mddev->pers->check_reshape(mddev);
7264 	if (rv < 0) {
7265 		mddev->delta_disks = 0;
7266 		mddev->reshape_backwards = 0;
7267 	}
7268 	return rv;
7269 }
7270 
7271 /*
7272  * update_array_info is used to change the configuration of an
7273  * on-line array.
7274  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
7275  * fields in the info are checked against the array.
7276  * Any differences that cannot be handled will cause an error.
7277  * Normally, only one change can be managed at a time.
7278  */
7279 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
7280 {
7281 	int rv = 0;
7282 	int cnt = 0;
7283 	int state = 0;
7284 
7285 	/* calculate expected state,ignoring low bits */
7286 	if (mddev->bitmap && mddev->bitmap_info.offset)
7287 		state |= (1 << MD_SB_BITMAP_PRESENT);
7288 
7289 	if (mddev->major_version != info->major_version ||
7290 	    mddev->minor_version != info->minor_version ||
7291 /*	    mddev->patch_version != info->patch_version || */
7292 	    mddev->ctime         != info->ctime         ||
7293 	    mddev->level         != info->level         ||
7294 /*	    mddev->layout        != info->layout        || */
7295 	    mddev->persistent	 != !info->not_persistent ||
7296 	    mddev->chunk_sectors != info->chunk_size >> 9 ||
7297 	    /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
7298 	    ((state^info->state) & 0xfffffe00)
7299 		)
7300 		return -EINVAL;
7301 	/* Check there is only one change */
7302 	if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
7303 		cnt++;
7304 	if (mddev->raid_disks != info->raid_disks)
7305 		cnt++;
7306 	if (mddev->layout != info->layout)
7307 		cnt++;
7308 	if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
7309 		cnt++;
7310 	if (cnt == 0)
7311 		return 0;
7312 	if (cnt > 1)
7313 		return -EINVAL;
7314 
7315 	if (mddev->layout != info->layout) {
7316 		/* Change layout
7317 		 * we don't need to do anything at the md level, the
7318 		 * personality will take care of it all.
7319 		 */
7320 		if (mddev->pers->check_reshape == NULL)
7321 			return -EINVAL;
7322 		else {
7323 			mddev->new_layout = info->layout;
7324 			rv = mddev->pers->check_reshape(mddev);
7325 			if (rv)
7326 				mddev->new_layout = mddev->layout;
7327 			return rv;
7328 		}
7329 	}
7330 	if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
7331 		rv = update_size(mddev, (sector_t)info->size * 2);
7332 
7333 	if (mddev->raid_disks    != info->raid_disks)
7334 		rv = update_raid_disks(mddev, info->raid_disks);
7335 
7336 	if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
7337 		if (mddev->pers->quiesce == NULL || mddev->thread == NULL) {
7338 			rv = -EINVAL;
7339 			goto err;
7340 		}
7341 		if (mddev->recovery || mddev->sync_thread) {
7342 			rv = -EBUSY;
7343 			goto err;
7344 		}
7345 		if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
7346 			struct bitmap *bitmap;
7347 			/* add the bitmap */
7348 			if (mddev->bitmap) {
7349 				rv = -EEXIST;
7350 				goto err;
7351 			}
7352 			if (mddev->bitmap_info.default_offset == 0) {
7353 				rv = -EINVAL;
7354 				goto err;
7355 			}
7356 			mddev->bitmap_info.offset =
7357 				mddev->bitmap_info.default_offset;
7358 			mddev->bitmap_info.space =
7359 				mddev->bitmap_info.default_space;
7360 			bitmap = md_bitmap_create(mddev, -1);
7361 			mddev_suspend(mddev);
7362 			if (!IS_ERR(bitmap)) {
7363 				mddev->bitmap = bitmap;
7364 				rv = md_bitmap_load(mddev);
7365 			} else
7366 				rv = PTR_ERR(bitmap);
7367 			if (rv)
7368 				md_bitmap_destroy(mddev);
7369 			mddev_resume(mddev);
7370 		} else {
7371 			/* remove the bitmap */
7372 			if (!mddev->bitmap) {
7373 				rv = -ENOENT;
7374 				goto err;
7375 			}
7376 			if (mddev->bitmap->storage.file) {
7377 				rv = -EINVAL;
7378 				goto err;
7379 			}
7380 			if (mddev->bitmap_info.nodes) {
7381 				/* hold PW on all the bitmap lock */
7382 				if (md_cluster_ops->lock_all_bitmaps(mddev) <= 0) {
7383 					pr_warn("md: can't change bitmap to none since the array is in use by more than one node\n");
7384 					rv = -EPERM;
7385 					md_cluster_ops->unlock_all_bitmaps(mddev);
7386 					goto err;
7387 				}
7388 
7389 				mddev->bitmap_info.nodes = 0;
7390 				md_cluster_ops->leave(mddev);
7391 				module_put(md_cluster_mod);
7392 				mddev->safemode_delay = DEFAULT_SAFEMODE_DELAY;
7393 			}
7394 			mddev_suspend(mddev);
7395 			md_bitmap_destroy(mddev);
7396 			mddev_resume(mddev);
7397 			mddev->bitmap_info.offset = 0;
7398 		}
7399 	}
7400 	md_update_sb(mddev, 1);
7401 	return rv;
7402 err:
7403 	return rv;
7404 }
7405 
7406 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
7407 {
7408 	struct md_rdev *rdev;
7409 	int err = 0;
7410 
7411 	if (mddev->pers == NULL)
7412 		return -ENODEV;
7413 
7414 	rcu_read_lock();
7415 	rdev = md_find_rdev_rcu(mddev, dev);
7416 	if (!rdev)
7417 		err =  -ENODEV;
7418 	else {
7419 		md_error(mddev, rdev);
7420 		if (test_bit(MD_BROKEN, &mddev->flags))
7421 			err = -EBUSY;
7422 	}
7423 	rcu_read_unlock();
7424 	return err;
7425 }
7426 
7427 /*
7428  * We have a problem here : there is no easy way to give a CHS
7429  * virtual geometry. We currently pretend that we have a 2 heads
7430  * 4 sectors (with a BIG number of cylinders...). This drives
7431  * dosfs just mad... ;-)
7432  */
7433 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
7434 {
7435 	struct mddev *mddev = bdev->bd_disk->private_data;
7436 
7437 	geo->heads = 2;
7438 	geo->sectors = 4;
7439 	geo->cylinders = mddev->array_sectors / 8;
7440 	return 0;
7441 }
7442 
7443 static inline bool md_ioctl_valid(unsigned int cmd)
7444 {
7445 	switch (cmd) {
7446 	case ADD_NEW_DISK:
7447 	case GET_ARRAY_INFO:
7448 	case GET_BITMAP_FILE:
7449 	case GET_DISK_INFO:
7450 	case HOT_ADD_DISK:
7451 	case HOT_REMOVE_DISK:
7452 	case RAID_VERSION:
7453 	case RESTART_ARRAY_RW:
7454 	case RUN_ARRAY:
7455 	case SET_ARRAY_INFO:
7456 	case SET_BITMAP_FILE:
7457 	case SET_DISK_FAULTY:
7458 	case STOP_ARRAY:
7459 	case STOP_ARRAY_RO:
7460 	case CLUSTERED_DISK_NACK:
7461 		return true;
7462 	default:
7463 		return false;
7464 	}
7465 }
7466 
7467 static int md_ioctl(struct block_device *bdev, fmode_t mode,
7468 			unsigned int cmd, unsigned long arg)
7469 {
7470 	int err = 0;
7471 	void __user *argp = (void __user *)arg;
7472 	struct mddev *mddev = NULL;
7473 	bool did_set_md_closing = false;
7474 
7475 	if (!md_ioctl_valid(cmd))
7476 		return -ENOTTY;
7477 
7478 	switch (cmd) {
7479 	case RAID_VERSION:
7480 	case GET_ARRAY_INFO:
7481 	case GET_DISK_INFO:
7482 		break;
7483 	default:
7484 		if (!capable(CAP_SYS_ADMIN))
7485 			return -EACCES;
7486 	}
7487 
7488 	/*
7489 	 * Commands dealing with the RAID driver but not any
7490 	 * particular array:
7491 	 */
7492 	switch (cmd) {
7493 	case RAID_VERSION:
7494 		err = get_version(argp);
7495 		goto out;
7496 	default:;
7497 	}
7498 
7499 	/*
7500 	 * Commands creating/starting a new array:
7501 	 */
7502 
7503 	mddev = bdev->bd_disk->private_data;
7504 
7505 	if (!mddev) {
7506 		BUG();
7507 		goto out;
7508 	}
7509 
7510 	/* Some actions do not requires the mutex */
7511 	switch (cmd) {
7512 	case GET_ARRAY_INFO:
7513 		if (!mddev->raid_disks && !mddev->external)
7514 			err = -ENODEV;
7515 		else
7516 			err = get_array_info(mddev, argp);
7517 		goto out;
7518 
7519 	case GET_DISK_INFO:
7520 		if (!mddev->raid_disks && !mddev->external)
7521 			err = -ENODEV;
7522 		else
7523 			err = get_disk_info(mddev, argp);
7524 		goto out;
7525 
7526 	case SET_DISK_FAULTY:
7527 		err = set_disk_faulty(mddev, new_decode_dev(arg));
7528 		goto out;
7529 
7530 	case GET_BITMAP_FILE:
7531 		err = get_bitmap_file(mddev, argp);
7532 		goto out;
7533 
7534 	}
7535 
7536 	if (cmd == ADD_NEW_DISK || cmd == HOT_ADD_DISK)
7537 		flush_rdev_wq(mddev);
7538 
7539 	if (cmd == HOT_REMOVE_DISK)
7540 		/* need to ensure recovery thread has run */
7541 		wait_event_interruptible_timeout(mddev->sb_wait,
7542 						 !test_bit(MD_RECOVERY_NEEDED,
7543 							   &mddev->recovery),
7544 						 msecs_to_jiffies(5000));
7545 	if (cmd == STOP_ARRAY || cmd == STOP_ARRAY_RO) {
7546 		/* Need to flush page cache, and ensure no-one else opens
7547 		 * and writes
7548 		 */
7549 		mutex_lock(&mddev->open_mutex);
7550 		if (mddev->pers && atomic_read(&mddev->openers) > 1) {
7551 			mutex_unlock(&mddev->open_mutex);
7552 			err = -EBUSY;
7553 			goto out;
7554 		}
7555 		if (test_and_set_bit(MD_CLOSING, &mddev->flags)) {
7556 			mutex_unlock(&mddev->open_mutex);
7557 			err = -EBUSY;
7558 			goto out;
7559 		}
7560 		did_set_md_closing = true;
7561 		mutex_unlock(&mddev->open_mutex);
7562 		sync_blockdev(bdev);
7563 	}
7564 	err = mddev_lock(mddev);
7565 	if (err) {
7566 		pr_debug("md: ioctl lock interrupted, reason %d, cmd %d\n",
7567 			 err, cmd);
7568 		goto out;
7569 	}
7570 
7571 	if (cmd == SET_ARRAY_INFO) {
7572 		mdu_array_info_t info;
7573 		if (!arg)
7574 			memset(&info, 0, sizeof(info));
7575 		else if (copy_from_user(&info, argp, sizeof(info))) {
7576 			err = -EFAULT;
7577 			goto unlock;
7578 		}
7579 		if (mddev->pers) {
7580 			err = update_array_info(mddev, &info);
7581 			if (err) {
7582 				pr_warn("md: couldn't update array info. %d\n", err);
7583 				goto unlock;
7584 			}
7585 			goto unlock;
7586 		}
7587 		if (!list_empty(&mddev->disks)) {
7588 			pr_warn("md: array %s already has disks!\n", mdname(mddev));
7589 			err = -EBUSY;
7590 			goto unlock;
7591 		}
7592 		if (mddev->raid_disks) {
7593 			pr_warn("md: array %s already initialised!\n", mdname(mddev));
7594 			err = -EBUSY;
7595 			goto unlock;
7596 		}
7597 		err = md_set_array_info(mddev, &info);
7598 		if (err) {
7599 			pr_warn("md: couldn't set array info. %d\n", err);
7600 			goto unlock;
7601 		}
7602 		goto unlock;
7603 	}
7604 
7605 	/*
7606 	 * Commands querying/configuring an existing array:
7607 	 */
7608 	/* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
7609 	 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
7610 	if ((!mddev->raid_disks && !mddev->external)
7611 	    && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
7612 	    && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
7613 	    && cmd != GET_BITMAP_FILE) {
7614 		err = -ENODEV;
7615 		goto unlock;
7616 	}
7617 
7618 	/*
7619 	 * Commands even a read-only array can execute:
7620 	 */
7621 	switch (cmd) {
7622 	case RESTART_ARRAY_RW:
7623 		err = restart_array(mddev);
7624 		goto unlock;
7625 
7626 	case STOP_ARRAY:
7627 		err = do_md_stop(mddev, 0, bdev);
7628 		goto unlock;
7629 
7630 	case STOP_ARRAY_RO:
7631 		err = md_set_readonly(mddev, bdev);
7632 		goto unlock;
7633 
7634 	case HOT_REMOVE_DISK:
7635 		err = hot_remove_disk(mddev, new_decode_dev(arg));
7636 		goto unlock;
7637 
7638 	case ADD_NEW_DISK:
7639 		/* We can support ADD_NEW_DISK on read-only arrays
7640 		 * only if we are re-adding a preexisting device.
7641 		 * So require mddev->pers and MD_DISK_SYNC.
7642 		 */
7643 		if (mddev->pers) {
7644 			mdu_disk_info_t info;
7645 			if (copy_from_user(&info, argp, sizeof(info)))
7646 				err = -EFAULT;
7647 			else if (!(info.state & (1<<MD_DISK_SYNC)))
7648 				/* Need to clear read-only for this */
7649 				break;
7650 			else
7651 				err = md_add_new_disk(mddev, &info);
7652 			goto unlock;
7653 		}
7654 		break;
7655 	}
7656 
7657 	/*
7658 	 * The remaining ioctls are changing the state of the
7659 	 * superblock, so we do not allow them on read-only arrays.
7660 	 */
7661 	if (mddev->ro && mddev->pers) {
7662 		if (mddev->ro == 2) {
7663 			mddev->ro = 0;
7664 			sysfs_notify_dirent_safe(mddev->sysfs_state);
7665 			set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7666 			/* mddev_unlock will wake thread */
7667 			/* If a device failed while we were read-only, we
7668 			 * need to make sure the metadata is updated now.
7669 			 */
7670 			if (test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)) {
7671 				mddev_unlock(mddev);
7672 				wait_event(mddev->sb_wait,
7673 					   !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags) &&
7674 					   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
7675 				mddev_lock_nointr(mddev);
7676 			}
7677 		} else {
7678 			err = -EROFS;
7679 			goto unlock;
7680 		}
7681 	}
7682 
7683 	switch (cmd) {
7684 	case ADD_NEW_DISK:
7685 	{
7686 		mdu_disk_info_t info;
7687 		if (copy_from_user(&info, argp, sizeof(info)))
7688 			err = -EFAULT;
7689 		else
7690 			err = md_add_new_disk(mddev, &info);
7691 		goto unlock;
7692 	}
7693 
7694 	case CLUSTERED_DISK_NACK:
7695 		if (mddev_is_clustered(mddev))
7696 			md_cluster_ops->new_disk_ack(mddev, false);
7697 		else
7698 			err = -EINVAL;
7699 		goto unlock;
7700 
7701 	case HOT_ADD_DISK:
7702 		err = hot_add_disk(mddev, new_decode_dev(arg));
7703 		goto unlock;
7704 
7705 	case RUN_ARRAY:
7706 		err = do_md_run(mddev);
7707 		goto unlock;
7708 
7709 	case SET_BITMAP_FILE:
7710 		err = set_bitmap_file(mddev, (int)arg);
7711 		goto unlock;
7712 
7713 	default:
7714 		err = -EINVAL;
7715 		goto unlock;
7716 	}
7717 
7718 unlock:
7719 	if (mddev->hold_active == UNTIL_IOCTL &&
7720 	    err != -EINVAL)
7721 		mddev->hold_active = 0;
7722 	mddev_unlock(mddev);
7723 out:
7724 	if(did_set_md_closing)
7725 		clear_bit(MD_CLOSING, &mddev->flags);
7726 	return err;
7727 }
7728 #ifdef CONFIG_COMPAT
7729 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
7730 		    unsigned int cmd, unsigned long arg)
7731 {
7732 	switch (cmd) {
7733 	case HOT_REMOVE_DISK:
7734 	case HOT_ADD_DISK:
7735 	case SET_DISK_FAULTY:
7736 	case SET_BITMAP_FILE:
7737 		/* These take in integer arg, do not convert */
7738 		break;
7739 	default:
7740 		arg = (unsigned long)compat_ptr(arg);
7741 		break;
7742 	}
7743 
7744 	return md_ioctl(bdev, mode, cmd, arg);
7745 }
7746 #endif /* CONFIG_COMPAT */
7747 
7748 static int md_set_read_only(struct block_device *bdev, bool ro)
7749 {
7750 	struct mddev *mddev = bdev->bd_disk->private_data;
7751 	int err;
7752 
7753 	err = mddev_lock(mddev);
7754 	if (err)
7755 		return err;
7756 
7757 	if (!mddev->raid_disks && !mddev->external) {
7758 		err = -ENODEV;
7759 		goto out_unlock;
7760 	}
7761 
7762 	/*
7763 	 * Transitioning to read-auto need only happen for arrays that call
7764 	 * md_write_start and which are not ready for writes yet.
7765 	 */
7766 	if (!ro && mddev->ro == 1 && mddev->pers) {
7767 		err = restart_array(mddev);
7768 		if (err)
7769 			goto out_unlock;
7770 		mddev->ro = 2;
7771 	}
7772 
7773 out_unlock:
7774 	mddev_unlock(mddev);
7775 	return err;
7776 }
7777 
7778 static int md_open(struct block_device *bdev, fmode_t mode)
7779 {
7780 	struct mddev *mddev;
7781 	int err;
7782 
7783 	spin_lock(&all_mddevs_lock);
7784 	mddev = mddev_get(bdev->bd_disk->private_data);
7785 	spin_unlock(&all_mddevs_lock);
7786 	if (!mddev)
7787 		return -ENODEV;
7788 
7789 	err = mutex_lock_interruptible(&mddev->open_mutex);
7790 	if (err)
7791 		goto out;
7792 
7793 	err = -ENODEV;
7794 	if (test_bit(MD_CLOSING, &mddev->flags))
7795 		goto out_unlock;
7796 
7797 	atomic_inc(&mddev->openers);
7798 	mutex_unlock(&mddev->open_mutex);
7799 
7800 	bdev_check_media_change(bdev);
7801 	return 0;
7802 
7803 out_unlock:
7804 	mutex_unlock(&mddev->open_mutex);
7805 out:
7806 	mddev_put(mddev);
7807 	return err;
7808 }
7809 
7810 static void md_release(struct gendisk *disk, fmode_t mode)
7811 {
7812 	struct mddev *mddev = disk->private_data;
7813 
7814 	BUG_ON(!mddev);
7815 	atomic_dec(&mddev->openers);
7816 	mddev_put(mddev);
7817 }
7818 
7819 static unsigned int md_check_events(struct gendisk *disk, unsigned int clearing)
7820 {
7821 	struct mddev *mddev = disk->private_data;
7822 	unsigned int ret = 0;
7823 
7824 	if (mddev->changed)
7825 		ret = DISK_EVENT_MEDIA_CHANGE;
7826 	mddev->changed = 0;
7827 	return ret;
7828 }
7829 
7830 static void md_free_disk(struct gendisk *disk)
7831 {
7832 	struct mddev *mddev = disk->private_data;
7833 
7834 	percpu_ref_exit(&mddev->writes_pending);
7835 	bioset_exit(&mddev->bio_set);
7836 	bioset_exit(&mddev->sync_set);
7837 
7838 	mddev_free(mddev);
7839 }
7840 
7841 const struct block_device_operations md_fops =
7842 {
7843 	.owner		= THIS_MODULE,
7844 	.submit_bio	= md_submit_bio,
7845 	.open		= md_open,
7846 	.release	= md_release,
7847 	.ioctl		= md_ioctl,
7848 #ifdef CONFIG_COMPAT
7849 	.compat_ioctl	= md_compat_ioctl,
7850 #endif
7851 	.getgeo		= md_getgeo,
7852 	.check_events	= md_check_events,
7853 	.set_read_only	= md_set_read_only,
7854 	.free_disk	= md_free_disk,
7855 };
7856 
7857 static int md_thread(void *arg)
7858 {
7859 	struct md_thread *thread = arg;
7860 
7861 	/*
7862 	 * md_thread is a 'system-thread', it's priority should be very
7863 	 * high. We avoid resource deadlocks individually in each
7864 	 * raid personality. (RAID5 does preallocation) We also use RR and
7865 	 * the very same RT priority as kswapd, thus we will never get
7866 	 * into a priority inversion deadlock.
7867 	 *
7868 	 * we definitely have to have equal or higher priority than
7869 	 * bdflush, otherwise bdflush will deadlock if there are too
7870 	 * many dirty RAID5 blocks.
7871 	 */
7872 
7873 	allow_signal(SIGKILL);
7874 	while (!kthread_should_stop()) {
7875 
7876 		/* We need to wait INTERRUPTIBLE so that
7877 		 * we don't add to the load-average.
7878 		 * That means we need to be sure no signals are
7879 		 * pending
7880 		 */
7881 		if (signal_pending(current))
7882 			flush_signals(current);
7883 
7884 		wait_event_interruptible_timeout
7885 			(thread->wqueue,
7886 			 test_bit(THREAD_WAKEUP, &thread->flags)
7887 			 || kthread_should_stop() || kthread_should_park(),
7888 			 thread->timeout);
7889 
7890 		clear_bit(THREAD_WAKEUP, &thread->flags);
7891 		if (kthread_should_park())
7892 			kthread_parkme();
7893 		if (!kthread_should_stop())
7894 			thread->run(thread);
7895 	}
7896 
7897 	return 0;
7898 }
7899 
7900 void md_wakeup_thread(struct md_thread *thread)
7901 {
7902 	if (thread) {
7903 		pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
7904 		set_bit(THREAD_WAKEUP, &thread->flags);
7905 		wake_up(&thread->wqueue);
7906 	}
7907 }
7908 EXPORT_SYMBOL(md_wakeup_thread);
7909 
7910 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
7911 		struct mddev *mddev, const char *name)
7912 {
7913 	struct md_thread *thread;
7914 
7915 	thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
7916 	if (!thread)
7917 		return NULL;
7918 
7919 	init_waitqueue_head(&thread->wqueue);
7920 
7921 	thread->run = run;
7922 	thread->mddev = mddev;
7923 	thread->timeout = MAX_SCHEDULE_TIMEOUT;
7924 	thread->tsk = kthread_run(md_thread, thread,
7925 				  "%s_%s",
7926 				  mdname(thread->mddev),
7927 				  name);
7928 	if (IS_ERR(thread->tsk)) {
7929 		kfree(thread);
7930 		return NULL;
7931 	}
7932 	return thread;
7933 }
7934 EXPORT_SYMBOL(md_register_thread);
7935 
7936 void md_unregister_thread(struct md_thread **threadp)
7937 {
7938 	struct md_thread *thread;
7939 
7940 	/*
7941 	 * Locking ensures that mddev_unlock does not wake_up a
7942 	 * non-existent thread
7943 	 */
7944 	spin_lock(&pers_lock);
7945 	thread = *threadp;
7946 	if (!thread) {
7947 		spin_unlock(&pers_lock);
7948 		return;
7949 	}
7950 	*threadp = NULL;
7951 	spin_unlock(&pers_lock);
7952 
7953 	pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
7954 	kthread_stop(thread->tsk);
7955 	kfree(thread);
7956 }
7957 EXPORT_SYMBOL(md_unregister_thread);
7958 
7959 void md_error(struct mddev *mddev, struct md_rdev *rdev)
7960 {
7961 	if (!rdev || test_bit(Faulty, &rdev->flags))
7962 		return;
7963 
7964 	if (!mddev->pers || !mddev->pers->error_handler)
7965 		return;
7966 	mddev->pers->error_handler(mddev, rdev);
7967 
7968 	if (mddev->degraded && !test_bit(MD_BROKEN, &mddev->flags))
7969 		set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7970 	sysfs_notify_dirent_safe(rdev->sysfs_state);
7971 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7972 	if (!test_bit(MD_BROKEN, &mddev->flags)) {
7973 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7974 		md_wakeup_thread(mddev->thread);
7975 	}
7976 	if (mddev->event_work.func)
7977 		queue_work(md_misc_wq, &mddev->event_work);
7978 	md_new_event();
7979 }
7980 EXPORT_SYMBOL(md_error);
7981 
7982 /* seq_file implementation /proc/mdstat */
7983 
7984 static void status_unused(struct seq_file *seq)
7985 {
7986 	int i = 0;
7987 	struct md_rdev *rdev;
7988 
7989 	seq_printf(seq, "unused devices: ");
7990 
7991 	list_for_each_entry(rdev, &pending_raid_disks, same_set) {
7992 		i++;
7993 		seq_printf(seq, "%pg ", rdev->bdev);
7994 	}
7995 	if (!i)
7996 		seq_printf(seq, "<none>");
7997 
7998 	seq_printf(seq, "\n");
7999 }
8000 
8001 static int status_resync(struct seq_file *seq, struct mddev *mddev)
8002 {
8003 	sector_t max_sectors, resync, res;
8004 	unsigned long dt, db = 0;
8005 	sector_t rt, curr_mark_cnt, resync_mark_cnt;
8006 	int scale, recovery_active;
8007 	unsigned int per_milli;
8008 
8009 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
8010 	    test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8011 		max_sectors = mddev->resync_max_sectors;
8012 	else
8013 		max_sectors = mddev->dev_sectors;
8014 
8015 	resync = mddev->curr_resync;
8016 	if (resync < MD_RESYNC_ACTIVE) {
8017 		if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
8018 			/* Still cleaning up */
8019 			resync = max_sectors;
8020 	} else if (resync > max_sectors) {
8021 		resync = max_sectors;
8022 	} else {
8023 		resync -= atomic_read(&mddev->recovery_active);
8024 		if (resync < MD_RESYNC_ACTIVE) {
8025 			/*
8026 			 * Resync has started, but the subtraction has
8027 			 * yielded one of the special values. Force it
8028 			 * to active to ensure the status reports an
8029 			 * active resync.
8030 			 */
8031 			resync = MD_RESYNC_ACTIVE;
8032 		}
8033 	}
8034 
8035 	if (resync == MD_RESYNC_NONE) {
8036 		if (test_bit(MD_RESYNCING_REMOTE, &mddev->recovery)) {
8037 			struct md_rdev *rdev;
8038 
8039 			rdev_for_each(rdev, mddev)
8040 				if (rdev->raid_disk >= 0 &&
8041 				    !test_bit(Faulty, &rdev->flags) &&
8042 				    rdev->recovery_offset != MaxSector &&
8043 				    rdev->recovery_offset) {
8044 					seq_printf(seq, "\trecover=REMOTE");
8045 					return 1;
8046 				}
8047 			if (mddev->reshape_position != MaxSector)
8048 				seq_printf(seq, "\treshape=REMOTE");
8049 			else
8050 				seq_printf(seq, "\tresync=REMOTE");
8051 			return 1;
8052 		}
8053 		if (mddev->recovery_cp < MaxSector) {
8054 			seq_printf(seq, "\tresync=PENDING");
8055 			return 1;
8056 		}
8057 		return 0;
8058 	}
8059 	if (resync < MD_RESYNC_ACTIVE) {
8060 		seq_printf(seq, "\tresync=DELAYED");
8061 		return 1;
8062 	}
8063 
8064 	WARN_ON(max_sectors == 0);
8065 	/* Pick 'scale' such that (resync>>scale)*1000 will fit
8066 	 * in a sector_t, and (max_sectors>>scale) will fit in a
8067 	 * u32, as those are the requirements for sector_div.
8068 	 * Thus 'scale' must be at least 10
8069 	 */
8070 	scale = 10;
8071 	if (sizeof(sector_t) > sizeof(unsigned long)) {
8072 		while ( max_sectors/2 > (1ULL<<(scale+32)))
8073 			scale++;
8074 	}
8075 	res = (resync>>scale)*1000;
8076 	sector_div(res, (u32)((max_sectors>>scale)+1));
8077 
8078 	per_milli = res;
8079 	{
8080 		int i, x = per_milli/50, y = 20-x;
8081 		seq_printf(seq, "[");
8082 		for (i = 0; i < x; i++)
8083 			seq_printf(seq, "=");
8084 		seq_printf(seq, ">");
8085 		for (i = 0; i < y; i++)
8086 			seq_printf(seq, ".");
8087 		seq_printf(seq, "] ");
8088 	}
8089 	seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
8090 		   (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
8091 		    "reshape" :
8092 		    (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
8093 		     "check" :
8094 		     (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
8095 		      "resync" : "recovery"))),
8096 		   per_milli/10, per_milli % 10,
8097 		   (unsigned long long) resync/2,
8098 		   (unsigned long long) max_sectors/2);
8099 
8100 	/*
8101 	 * dt: time from mark until now
8102 	 * db: blocks written from mark until now
8103 	 * rt: remaining time
8104 	 *
8105 	 * rt is a sector_t, which is always 64bit now. We are keeping
8106 	 * the original algorithm, but it is not really necessary.
8107 	 *
8108 	 * Original algorithm:
8109 	 *   So we divide before multiply in case it is 32bit and close
8110 	 *   to the limit.
8111 	 *   We scale the divisor (db) by 32 to avoid losing precision
8112 	 *   near the end of resync when the number of remaining sectors
8113 	 *   is close to 'db'.
8114 	 *   We then divide rt by 32 after multiplying by db to compensate.
8115 	 *   The '+1' avoids division by zero if db is very small.
8116 	 */
8117 	dt = ((jiffies - mddev->resync_mark) / HZ);
8118 	if (!dt) dt++;
8119 
8120 	curr_mark_cnt = mddev->curr_mark_cnt;
8121 	recovery_active = atomic_read(&mddev->recovery_active);
8122 	resync_mark_cnt = mddev->resync_mark_cnt;
8123 
8124 	if (curr_mark_cnt >= (recovery_active + resync_mark_cnt))
8125 		db = curr_mark_cnt - (recovery_active + resync_mark_cnt);
8126 
8127 	rt = max_sectors - resync;    /* number of remaining sectors */
8128 	rt = div64_u64(rt, db/32+1);
8129 	rt *= dt;
8130 	rt >>= 5;
8131 
8132 	seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
8133 		   ((unsigned long)rt % 60)/6);
8134 
8135 	seq_printf(seq, " speed=%ldK/sec", db/2/dt);
8136 	return 1;
8137 }
8138 
8139 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
8140 {
8141 	struct list_head *tmp;
8142 	loff_t l = *pos;
8143 	struct mddev *mddev;
8144 
8145 	if (l == 0x10000) {
8146 		++*pos;
8147 		return (void *)2;
8148 	}
8149 	if (l > 0x10000)
8150 		return NULL;
8151 	if (!l--)
8152 		/* header */
8153 		return (void*)1;
8154 
8155 	spin_lock(&all_mddevs_lock);
8156 	list_for_each(tmp,&all_mddevs)
8157 		if (!l--) {
8158 			mddev = list_entry(tmp, struct mddev, all_mddevs);
8159 			if (!mddev_get(mddev))
8160 				continue;
8161 			spin_unlock(&all_mddevs_lock);
8162 			return mddev;
8163 		}
8164 	spin_unlock(&all_mddevs_lock);
8165 	if (!l--)
8166 		return (void*)2;/* tail */
8167 	return NULL;
8168 }
8169 
8170 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
8171 {
8172 	struct list_head *tmp;
8173 	struct mddev *next_mddev, *mddev = v;
8174 	struct mddev *to_put = NULL;
8175 
8176 	++*pos;
8177 	if (v == (void*)2)
8178 		return NULL;
8179 
8180 	spin_lock(&all_mddevs_lock);
8181 	if (v == (void*)1) {
8182 		tmp = all_mddevs.next;
8183 	} else {
8184 		to_put = mddev;
8185 		tmp = mddev->all_mddevs.next;
8186 	}
8187 
8188 	for (;;) {
8189 		if (tmp == &all_mddevs) {
8190 			next_mddev = (void*)2;
8191 			*pos = 0x10000;
8192 			break;
8193 		}
8194 		next_mddev = list_entry(tmp, struct mddev, all_mddevs);
8195 		if (mddev_get(next_mddev))
8196 			break;
8197 		mddev = next_mddev;
8198 		tmp = mddev->all_mddevs.next;
8199 	}
8200 	spin_unlock(&all_mddevs_lock);
8201 
8202 	if (to_put)
8203 		mddev_put(mddev);
8204 	return next_mddev;
8205 
8206 }
8207 
8208 static void md_seq_stop(struct seq_file *seq, void *v)
8209 {
8210 	struct mddev *mddev = v;
8211 
8212 	if (mddev && v != (void*)1 && v != (void*)2)
8213 		mddev_put(mddev);
8214 }
8215 
8216 static int md_seq_show(struct seq_file *seq, void *v)
8217 {
8218 	struct mddev *mddev = v;
8219 	sector_t sectors;
8220 	struct md_rdev *rdev;
8221 
8222 	if (v == (void*)1) {
8223 		struct md_personality *pers;
8224 		seq_printf(seq, "Personalities : ");
8225 		spin_lock(&pers_lock);
8226 		list_for_each_entry(pers, &pers_list, list)
8227 			seq_printf(seq, "[%s] ", pers->name);
8228 
8229 		spin_unlock(&pers_lock);
8230 		seq_printf(seq, "\n");
8231 		seq->poll_event = atomic_read(&md_event_count);
8232 		return 0;
8233 	}
8234 	if (v == (void*)2) {
8235 		status_unused(seq);
8236 		return 0;
8237 	}
8238 
8239 	spin_lock(&mddev->lock);
8240 	if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
8241 		seq_printf(seq, "%s : %sactive", mdname(mddev),
8242 						mddev->pers ? "" : "in");
8243 		if (mddev->pers) {
8244 			if (mddev->ro==1)
8245 				seq_printf(seq, " (read-only)");
8246 			if (mddev->ro==2)
8247 				seq_printf(seq, " (auto-read-only)");
8248 			seq_printf(seq, " %s", mddev->pers->name);
8249 		}
8250 
8251 		sectors = 0;
8252 		rcu_read_lock();
8253 		rdev_for_each_rcu(rdev, mddev) {
8254 			seq_printf(seq, " %pg[%d]", rdev->bdev, rdev->desc_nr);
8255 
8256 			if (test_bit(WriteMostly, &rdev->flags))
8257 				seq_printf(seq, "(W)");
8258 			if (test_bit(Journal, &rdev->flags))
8259 				seq_printf(seq, "(J)");
8260 			if (test_bit(Faulty, &rdev->flags)) {
8261 				seq_printf(seq, "(F)");
8262 				continue;
8263 			}
8264 			if (rdev->raid_disk < 0)
8265 				seq_printf(seq, "(S)"); /* spare */
8266 			if (test_bit(Replacement, &rdev->flags))
8267 				seq_printf(seq, "(R)");
8268 			sectors += rdev->sectors;
8269 		}
8270 		rcu_read_unlock();
8271 
8272 		if (!list_empty(&mddev->disks)) {
8273 			if (mddev->pers)
8274 				seq_printf(seq, "\n      %llu blocks",
8275 					   (unsigned long long)
8276 					   mddev->array_sectors / 2);
8277 			else
8278 				seq_printf(seq, "\n      %llu blocks",
8279 					   (unsigned long long)sectors / 2);
8280 		}
8281 		if (mddev->persistent) {
8282 			if (mddev->major_version != 0 ||
8283 			    mddev->minor_version != 90) {
8284 				seq_printf(seq," super %d.%d",
8285 					   mddev->major_version,
8286 					   mddev->minor_version);
8287 			}
8288 		} else if (mddev->external)
8289 			seq_printf(seq, " super external:%s",
8290 				   mddev->metadata_type);
8291 		else
8292 			seq_printf(seq, " super non-persistent");
8293 
8294 		if (mddev->pers) {
8295 			mddev->pers->status(seq, mddev);
8296 			seq_printf(seq, "\n      ");
8297 			if (mddev->pers->sync_request) {
8298 				if (status_resync(seq, mddev))
8299 					seq_printf(seq, "\n      ");
8300 			}
8301 		} else
8302 			seq_printf(seq, "\n       ");
8303 
8304 		md_bitmap_status(seq, mddev->bitmap);
8305 
8306 		seq_printf(seq, "\n");
8307 	}
8308 	spin_unlock(&mddev->lock);
8309 
8310 	return 0;
8311 }
8312 
8313 static const struct seq_operations md_seq_ops = {
8314 	.start  = md_seq_start,
8315 	.next   = md_seq_next,
8316 	.stop   = md_seq_stop,
8317 	.show   = md_seq_show,
8318 };
8319 
8320 static int md_seq_open(struct inode *inode, struct file *file)
8321 {
8322 	struct seq_file *seq;
8323 	int error;
8324 
8325 	error = seq_open(file, &md_seq_ops);
8326 	if (error)
8327 		return error;
8328 
8329 	seq = file->private_data;
8330 	seq->poll_event = atomic_read(&md_event_count);
8331 	return error;
8332 }
8333 
8334 static int md_unloading;
8335 static __poll_t mdstat_poll(struct file *filp, poll_table *wait)
8336 {
8337 	struct seq_file *seq = filp->private_data;
8338 	__poll_t mask;
8339 
8340 	if (md_unloading)
8341 		return EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
8342 	poll_wait(filp, &md_event_waiters, wait);
8343 
8344 	/* always allow read */
8345 	mask = EPOLLIN | EPOLLRDNORM;
8346 
8347 	if (seq->poll_event != atomic_read(&md_event_count))
8348 		mask |= EPOLLERR | EPOLLPRI;
8349 	return mask;
8350 }
8351 
8352 static const struct proc_ops mdstat_proc_ops = {
8353 	.proc_open	= md_seq_open,
8354 	.proc_read	= seq_read,
8355 	.proc_lseek	= seq_lseek,
8356 	.proc_release	= seq_release,
8357 	.proc_poll	= mdstat_poll,
8358 };
8359 
8360 int register_md_personality(struct md_personality *p)
8361 {
8362 	pr_debug("md: %s personality registered for level %d\n",
8363 		 p->name, p->level);
8364 	spin_lock(&pers_lock);
8365 	list_add_tail(&p->list, &pers_list);
8366 	spin_unlock(&pers_lock);
8367 	return 0;
8368 }
8369 EXPORT_SYMBOL(register_md_personality);
8370 
8371 int unregister_md_personality(struct md_personality *p)
8372 {
8373 	pr_debug("md: %s personality unregistered\n", p->name);
8374 	spin_lock(&pers_lock);
8375 	list_del_init(&p->list);
8376 	spin_unlock(&pers_lock);
8377 	return 0;
8378 }
8379 EXPORT_SYMBOL(unregister_md_personality);
8380 
8381 int register_md_cluster_operations(struct md_cluster_operations *ops,
8382 				   struct module *module)
8383 {
8384 	int ret = 0;
8385 	spin_lock(&pers_lock);
8386 	if (md_cluster_ops != NULL)
8387 		ret = -EALREADY;
8388 	else {
8389 		md_cluster_ops = ops;
8390 		md_cluster_mod = module;
8391 	}
8392 	spin_unlock(&pers_lock);
8393 	return ret;
8394 }
8395 EXPORT_SYMBOL(register_md_cluster_operations);
8396 
8397 int unregister_md_cluster_operations(void)
8398 {
8399 	spin_lock(&pers_lock);
8400 	md_cluster_ops = NULL;
8401 	spin_unlock(&pers_lock);
8402 	return 0;
8403 }
8404 EXPORT_SYMBOL(unregister_md_cluster_operations);
8405 
8406 int md_setup_cluster(struct mddev *mddev, int nodes)
8407 {
8408 	int ret;
8409 	if (!md_cluster_ops)
8410 		request_module("md-cluster");
8411 	spin_lock(&pers_lock);
8412 	/* ensure module won't be unloaded */
8413 	if (!md_cluster_ops || !try_module_get(md_cluster_mod)) {
8414 		pr_warn("can't find md-cluster module or get its reference.\n");
8415 		spin_unlock(&pers_lock);
8416 		return -ENOENT;
8417 	}
8418 	spin_unlock(&pers_lock);
8419 
8420 	ret = md_cluster_ops->join(mddev, nodes);
8421 	if (!ret)
8422 		mddev->safemode_delay = 0;
8423 	return ret;
8424 }
8425 
8426 void md_cluster_stop(struct mddev *mddev)
8427 {
8428 	if (!md_cluster_ops)
8429 		return;
8430 	md_cluster_ops->leave(mddev);
8431 	module_put(md_cluster_mod);
8432 }
8433 
8434 static int is_mddev_idle(struct mddev *mddev, int init)
8435 {
8436 	struct md_rdev *rdev;
8437 	int idle;
8438 	int curr_events;
8439 
8440 	idle = 1;
8441 	rcu_read_lock();
8442 	rdev_for_each_rcu(rdev, mddev) {
8443 		struct gendisk *disk = rdev->bdev->bd_disk;
8444 		curr_events = (int)part_stat_read_accum(disk->part0, sectors) -
8445 			      atomic_read(&disk->sync_io);
8446 		/* sync IO will cause sync_io to increase before the disk_stats
8447 		 * as sync_io is counted when a request starts, and
8448 		 * disk_stats is counted when it completes.
8449 		 * So resync activity will cause curr_events to be smaller than
8450 		 * when there was no such activity.
8451 		 * non-sync IO will cause disk_stat to increase without
8452 		 * increasing sync_io so curr_events will (eventually)
8453 		 * be larger than it was before.  Once it becomes
8454 		 * substantially larger, the test below will cause
8455 		 * the array to appear non-idle, and resync will slow
8456 		 * down.
8457 		 * If there is a lot of outstanding resync activity when
8458 		 * we set last_event to curr_events, then all that activity
8459 		 * completing might cause the array to appear non-idle
8460 		 * and resync will be slowed down even though there might
8461 		 * not have been non-resync activity.  This will only
8462 		 * happen once though.  'last_events' will soon reflect
8463 		 * the state where there is little or no outstanding
8464 		 * resync requests, and further resync activity will
8465 		 * always make curr_events less than last_events.
8466 		 *
8467 		 */
8468 		if (init || curr_events - rdev->last_events > 64) {
8469 			rdev->last_events = curr_events;
8470 			idle = 0;
8471 		}
8472 	}
8473 	rcu_read_unlock();
8474 	return idle;
8475 }
8476 
8477 void md_done_sync(struct mddev *mddev, int blocks, int ok)
8478 {
8479 	/* another "blocks" (512byte) blocks have been synced */
8480 	atomic_sub(blocks, &mddev->recovery_active);
8481 	wake_up(&mddev->recovery_wait);
8482 	if (!ok) {
8483 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8484 		set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
8485 		md_wakeup_thread(mddev->thread);
8486 		// stop recovery, signal do_sync ....
8487 	}
8488 }
8489 EXPORT_SYMBOL(md_done_sync);
8490 
8491 /* md_write_start(mddev, bi)
8492  * If we need to update some array metadata (e.g. 'active' flag
8493  * in superblock) before writing, schedule a superblock update
8494  * and wait for it to complete.
8495  * A return value of 'false' means that the write wasn't recorded
8496  * and cannot proceed as the array is being suspend.
8497  */
8498 bool md_write_start(struct mddev *mddev, struct bio *bi)
8499 {
8500 	int did_change = 0;
8501 
8502 	if (bio_data_dir(bi) != WRITE)
8503 		return true;
8504 
8505 	BUG_ON(mddev->ro == 1);
8506 	if (mddev->ro == 2) {
8507 		/* need to switch to read/write */
8508 		mddev->ro = 0;
8509 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8510 		md_wakeup_thread(mddev->thread);
8511 		md_wakeup_thread(mddev->sync_thread);
8512 		did_change = 1;
8513 	}
8514 	rcu_read_lock();
8515 	percpu_ref_get(&mddev->writes_pending);
8516 	smp_mb(); /* Match smp_mb in set_in_sync() */
8517 	if (mddev->safemode == 1)
8518 		mddev->safemode = 0;
8519 	/* sync_checkers is always 0 when writes_pending is in per-cpu mode */
8520 	if (mddev->in_sync || mddev->sync_checkers) {
8521 		spin_lock(&mddev->lock);
8522 		if (mddev->in_sync) {
8523 			mddev->in_sync = 0;
8524 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8525 			set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8526 			md_wakeup_thread(mddev->thread);
8527 			did_change = 1;
8528 		}
8529 		spin_unlock(&mddev->lock);
8530 	}
8531 	rcu_read_unlock();
8532 	if (did_change)
8533 		sysfs_notify_dirent_safe(mddev->sysfs_state);
8534 	if (!mddev->has_superblocks)
8535 		return true;
8536 	wait_event(mddev->sb_wait,
8537 		   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags) ||
8538 		   mddev->suspended);
8539 	if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
8540 		percpu_ref_put(&mddev->writes_pending);
8541 		return false;
8542 	}
8543 	return true;
8544 }
8545 EXPORT_SYMBOL(md_write_start);
8546 
8547 /* md_write_inc can only be called when md_write_start() has
8548  * already been called at least once of the current request.
8549  * It increments the counter and is useful when a single request
8550  * is split into several parts.  Each part causes an increment and
8551  * so needs a matching md_write_end().
8552  * Unlike md_write_start(), it is safe to call md_write_inc() inside
8553  * a spinlocked region.
8554  */
8555 void md_write_inc(struct mddev *mddev, struct bio *bi)
8556 {
8557 	if (bio_data_dir(bi) != WRITE)
8558 		return;
8559 	WARN_ON_ONCE(mddev->in_sync || mddev->ro);
8560 	percpu_ref_get(&mddev->writes_pending);
8561 }
8562 EXPORT_SYMBOL(md_write_inc);
8563 
8564 void md_write_end(struct mddev *mddev)
8565 {
8566 	percpu_ref_put(&mddev->writes_pending);
8567 
8568 	if (mddev->safemode == 2)
8569 		md_wakeup_thread(mddev->thread);
8570 	else if (mddev->safemode_delay)
8571 		/* The roundup() ensures this only performs locking once
8572 		 * every ->safemode_delay jiffies
8573 		 */
8574 		mod_timer(&mddev->safemode_timer,
8575 			  roundup(jiffies, mddev->safemode_delay) +
8576 			  mddev->safemode_delay);
8577 }
8578 
8579 EXPORT_SYMBOL(md_write_end);
8580 
8581 /* This is used by raid0 and raid10 */
8582 void md_submit_discard_bio(struct mddev *mddev, struct md_rdev *rdev,
8583 			struct bio *bio, sector_t start, sector_t size)
8584 {
8585 	struct bio *discard_bio = NULL;
8586 
8587 	if (__blkdev_issue_discard(rdev->bdev, start, size, GFP_NOIO,
8588 			&discard_bio) || !discard_bio)
8589 		return;
8590 
8591 	bio_chain(discard_bio, bio);
8592 	bio_clone_blkg_association(discard_bio, bio);
8593 	if (mddev->gendisk)
8594 		trace_block_bio_remap(discard_bio,
8595 				disk_devt(mddev->gendisk),
8596 				bio->bi_iter.bi_sector);
8597 	submit_bio_noacct(discard_bio);
8598 }
8599 EXPORT_SYMBOL_GPL(md_submit_discard_bio);
8600 
8601 int acct_bioset_init(struct mddev *mddev)
8602 {
8603 	int err = 0;
8604 
8605 	if (!bioset_initialized(&mddev->io_acct_set))
8606 		err = bioset_init(&mddev->io_acct_set, BIO_POOL_SIZE,
8607 			offsetof(struct md_io_acct, bio_clone), 0);
8608 	return err;
8609 }
8610 EXPORT_SYMBOL_GPL(acct_bioset_init);
8611 
8612 void acct_bioset_exit(struct mddev *mddev)
8613 {
8614 	bioset_exit(&mddev->io_acct_set);
8615 }
8616 EXPORT_SYMBOL_GPL(acct_bioset_exit);
8617 
8618 static void md_end_io_acct(struct bio *bio)
8619 {
8620 	struct md_io_acct *md_io_acct = bio->bi_private;
8621 	struct bio *orig_bio = md_io_acct->orig_bio;
8622 
8623 	orig_bio->bi_status = bio->bi_status;
8624 
8625 	bio_end_io_acct(orig_bio, md_io_acct->start_time);
8626 	bio_put(bio);
8627 	bio_endio(orig_bio);
8628 }
8629 
8630 /*
8631  * Used by personalities that don't already clone the bio and thus can't
8632  * easily add the timestamp to their extended bio structure.
8633  */
8634 void md_account_bio(struct mddev *mddev, struct bio **bio)
8635 {
8636 	struct block_device *bdev = (*bio)->bi_bdev;
8637 	struct md_io_acct *md_io_acct;
8638 	struct bio *clone;
8639 
8640 	if (!blk_queue_io_stat(bdev->bd_disk->queue))
8641 		return;
8642 
8643 	clone = bio_alloc_clone(bdev, *bio, GFP_NOIO, &mddev->io_acct_set);
8644 	md_io_acct = container_of(clone, struct md_io_acct, bio_clone);
8645 	md_io_acct->orig_bio = *bio;
8646 	md_io_acct->start_time = bio_start_io_acct(*bio);
8647 
8648 	clone->bi_end_io = md_end_io_acct;
8649 	clone->bi_private = md_io_acct;
8650 	*bio = clone;
8651 }
8652 EXPORT_SYMBOL_GPL(md_account_bio);
8653 
8654 /* md_allow_write(mddev)
8655  * Calling this ensures that the array is marked 'active' so that writes
8656  * may proceed without blocking.  It is important to call this before
8657  * attempting a GFP_KERNEL allocation while holding the mddev lock.
8658  * Must be called with mddev_lock held.
8659  */
8660 void md_allow_write(struct mddev *mddev)
8661 {
8662 	if (!mddev->pers)
8663 		return;
8664 	if (mddev->ro)
8665 		return;
8666 	if (!mddev->pers->sync_request)
8667 		return;
8668 
8669 	spin_lock(&mddev->lock);
8670 	if (mddev->in_sync) {
8671 		mddev->in_sync = 0;
8672 		set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8673 		set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8674 		if (mddev->safemode_delay &&
8675 		    mddev->safemode == 0)
8676 			mddev->safemode = 1;
8677 		spin_unlock(&mddev->lock);
8678 		md_update_sb(mddev, 0);
8679 		sysfs_notify_dirent_safe(mddev->sysfs_state);
8680 		/* wait for the dirty state to be recorded in the metadata */
8681 		wait_event(mddev->sb_wait,
8682 			   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
8683 	} else
8684 		spin_unlock(&mddev->lock);
8685 }
8686 EXPORT_SYMBOL_GPL(md_allow_write);
8687 
8688 #define SYNC_MARKS	10
8689 #define	SYNC_MARK_STEP	(3*HZ)
8690 #define UPDATE_FREQUENCY (5*60*HZ)
8691 void md_do_sync(struct md_thread *thread)
8692 {
8693 	struct mddev *mddev = thread->mddev;
8694 	struct mddev *mddev2;
8695 	unsigned int currspeed = 0, window;
8696 	sector_t max_sectors,j, io_sectors, recovery_done;
8697 	unsigned long mark[SYNC_MARKS];
8698 	unsigned long update_time;
8699 	sector_t mark_cnt[SYNC_MARKS];
8700 	int last_mark,m;
8701 	sector_t last_check;
8702 	int skipped = 0;
8703 	struct md_rdev *rdev;
8704 	char *desc, *action = NULL;
8705 	struct blk_plug plug;
8706 	int ret;
8707 
8708 	/* just incase thread restarts... */
8709 	if (test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8710 	    test_bit(MD_RECOVERY_WAIT, &mddev->recovery))
8711 		return;
8712 	if (mddev->ro) {/* never try to sync a read-only array */
8713 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8714 		return;
8715 	}
8716 
8717 	if (mddev_is_clustered(mddev)) {
8718 		ret = md_cluster_ops->resync_start(mddev);
8719 		if (ret)
8720 			goto skip;
8721 
8722 		set_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags);
8723 		if (!(test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
8724 			test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) ||
8725 			test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
8726 		     && ((unsigned long long)mddev->curr_resync_completed
8727 			 < (unsigned long long)mddev->resync_max_sectors))
8728 			goto skip;
8729 	}
8730 
8731 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8732 		if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
8733 			desc = "data-check";
8734 			action = "check";
8735 		} else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8736 			desc = "requested-resync";
8737 			action = "repair";
8738 		} else
8739 			desc = "resync";
8740 	} else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8741 		desc = "reshape";
8742 	else
8743 		desc = "recovery";
8744 
8745 	mddev->last_sync_action = action ?: desc;
8746 
8747 	/*
8748 	 * Before starting a resync we must have set curr_resync to
8749 	 * 2, and then checked that every "conflicting" array has curr_resync
8750 	 * less than ours.  When we find one that is the same or higher
8751 	 * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
8752 	 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
8753 	 * This will mean we have to start checking from the beginning again.
8754 	 *
8755 	 */
8756 
8757 	do {
8758 		int mddev2_minor = -1;
8759 		mddev->curr_resync = MD_RESYNC_DELAYED;
8760 
8761 	try_again:
8762 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8763 			goto skip;
8764 		spin_lock(&all_mddevs_lock);
8765 		list_for_each_entry(mddev2, &all_mddevs, all_mddevs) {
8766 			if (test_bit(MD_DELETED, &mddev2->flags))
8767 				continue;
8768 			if (mddev2 == mddev)
8769 				continue;
8770 			if (!mddev->parallel_resync
8771 			&&  mddev2->curr_resync
8772 			&&  match_mddev_units(mddev, mddev2)) {
8773 				DEFINE_WAIT(wq);
8774 				if (mddev < mddev2 &&
8775 				    mddev->curr_resync == MD_RESYNC_DELAYED) {
8776 					/* arbitrarily yield */
8777 					mddev->curr_resync = MD_RESYNC_YIELDED;
8778 					wake_up(&resync_wait);
8779 				}
8780 				if (mddev > mddev2 &&
8781 				    mddev->curr_resync == MD_RESYNC_YIELDED)
8782 					/* no need to wait here, we can wait the next
8783 					 * time 'round when curr_resync == 2
8784 					 */
8785 					continue;
8786 				/* We need to wait 'interruptible' so as not to
8787 				 * contribute to the load average, and not to
8788 				 * be caught by 'softlockup'
8789 				 */
8790 				prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
8791 				if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8792 				    mddev2->curr_resync >= mddev->curr_resync) {
8793 					if (mddev2_minor != mddev2->md_minor) {
8794 						mddev2_minor = mddev2->md_minor;
8795 						pr_info("md: delaying %s of %s until %s has finished (they share one or more physical units)\n",
8796 							desc, mdname(mddev),
8797 							mdname(mddev2));
8798 					}
8799 					spin_unlock(&all_mddevs_lock);
8800 
8801 					if (signal_pending(current))
8802 						flush_signals(current);
8803 					schedule();
8804 					finish_wait(&resync_wait, &wq);
8805 					goto try_again;
8806 				}
8807 				finish_wait(&resync_wait, &wq);
8808 			}
8809 		}
8810 		spin_unlock(&all_mddevs_lock);
8811 	} while (mddev->curr_resync < MD_RESYNC_DELAYED);
8812 
8813 	j = 0;
8814 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8815 		/* resync follows the size requested by the personality,
8816 		 * which defaults to physical size, but can be virtual size
8817 		 */
8818 		max_sectors = mddev->resync_max_sectors;
8819 		atomic64_set(&mddev->resync_mismatches, 0);
8820 		/* we don't use the checkpoint if there's a bitmap */
8821 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8822 			j = mddev->resync_min;
8823 		else if (!mddev->bitmap)
8824 			j = mddev->recovery_cp;
8825 
8826 	} else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
8827 		max_sectors = mddev->resync_max_sectors;
8828 		/*
8829 		 * If the original node aborts reshaping then we continue the
8830 		 * reshaping, so set j again to avoid restart reshape from the
8831 		 * first beginning
8832 		 */
8833 		if (mddev_is_clustered(mddev) &&
8834 		    mddev->reshape_position != MaxSector)
8835 			j = mddev->reshape_position;
8836 	} else {
8837 		/* recovery follows the physical size of devices */
8838 		max_sectors = mddev->dev_sectors;
8839 		j = MaxSector;
8840 		rcu_read_lock();
8841 		rdev_for_each_rcu(rdev, mddev)
8842 			if (rdev->raid_disk >= 0 &&
8843 			    !test_bit(Journal, &rdev->flags) &&
8844 			    !test_bit(Faulty, &rdev->flags) &&
8845 			    !test_bit(In_sync, &rdev->flags) &&
8846 			    rdev->recovery_offset < j)
8847 				j = rdev->recovery_offset;
8848 		rcu_read_unlock();
8849 
8850 		/* If there is a bitmap, we need to make sure all
8851 		 * writes that started before we added a spare
8852 		 * complete before we start doing a recovery.
8853 		 * Otherwise the write might complete and (via
8854 		 * bitmap_endwrite) set a bit in the bitmap after the
8855 		 * recovery has checked that bit and skipped that
8856 		 * region.
8857 		 */
8858 		if (mddev->bitmap) {
8859 			mddev->pers->quiesce(mddev, 1);
8860 			mddev->pers->quiesce(mddev, 0);
8861 		}
8862 	}
8863 
8864 	pr_info("md: %s of RAID array %s\n", desc, mdname(mddev));
8865 	pr_debug("md: minimum _guaranteed_  speed: %d KB/sec/disk.\n", speed_min(mddev));
8866 	pr_debug("md: using maximum available idle IO bandwidth (but not more than %d KB/sec) for %s.\n",
8867 		 speed_max(mddev), desc);
8868 
8869 	is_mddev_idle(mddev, 1); /* this initializes IO event counters */
8870 
8871 	io_sectors = 0;
8872 	for (m = 0; m < SYNC_MARKS; m++) {
8873 		mark[m] = jiffies;
8874 		mark_cnt[m] = io_sectors;
8875 	}
8876 	last_mark = 0;
8877 	mddev->resync_mark = mark[last_mark];
8878 	mddev->resync_mark_cnt = mark_cnt[last_mark];
8879 
8880 	/*
8881 	 * Tune reconstruction:
8882 	 */
8883 	window = 32 * (PAGE_SIZE / 512);
8884 	pr_debug("md: using %dk window, over a total of %lluk.\n",
8885 		 window/2, (unsigned long long)max_sectors/2);
8886 
8887 	atomic_set(&mddev->recovery_active, 0);
8888 	last_check = 0;
8889 
8890 	if (j>2) {
8891 		pr_debug("md: resuming %s of %s from checkpoint.\n",
8892 			 desc, mdname(mddev));
8893 		mddev->curr_resync = j;
8894 	} else
8895 		mddev->curr_resync = MD_RESYNC_ACTIVE; /* no longer delayed */
8896 	mddev->curr_resync_completed = j;
8897 	sysfs_notify_dirent_safe(mddev->sysfs_completed);
8898 	md_new_event();
8899 	update_time = jiffies;
8900 
8901 	blk_start_plug(&plug);
8902 	while (j < max_sectors) {
8903 		sector_t sectors;
8904 
8905 		skipped = 0;
8906 
8907 		if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8908 		    ((mddev->curr_resync > mddev->curr_resync_completed &&
8909 		      (mddev->curr_resync - mddev->curr_resync_completed)
8910 		      > (max_sectors >> 4)) ||
8911 		     time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
8912 		     (j - mddev->curr_resync_completed)*2
8913 		     >= mddev->resync_max - mddev->curr_resync_completed ||
8914 		     mddev->curr_resync_completed > mddev->resync_max
8915 			    )) {
8916 			/* time to update curr_resync_completed */
8917 			wait_event(mddev->recovery_wait,
8918 				   atomic_read(&mddev->recovery_active) == 0);
8919 			mddev->curr_resync_completed = j;
8920 			if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
8921 			    j > mddev->recovery_cp)
8922 				mddev->recovery_cp = j;
8923 			update_time = jiffies;
8924 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8925 			sysfs_notify_dirent_safe(mddev->sysfs_completed);
8926 		}
8927 
8928 		while (j >= mddev->resync_max &&
8929 		       !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8930 			/* As this condition is controlled by user-space,
8931 			 * we can block indefinitely, so use '_interruptible'
8932 			 * to avoid triggering warnings.
8933 			 */
8934 			flush_signals(current); /* just in case */
8935 			wait_event_interruptible(mddev->recovery_wait,
8936 						 mddev->resync_max > j
8937 						 || test_bit(MD_RECOVERY_INTR,
8938 							     &mddev->recovery));
8939 		}
8940 
8941 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8942 			break;
8943 
8944 		sectors = mddev->pers->sync_request(mddev, j, &skipped);
8945 		if (sectors == 0) {
8946 			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8947 			break;
8948 		}
8949 
8950 		if (!skipped) { /* actual IO requested */
8951 			io_sectors += sectors;
8952 			atomic_add(sectors, &mddev->recovery_active);
8953 		}
8954 
8955 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8956 			break;
8957 
8958 		j += sectors;
8959 		if (j > max_sectors)
8960 			/* when skipping, extra large numbers can be returned. */
8961 			j = max_sectors;
8962 		if (j > 2)
8963 			mddev->curr_resync = j;
8964 		mddev->curr_mark_cnt = io_sectors;
8965 		if (last_check == 0)
8966 			/* this is the earliest that rebuild will be
8967 			 * visible in /proc/mdstat
8968 			 */
8969 			md_new_event();
8970 
8971 		if (last_check + window > io_sectors || j == max_sectors)
8972 			continue;
8973 
8974 		last_check = io_sectors;
8975 	repeat:
8976 		if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
8977 			/* step marks */
8978 			int next = (last_mark+1) % SYNC_MARKS;
8979 
8980 			mddev->resync_mark = mark[next];
8981 			mddev->resync_mark_cnt = mark_cnt[next];
8982 			mark[next] = jiffies;
8983 			mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
8984 			last_mark = next;
8985 		}
8986 
8987 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8988 			break;
8989 
8990 		/*
8991 		 * this loop exits only if either when we are slower than
8992 		 * the 'hard' speed limit, or the system was IO-idle for
8993 		 * a jiffy.
8994 		 * the system might be non-idle CPU-wise, but we only care
8995 		 * about not overloading the IO subsystem. (things like an
8996 		 * e2fsck being done on the RAID array should execute fast)
8997 		 */
8998 		cond_resched();
8999 
9000 		recovery_done = io_sectors - atomic_read(&mddev->recovery_active);
9001 		currspeed = ((unsigned long)(recovery_done - mddev->resync_mark_cnt))/2
9002 			/((jiffies-mddev->resync_mark)/HZ +1) +1;
9003 
9004 		if (currspeed > speed_min(mddev)) {
9005 			if (currspeed > speed_max(mddev)) {
9006 				msleep(500);
9007 				goto repeat;
9008 			}
9009 			if (!is_mddev_idle(mddev, 0)) {
9010 				/*
9011 				 * Give other IO more of a chance.
9012 				 * The faster the devices, the less we wait.
9013 				 */
9014 				wait_event(mddev->recovery_wait,
9015 					   !atomic_read(&mddev->recovery_active));
9016 			}
9017 		}
9018 	}
9019 	pr_info("md: %s: %s %s.\n",mdname(mddev), desc,
9020 		test_bit(MD_RECOVERY_INTR, &mddev->recovery)
9021 		? "interrupted" : "done");
9022 	/*
9023 	 * this also signals 'finished resyncing' to md_stop
9024 	 */
9025 	blk_finish_plug(&plug);
9026 	wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
9027 
9028 	if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
9029 	    !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
9030 	    mddev->curr_resync >= MD_RESYNC_ACTIVE) {
9031 		mddev->curr_resync_completed = mddev->curr_resync;
9032 		sysfs_notify_dirent_safe(mddev->sysfs_completed);
9033 	}
9034 	mddev->pers->sync_request(mddev, max_sectors, &skipped);
9035 
9036 	if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
9037 	    mddev->curr_resync >= MD_RESYNC_ACTIVE) {
9038 		if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
9039 			if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
9040 				if (mddev->curr_resync >= mddev->recovery_cp) {
9041 					pr_debug("md: checkpointing %s of %s.\n",
9042 						 desc, mdname(mddev));
9043 					if (test_bit(MD_RECOVERY_ERROR,
9044 						&mddev->recovery))
9045 						mddev->recovery_cp =
9046 							mddev->curr_resync_completed;
9047 					else
9048 						mddev->recovery_cp =
9049 							mddev->curr_resync;
9050 				}
9051 			} else
9052 				mddev->recovery_cp = MaxSector;
9053 		} else {
9054 			if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
9055 				mddev->curr_resync = MaxSector;
9056 			if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
9057 			    test_bit(MD_RECOVERY_RECOVER, &mddev->recovery)) {
9058 				rcu_read_lock();
9059 				rdev_for_each_rcu(rdev, mddev)
9060 					if (rdev->raid_disk >= 0 &&
9061 					    mddev->delta_disks >= 0 &&
9062 					    !test_bit(Journal, &rdev->flags) &&
9063 					    !test_bit(Faulty, &rdev->flags) &&
9064 					    !test_bit(In_sync, &rdev->flags) &&
9065 					    rdev->recovery_offset < mddev->curr_resync)
9066 						rdev->recovery_offset = mddev->curr_resync;
9067 				rcu_read_unlock();
9068 			}
9069 		}
9070 	}
9071  skip:
9072 	/* set CHANGE_PENDING here since maybe another update is needed,
9073 	 * so other nodes are informed. It should be harmless for normal
9074 	 * raid */
9075 	set_mask_bits(&mddev->sb_flags, 0,
9076 		      BIT(MD_SB_CHANGE_PENDING) | BIT(MD_SB_CHANGE_DEVS));
9077 
9078 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
9079 			!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
9080 			mddev->delta_disks > 0 &&
9081 			mddev->pers->finish_reshape &&
9082 			mddev->pers->size &&
9083 			mddev->queue) {
9084 		mddev_lock_nointr(mddev);
9085 		md_set_array_sectors(mddev, mddev->pers->size(mddev, 0, 0));
9086 		mddev_unlock(mddev);
9087 		if (!mddev_is_clustered(mddev))
9088 			set_capacity_and_notify(mddev->gendisk,
9089 						mddev->array_sectors);
9090 	}
9091 
9092 	spin_lock(&mddev->lock);
9093 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
9094 		/* We completed so min/max setting can be forgotten if used. */
9095 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
9096 			mddev->resync_min = 0;
9097 		mddev->resync_max = MaxSector;
9098 	} else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
9099 		mddev->resync_min = mddev->curr_resync_completed;
9100 	set_bit(MD_RECOVERY_DONE, &mddev->recovery);
9101 	mddev->curr_resync = MD_RESYNC_NONE;
9102 	spin_unlock(&mddev->lock);
9103 
9104 	wake_up(&resync_wait);
9105 	md_wakeup_thread(mddev->thread);
9106 	return;
9107 }
9108 EXPORT_SYMBOL_GPL(md_do_sync);
9109 
9110 static int remove_and_add_spares(struct mddev *mddev,
9111 				 struct md_rdev *this)
9112 {
9113 	struct md_rdev *rdev;
9114 	int spares = 0;
9115 	int removed = 0;
9116 	bool remove_some = false;
9117 
9118 	if (this && test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
9119 		/* Mustn't remove devices when resync thread is running */
9120 		return 0;
9121 
9122 	rdev_for_each(rdev, mddev) {
9123 		if ((this == NULL || rdev == this) &&
9124 		    rdev->raid_disk >= 0 &&
9125 		    !test_bit(Blocked, &rdev->flags) &&
9126 		    test_bit(Faulty, &rdev->flags) &&
9127 		    atomic_read(&rdev->nr_pending)==0) {
9128 			/* Faulty non-Blocked devices with nr_pending == 0
9129 			 * never get nr_pending incremented,
9130 			 * never get Faulty cleared, and never get Blocked set.
9131 			 * So we can synchronize_rcu now rather than once per device
9132 			 */
9133 			remove_some = true;
9134 			set_bit(RemoveSynchronized, &rdev->flags);
9135 		}
9136 	}
9137 
9138 	if (remove_some)
9139 		synchronize_rcu();
9140 	rdev_for_each(rdev, mddev) {
9141 		if ((this == NULL || rdev == this) &&
9142 		    rdev->raid_disk >= 0 &&
9143 		    !test_bit(Blocked, &rdev->flags) &&
9144 		    ((test_bit(RemoveSynchronized, &rdev->flags) ||
9145 		     (!test_bit(In_sync, &rdev->flags) &&
9146 		      !test_bit(Journal, &rdev->flags))) &&
9147 		    atomic_read(&rdev->nr_pending)==0)) {
9148 			if (mddev->pers->hot_remove_disk(
9149 				    mddev, rdev) == 0) {
9150 				sysfs_unlink_rdev(mddev, rdev);
9151 				rdev->saved_raid_disk = rdev->raid_disk;
9152 				rdev->raid_disk = -1;
9153 				removed++;
9154 			}
9155 		}
9156 		if (remove_some && test_bit(RemoveSynchronized, &rdev->flags))
9157 			clear_bit(RemoveSynchronized, &rdev->flags);
9158 	}
9159 
9160 	if (removed && mddev->kobj.sd)
9161 		sysfs_notify_dirent_safe(mddev->sysfs_degraded);
9162 
9163 	if (this && removed)
9164 		goto no_add;
9165 
9166 	rdev_for_each(rdev, mddev) {
9167 		if (this && this != rdev)
9168 			continue;
9169 		if (test_bit(Candidate, &rdev->flags))
9170 			continue;
9171 		if (rdev->raid_disk >= 0 &&
9172 		    !test_bit(In_sync, &rdev->flags) &&
9173 		    !test_bit(Journal, &rdev->flags) &&
9174 		    !test_bit(Faulty, &rdev->flags))
9175 			spares++;
9176 		if (rdev->raid_disk >= 0)
9177 			continue;
9178 		if (test_bit(Faulty, &rdev->flags))
9179 			continue;
9180 		if (!test_bit(Journal, &rdev->flags)) {
9181 			if (mddev->ro &&
9182 			    ! (rdev->saved_raid_disk >= 0 &&
9183 			       !test_bit(Bitmap_sync, &rdev->flags)))
9184 				continue;
9185 
9186 			rdev->recovery_offset = 0;
9187 		}
9188 		if (mddev->pers->hot_add_disk(mddev, rdev) == 0) {
9189 			/* failure here is OK */
9190 			sysfs_link_rdev(mddev, rdev);
9191 			if (!test_bit(Journal, &rdev->flags))
9192 				spares++;
9193 			md_new_event();
9194 			set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
9195 		}
9196 	}
9197 no_add:
9198 	if (removed)
9199 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
9200 	return spares;
9201 }
9202 
9203 static void md_start_sync(struct work_struct *ws)
9204 {
9205 	struct mddev *mddev = container_of(ws, struct mddev, del_work);
9206 
9207 	mddev->sync_thread = md_register_thread(md_do_sync,
9208 						mddev,
9209 						"resync");
9210 	if (!mddev->sync_thread) {
9211 		pr_warn("%s: could not start resync thread...\n",
9212 			mdname(mddev));
9213 		/* leave the spares where they are, it shouldn't hurt */
9214 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
9215 		clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
9216 		clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
9217 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
9218 		clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
9219 		wake_up(&resync_wait);
9220 		if (test_and_clear_bit(MD_RECOVERY_RECOVER,
9221 				       &mddev->recovery))
9222 			if (mddev->sysfs_action)
9223 				sysfs_notify_dirent_safe(mddev->sysfs_action);
9224 	} else
9225 		md_wakeup_thread(mddev->sync_thread);
9226 	sysfs_notify_dirent_safe(mddev->sysfs_action);
9227 	md_new_event();
9228 }
9229 
9230 /*
9231  * This routine is regularly called by all per-raid-array threads to
9232  * deal with generic issues like resync and super-block update.
9233  * Raid personalities that don't have a thread (linear/raid0) do not
9234  * need this as they never do any recovery or update the superblock.
9235  *
9236  * It does not do any resync itself, but rather "forks" off other threads
9237  * to do that as needed.
9238  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
9239  * "->recovery" and create a thread at ->sync_thread.
9240  * When the thread finishes it sets MD_RECOVERY_DONE
9241  * and wakeups up this thread which will reap the thread and finish up.
9242  * This thread also removes any faulty devices (with nr_pending == 0).
9243  *
9244  * The overall approach is:
9245  *  1/ if the superblock needs updating, update it.
9246  *  2/ If a recovery thread is running, don't do anything else.
9247  *  3/ If recovery has finished, clean up, possibly marking spares active.
9248  *  4/ If there are any faulty devices, remove them.
9249  *  5/ If array is degraded, try to add spares devices
9250  *  6/ If array has spares or is not in-sync, start a resync thread.
9251  */
9252 void md_check_recovery(struct mddev *mddev)
9253 {
9254 	if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags) && mddev->sb_flags) {
9255 		/* Write superblock - thread that called mddev_suspend()
9256 		 * holds reconfig_mutex for us.
9257 		 */
9258 		set_bit(MD_UPDATING_SB, &mddev->flags);
9259 		smp_mb__after_atomic();
9260 		if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags))
9261 			md_update_sb(mddev, 0);
9262 		clear_bit_unlock(MD_UPDATING_SB, &mddev->flags);
9263 		wake_up(&mddev->sb_wait);
9264 	}
9265 
9266 	if (mddev->suspended)
9267 		return;
9268 
9269 	if (mddev->bitmap)
9270 		md_bitmap_daemon_work(mddev);
9271 
9272 	if (signal_pending(current)) {
9273 		if (mddev->pers->sync_request && !mddev->external) {
9274 			pr_debug("md: %s in immediate safe mode\n",
9275 				 mdname(mddev));
9276 			mddev->safemode = 2;
9277 		}
9278 		flush_signals(current);
9279 	}
9280 
9281 	if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
9282 		return;
9283 	if ( ! (
9284 		(mddev->sb_flags & ~ (1<<MD_SB_CHANGE_PENDING)) ||
9285 		test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
9286 		test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
9287 		(mddev->external == 0 && mddev->safemode == 1) ||
9288 		(mddev->safemode == 2
9289 		 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
9290 		))
9291 		return;
9292 
9293 	if (mddev_trylock(mddev)) {
9294 		int spares = 0;
9295 		bool try_set_sync = mddev->safemode != 0;
9296 
9297 		if (!mddev->external && mddev->safemode == 1)
9298 			mddev->safemode = 0;
9299 
9300 		if (mddev->ro) {
9301 			struct md_rdev *rdev;
9302 			if (!mddev->external && mddev->in_sync)
9303 				/* 'Blocked' flag not needed as failed devices
9304 				 * will be recorded if array switched to read/write.
9305 				 * Leaving it set will prevent the device
9306 				 * from being removed.
9307 				 */
9308 				rdev_for_each(rdev, mddev)
9309 					clear_bit(Blocked, &rdev->flags);
9310 			/* On a read-only array we can:
9311 			 * - remove failed devices
9312 			 * - add already-in_sync devices if the array itself
9313 			 *   is in-sync.
9314 			 * As we only add devices that are already in-sync,
9315 			 * we can activate the spares immediately.
9316 			 */
9317 			remove_and_add_spares(mddev, NULL);
9318 			/* There is no thread, but we need to call
9319 			 * ->spare_active and clear saved_raid_disk
9320 			 */
9321 			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
9322 			md_unregister_thread(&mddev->sync_thread);
9323 			md_reap_sync_thread(mddev);
9324 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9325 			clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9326 			clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
9327 			goto unlock;
9328 		}
9329 
9330 		if (mddev_is_clustered(mddev)) {
9331 			struct md_rdev *rdev, *tmp;
9332 			/* kick the device if another node issued a
9333 			 * remove disk.
9334 			 */
9335 			rdev_for_each_safe(rdev, tmp, mddev) {
9336 				if (test_and_clear_bit(ClusterRemove, &rdev->flags) &&
9337 						rdev->raid_disk < 0)
9338 					md_kick_rdev_from_array(rdev);
9339 			}
9340 		}
9341 
9342 		if (try_set_sync && !mddev->external && !mddev->in_sync) {
9343 			spin_lock(&mddev->lock);
9344 			set_in_sync(mddev);
9345 			spin_unlock(&mddev->lock);
9346 		}
9347 
9348 		if (mddev->sb_flags)
9349 			md_update_sb(mddev, 0);
9350 
9351 		if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
9352 		    !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
9353 			/* resync/recovery still happening */
9354 			clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9355 			goto unlock;
9356 		}
9357 		if (mddev->sync_thread) {
9358 			md_unregister_thread(&mddev->sync_thread);
9359 			md_reap_sync_thread(mddev);
9360 			goto unlock;
9361 		}
9362 		/* Set RUNNING before clearing NEEDED to avoid
9363 		 * any transients in the value of "sync_action".
9364 		 */
9365 		mddev->curr_resync_completed = 0;
9366 		spin_lock(&mddev->lock);
9367 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
9368 		spin_unlock(&mddev->lock);
9369 		/* Clear some bits that don't mean anything, but
9370 		 * might be left set
9371 		 */
9372 		clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
9373 		clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
9374 
9375 		if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
9376 		    test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
9377 			goto not_running;
9378 		/* no recovery is running.
9379 		 * remove any failed drives, then
9380 		 * add spares if possible.
9381 		 * Spares are also removed and re-added, to allow
9382 		 * the personality to fail the re-add.
9383 		 */
9384 
9385 		if (mddev->reshape_position != MaxSector) {
9386 			if (mddev->pers->check_reshape == NULL ||
9387 			    mddev->pers->check_reshape(mddev) != 0)
9388 				/* Cannot proceed */
9389 				goto not_running;
9390 			set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
9391 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9392 		} else if ((spares = remove_and_add_spares(mddev, NULL))) {
9393 			clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
9394 			clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
9395 			clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
9396 			set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9397 		} else if (mddev->recovery_cp < MaxSector) {
9398 			set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
9399 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9400 		} else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
9401 			/* nothing to be done ... */
9402 			goto not_running;
9403 
9404 		if (mddev->pers->sync_request) {
9405 			if (spares) {
9406 				/* We are adding a device or devices to an array
9407 				 * which has the bitmap stored on all devices.
9408 				 * So make sure all bitmap pages get written
9409 				 */
9410 				md_bitmap_write_all(mddev->bitmap);
9411 			}
9412 			INIT_WORK(&mddev->del_work, md_start_sync);
9413 			queue_work(md_misc_wq, &mddev->del_work);
9414 			goto unlock;
9415 		}
9416 	not_running:
9417 		if (!mddev->sync_thread) {
9418 			clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
9419 			wake_up(&resync_wait);
9420 			if (test_and_clear_bit(MD_RECOVERY_RECOVER,
9421 					       &mddev->recovery))
9422 				if (mddev->sysfs_action)
9423 					sysfs_notify_dirent_safe(mddev->sysfs_action);
9424 		}
9425 	unlock:
9426 		wake_up(&mddev->sb_wait);
9427 		mddev_unlock(mddev);
9428 	}
9429 }
9430 EXPORT_SYMBOL(md_check_recovery);
9431 
9432 void md_reap_sync_thread(struct mddev *mddev)
9433 {
9434 	struct md_rdev *rdev;
9435 	sector_t old_dev_sectors = mddev->dev_sectors;
9436 	bool is_reshaped = false;
9437 
9438 	/* sync_thread should be unregistered, collect result */
9439 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
9440 	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
9441 	    mddev->degraded != mddev->raid_disks) {
9442 		/* success...*/
9443 		/* activate any spares */
9444 		if (mddev->pers->spare_active(mddev)) {
9445 			sysfs_notify_dirent_safe(mddev->sysfs_degraded);
9446 			set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
9447 		}
9448 	}
9449 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
9450 	    mddev->pers->finish_reshape) {
9451 		mddev->pers->finish_reshape(mddev);
9452 		if (mddev_is_clustered(mddev))
9453 			is_reshaped = true;
9454 	}
9455 
9456 	/* If array is no-longer degraded, then any saved_raid_disk
9457 	 * information must be scrapped.
9458 	 */
9459 	if (!mddev->degraded)
9460 		rdev_for_each(rdev, mddev)
9461 			rdev->saved_raid_disk = -1;
9462 
9463 	md_update_sb(mddev, 1);
9464 	/* MD_SB_CHANGE_PENDING should be cleared by md_update_sb, so we can
9465 	 * call resync_finish here if MD_CLUSTER_RESYNC_LOCKED is set by
9466 	 * clustered raid */
9467 	if (test_and_clear_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags))
9468 		md_cluster_ops->resync_finish(mddev);
9469 	clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
9470 	clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
9471 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
9472 	clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
9473 	clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
9474 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
9475 	/*
9476 	 * We call md_cluster_ops->update_size here because sync_size could
9477 	 * be changed by md_update_sb, and MD_RECOVERY_RESHAPE is cleared,
9478 	 * so it is time to update size across cluster.
9479 	 */
9480 	if (mddev_is_clustered(mddev) && is_reshaped
9481 				      && !test_bit(MD_CLOSING, &mddev->flags))
9482 		md_cluster_ops->update_size(mddev, old_dev_sectors);
9483 	wake_up(&resync_wait);
9484 	/* flag recovery needed just to double check */
9485 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9486 	sysfs_notify_dirent_safe(mddev->sysfs_completed);
9487 	sysfs_notify_dirent_safe(mddev->sysfs_action);
9488 	md_new_event();
9489 	if (mddev->event_work.func)
9490 		queue_work(md_misc_wq, &mddev->event_work);
9491 }
9492 EXPORT_SYMBOL(md_reap_sync_thread);
9493 
9494 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
9495 {
9496 	sysfs_notify_dirent_safe(rdev->sysfs_state);
9497 	wait_event_timeout(rdev->blocked_wait,
9498 			   !test_bit(Blocked, &rdev->flags) &&
9499 			   !test_bit(BlockedBadBlocks, &rdev->flags),
9500 			   msecs_to_jiffies(5000));
9501 	rdev_dec_pending(rdev, mddev);
9502 }
9503 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
9504 
9505 void md_finish_reshape(struct mddev *mddev)
9506 {
9507 	/* called be personality module when reshape completes. */
9508 	struct md_rdev *rdev;
9509 
9510 	rdev_for_each(rdev, mddev) {
9511 		if (rdev->data_offset > rdev->new_data_offset)
9512 			rdev->sectors += rdev->data_offset - rdev->new_data_offset;
9513 		else
9514 			rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
9515 		rdev->data_offset = rdev->new_data_offset;
9516 	}
9517 }
9518 EXPORT_SYMBOL(md_finish_reshape);
9519 
9520 /* Bad block management */
9521 
9522 /* Returns 1 on success, 0 on failure */
9523 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9524 		       int is_new)
9525 {
9526 	struct mddev *mddev = rdev->mddev;
9527 	int rv;
9528 	if (is_new)
9529 		s += rdev->new_data_offset;
9530 	else
9531 		s += rdev->data_offset;
9532 	rv = badblocks_set(&rdev->badblocks, s, sectors, 0);
9533 	if (rv == 0) {
9534 		/* Make sure they get written out promptly */
9535 		if (test_bit(ExternalBbl, &rdev->flags))
9536 			sysfs_notify_dirent_safe(rdev->sysfs_unack_badblocks);
9537 		sysfs_notify_dirent_safe(rdev->sysfs_state);
9538 		set_mask_bits(&mddev->sb_flags, 0,
9539 			      BIT(MD_SB_CHANGE_CLEAN) | BIT(MD_SB_CHANGE_PENDING));
9540 		md_wakeup_thread(rdev->mddev->thread);
9541 		return 1;
9542 	} else
9543 		return 0;
9544 }
9545 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
9546 
9547 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9548 			 int is_new)
9549 {
9550 	int rv;
9551 	if (is_new)
9552 		s += rdev->new_data_offset;
9553 	else
9554 		s += rdev->data_offset;
9555 	rv = badblocks_clear(&rdev->badblocks, s, sectors);
9556 	if ((rv == 0) && test_bit(ExternalBbl, &rdev->flags))
9557 		sysfs_notify_dirent_safe(rdev->sysfs_badblocks);
9558 	return rv;
9559 }
9560 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
9561 
9562 static int md_notify_reboot(struct notifier_block *this,
9563 			    unsigned long code, void *x)
9564 {
9565 	struct mddev *mddev, *n;
9566 	int need_delay = 0;
9567 
9568 	spin_lock(&all_mddevs_lock);
9569 	list_for_each_entry_safe(mddev, n, &all_mddevs, all_mddevs) {
9570 		if (!mddev_get(mddev))
9571 			continue;
9572 		spin_unlock(&all_mddevs_lock);
9573 		if (mddev_trylock(mddev)) {
9574 			if (mddev->pers)
9575 				__md_stop_writes(mddev);
9576 			if (mddev->persistent)
9577 				mddev->safemode = 2;
9578 			mddev_unlock(mddev);
9579 		}
9580 		need_delay = 1;
9581 		mddev_put(mddev);
9582 		spin_lock(&all_mddevs_lock);
9583 	}
9584 	spin_unlock(&all_mddevs_lock);
9585 
9586 	/*
9587 	 * certain more exotic SCSI devices are known to be
9588 	 * volatile wrt too early system reboots. While the
9589 	 * right place to handle this issue is the given
9590 	 * driver, we do want to have a safe RAID driver ...
9591 	 */
9592 	if (need_delay)
9593 		msleep(1000);
9594 
9595 	return NOTIFY_DONE;
9596 }
9597 
9598 static struct notifier_block md_notifier = {
9599 	.notifier_call	= md_notify_reboot,
9600 	.next		= NULL,
9601 	.priority	= INT_MAX, /* before any real devices */
9602 };
9603 
9604 static void md_geninit(void)
9605 {
9606 	pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
9607 
9608 	proc_create("mdstat", S_IRUGO, NULL, &mdstat_proc_ops);
9609 }
9610 
9611 static int __init md_init(void)
9612 {
9613 	int ret = -ENOMEM;
9614 
9615 	md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
9616 	if (!md_wq)
9617 		goto err_wq;
9618 
9619 	md_misc_wq = alloc_workqueue("md_misc", 0, 0);
9620 	if (!md_misc_wq)
9621 		goto err_misc_wq;
9622 
9623 	md_rdev_misc_wq = alloc_workqueue("md_rdev_misc", 0, 0);
9624 	if (!md_rdev_misc_wq)
9625 		goto err_rdev_misc_wq;
9626 
9627 	ret = __register_blkdev(MD_MAJOR, "md", md_probe);
9628 	if (ret < 0)
9629 		goto err_md;
9630 
9631 	ret = __register_blkdev(0, "mdp", md_probe);
9632 	if (ret < 0)
9633 		goto err_mdp;
9634 	mdp_major = ret;
9635 
9636 	register_reboot_notifier(&md_notifier);
9637 	raid_table_header = register_sysctl_table(raid_root_table);
9638 
9639 	md_geninit();
9640 	return 0;
9641 
9642 err_mdp:
9643 	unregister_blkdev(MD_MAJOR, "md");
9644 err_md:
9645 	destroy_workqueue(md_rdev_misc_wq);
9646 err_rdev_misc_wq:
9647 	destroy_workqueue(md_misc_wq);
9648 err_misc_wq:
9649 	destroy_workqueue(md_wq);
9650 err_wq:
9651 	return ret;
9652 }
9653 
9654 static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
9655 {
9656 	struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
9657 	struct md_rdev *rdev2, *tmp;
9658 	int role, ret;
9659 
9660 	/*
9661 	 * If size is changed in another node then we need to
9662 	 * do resize as well.
9663 	 */
9664 	if (mddev->dev_sectors != le64_to_cpu(sb->size)) {
9665 		ret = mddev->pers->resize(mddev, le64_to_cpu(sb->size));
9666 		if (ret)
9667 			pr_info("md-cluster: resize failed\n");
9668 		else
9669 			md_bitmap_update_sb(mddev->bitmap);
9670 	}
9671 
9672 	/* Check for change of roles in the active devices */
9673 	rdev_for_each_safe(rdev2, tmp, mddev) {
9674 		if (test_bit(Faulty, &rdev2->flags))
9675 			continue;
9676 
9677 		/* Check if the roles changed */
9678 		role = le16_to_cpu(sb->dev_roles[rdev2->desc_nr]);
9679 
9680 		if (test_bit(Candidate, &rdev2->flags)) {
9681 			if (role == MD_DISK_ROLE_FAULTY) {
9682 				pr_info("md: Removing Candidate device %pg because add failed\n",
9683 					rdev2->bdev);
9684 				md_kick_rdev_from_array(rdev2);
9685 				continue;
9686 			}
9687 			else
9688 				clear_bit(Candidate, &rdev2->flags);
9689 		}
9690 
9691 		if (role != rdev2->raid_disk) {
9692 			/*
9693 			 * got activated except reshape is happening.
9694 			 */
9695 			if (rdev2->raid_disk == -1 && role != MD_DISK_ROLE_SPARE &&
9696 			    !(le32_to_cpu(sb->feature_map) &
9697 			      MD_FEATURE_RESHAPE_ACTIVE)) {
9698 				rdev2->saved_raid_disk = role;
9699 				ret = remove_and_add_spares(mddev, rdev2);
9700 				pr_info("Activated spare: %pg\n",
9701 					rdev2->bdev);
9702 				/* wakeup mddev->thread here, so array could
9703 				 * perform resync with the new activated disk */
9704 				set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9705 				md_wakeup_thread(mddev->thread);
9706 			}
9707 			/* device faulty
9708 			 * We just want to do the minimum to mark the disk
9709 			 * as faulty. The recovery is performed by the
9710 			 * one who initiated the error.
9711 			 */
9712 			if (role == MD_DISK_ROLE_FAULTY ||
9713 			    role == MD_DISK_ROLE_JOURNAL) {
9714 				md_error(mddev, rdev2);
9715 				clear_bit(Blocked, &rdev2->flags);
9716 			}
9717 		}
9718 	}
9719 
9720 	if (mddev->raid_disks != le32_to_cpu(sb->raid_disks)) {
9721 		ret = update_raid_disks(mddev, le32_to_cpu(sb->raid_disks));
9722 		if (ret)
9723 			pr_warn("md: updating array disks failed. %d\n", ret);
9724 	}
9725 
9726 	/*
9727 	 * Since mddev->delta_disks has already updated in update_raid_disks,
9728 	 * so it is time to check reshape.
9729 	 */
9730 	if (test_bit(MD_RESYNCING_REMOTE, &mddev->recovery) &&
9731 	    (le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
9732 		/*
9733 		 * reshape is happening in the remote node, we need to
9734 		 * update reshape_position and call start_reshape.
9735 		 */
9736 		mddev->reshape_position = le64_to_cpu(sb->reshape_position);
9737 		if (mddev->pers->update_reshape_pos)
9738 			mddev->pers->update_reshape_pos(mddev);
9739 		if (mddev->pers->start_reshape)
9740 			mddev->pers->start_reshape(mddev);
9741 	} else if (test_bit(MD_RESYNCING_REMOTE, &mddev->recovery) &&
9742 		   mddev->reshape_position != MaxSector &&
9743 		   !(le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
9744 		/* reshape is just done in another node. */
9745 		mddev->reshape_position = MaxSector;
9746 		if (mddev->pers->update_reshape_pos)
9747 			mddev->pers->update_reshape_pos(mddev);
9748 	}
9749 
9750 	/* Finally set the event to be up to date */
9751 	mddev->events = le64_to_cpu(sb->events);
9752 }
9753 
9754 static int read_rdev(struct mddev *mddev, struct md_rdev *rdev)
9755 {
9756 	int err;
9757 	struct page *swapout = rdev->sb_page;
9758 	struct mdp_superblock_1 *sb;
9759 
9760 	/* Store the sb page of the rdev in the swapout temporary
9761 	 * variable in case we err in the future
9762 	 */
9763 	rdev->sb_page = NULL;
9764 	err = alloc_disk_sb(rdev);
9765 	if (err == 0) {
9766 		ClearPageUptodate(rdev->sb_page);
9767 		rdev->sb_loaded = 0;
9768 		err = super_types[mddev->major_version].
9769 			load_super(rdev, NULL, mddev->minor_version);
9770 	}
9771 	if (err < 0) {
9772 		pr_warn("%s: %d Could not reload rdev(%d) err: %d. Restoring old values\n",
9773 				__func__, __LINE__, rdev->desc_nr, err);
9774 		if (rdev->sb_page)
9775 			put_page(rdev->sb_page);
9776 		rdev->sb_page = swapout;
9777 		rdev->sb_loaded = 1;
9778 		return err;
9779 	}
9780 
9781 	sb = page_address(rdev->sb_page);
9782 	/* Read the offset unconditionally, even if MD_FEATURE_RECOVERY_OFFSET
9783 	 * is not set
9784 	 */
9785 
9786 	if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RECOVERY_OFFSET))
9787 		rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
9788 
9789 	/* The other node finished recovery, call spare_active to set
9790 	 * device In_sync and mddev->degraded
9791 	 */
9792 	if (rdev->recovery_offset == MaxSector &&
9793 	    !test_bit(In_sync, &rdev->flags) &&
9794 	    mddev->pers->spare_active(mddev))
9795 		sysfs_notify_dirent_safe(mddev->sysfs_degraded);
9796 
9797 	put_page(swapout);
9798 	return 0;
9799 }
9800 
9801 void md_reload_sb(struct mddev *mddev, int nr)
9802 {
9803 	struct md_rdev *rdev = NULL, *iter;
9804 	int err;
9805 
9806 	/* Find the rdev */
9807 	rdev_for_each_rcu(iter, mddev) {
9808 		if (iter->desc_nr == nr) {
9809 			rdev = iter;
9810 			break;
9811 		}
9812 	}
9813 
9814 	if (!rdev) {
9815 		pr_warn("%s: %d Could not find rdev with nr %d\n", __func__, __LINE__, nr);
9816 		return;
9817 	}
9818 
9819 	err = read_rdev(mddev, rdev);
9820 	if (err < 0)
9821 		return;
9822 
9823 	check_sb_changes(mddev, rdev);
9824 
9825 	/* Read all rdev's to update recovery_offset */
9826 	rdev_for_each_rcu(rdev, mddev) {
9827 		if (!test_bit(Faulty, &rdev->flags))
9828 			read_rdev(mddev, rdev);
9829 	}
9830 }
9831 EXPORT_SYMBOL(md_reload_sb);
9832 
9833 #ifndef MODULE
9834 
9835 /*
9836  * Searches all registered partitions for autorun RAID arrays
9837  * at boot time.
9838  */
9839 
9840 static DEFINE_MUTEX(detected_devices_mutex);
9841 static LIST_HEAD(all_detected_devices);
9842 struct detected_devices_node {
9843 	struct list_head list;
9844 	dev_t dev;
9845 };
9846 
9847 void md_autodetect_dev(dev_t dev)
9848 {
9849 	struct detected_devices_node *node_detected_dev;
9850 
9851 	node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
9852 	if (node_detected_dev) {
9853 		node_detected_dev->dev = dev;
9854 		mutex_lock(&detected_devices_mutex);
9855 		list_add_tail(&node_detected_dev->list, &all_detected_devices);
9856 		mutex_unlock(&detected_devices_mutex);
9857 	}
9858 }
9859 
9860 void md_autostart_arrays(int part)
9861 {
9862 	struct md_rdev *rdev;
9863 	struct detected_devices_node *node_detected_dev;
9864 	dev_t dev;
9865 	int i_scanned, i_passed;
9866 
9867 	i_scanned = 0;
9868 	i_passed = 0;
9869 
9870 	pr_info("md: Autodetecting RAID arrays.\n");
9871 
9872 	mutex_lock(&detected_devices_mutex);
9873 	while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
9874 		i_scanned++;
9875 		node_detected_dev = list_entry(all_detected_devices.next,
9876 					struct detected_devices_node, list);
9877 		list_del(&node_detected_dev->list);
9878 		dev = node_detected_dev->dev;
9879 		kfree(node_detected_dev);
9880 		mutex_unlock(&detected_devices_mutex);
9881 		rdev = md_import_device(dev,0, 90);
9882 		mutex_lock(&detected_devices_mutex);
9883 		if (IS_ERR(rdev))
9884 			continue;
9885 
9886 		if (test_bit(Faulty, &rdev->flags))
9887 			continue;
9888 
9889 		set_bit(AutoDetected, &rdev->flags);
9890 		list_add(&rdev->same_set, &pending_raid_disks);
9891 		i_passed++;
9892 	}
9893 	mutex_unlock(&detected_devices_mutex);
9894 
9895 	pr_debug("md: Scanned %d and added %d devices.\n", i_scanned, i_passed);
9896 
9897 	autorun_devices(part);
9898 }
9899 
9900 #endif /* !MODULE */
9901 
9902 static __exit void md_exit(void)
9903 {
9904 	struct mddev *mddev, *n;
9905 	int delay = 1;
9906 
9907 	unregister_blkdev(MD_MAJOR,"md");
9908 	unregister_blkdev(mdp_major, "mdp");
9909 	unregister_reboot_notifier(&md_notifier);
9910 	unregister_sysctl_table(raid_table_header);
9911 
9912 	/* We cannot unload the modules while some process is
9913 	 * waiting for us in select() or poll() - wake them up
9914 	 */
9915 	md_unloading = 1;
9916 	while (waitqueue_active(&md_event_waiters)) {
9917 		/* not safe to leave yet */
9918 		wake_up(&md_event_waiters);
9919 		msleep(delay);
9920 		delay += delay;
9921 	}
9922 	remove_proc_entry("mdstat", NULL);
9923 
9924 	spin_lock(&all_mddevs_lock);
9925 	list_for_each_entry_safe(mddev, n, &all_mddevs, all_mddevs) {
9926 		if (!mddev_get(mddev))
9927 			continue;
9928 		spin_unlock(&all_mddevs_lock);
9929 		export_array(mddev);
9930 		mddev->ctime = 0;
9931 		mddev->hold_active = 0;
9932 		/*
9933 		 * As the mddev is now fully clear, mddev_put will schedule
9934 		 * the mddev for destruction by a workqueue, and the
9935 		 * destroy_workqueue() below will wait for that to complete.
9936 		 */
9937 		mddev_put(mddev);
9938 		spin_lock(&all_mddevs_lock);
9939 	}
9940 	spin_unlock(&all_mddevs_lock);
9941 
9942 	destroy_workqueue(md_rdev_misc_wq);
9943 	destroy_workqueue(md_misc_wq);
9944 	destroy_workqueue(md_wq);
9945 }
9946 
9947 subsys_initcall(md_init);
9948 module_exit(md_exit)
9949 
9950 static int get_ro(char *buffer, const struct kernel_param *kp)
9951 {
9952 	return sprintf(buffer, "%d\n", start_readonly);
9953 }
9954 static int set_ro(const char *val, const struct kernel_param *kp)
9955 {
9956 	return kstrtouint(val, 10, (unsigned int *)&start_readonly);
9957 }
9958 
9959 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
9960 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
9961 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
9962 module_param(create_on_open, bool, S_IRUSR|S_IWUSR);
9963 
9964 MODULE_LICENSE("GPL");
9965 MODULE_DESCRIPTION("MD RAID framework");
9966 MODULE_ALIAS("md");
9967 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);
9968