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