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