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