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