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