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