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