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