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