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