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