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