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